local-operator-ui 0.52.7 → 0.52.9
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 +368 -30
- package/out/renderer/assets/{_basePickBy-Cn6QfSqv.js → _basePickBy-BG2VhiIr.js} +1 -1
- package/out/renderer/assets/{_baseUniq-DvtjRZBO.js → _baseUniq-G4ujmd2X.js} +1 -1
- package/out/renderer/assets/{agent-details-page-Bxrn_AT6.js → agent-details-page-CGBPck3M.js} +1 -1
- package/out/renderer/assets/agent-hub-page-oNcQi-BL.js +7 -0
- package/out/renderer/assets/{agents-page-BFDBD9AA.js → agents-page-BM9GCJql.js} +3 -3
- package/out/renderer/assets/{appearance-CdmD45BF.js → appearance-B-Sdp9IA.js} +36 -36
- package/out/renderer/assets/{approvalsOverlay-BEPoTGeb.js → approvalsOverlay-CT-lsZQd.js} +1 -1
- package/out/renderer/assets/{arc-DkFGP-FZ.js → arc-BN6jtH3A.js} +1 -1
- package/out/renderer/assets/{architectureDiagram-IEHRJDOE-CJxjagYN.js → architectureDiagram-IEHRJDOE-DsuIeLu0.js} +1 -1
- package/out/renderer/assets/{avatar-cropper-Dz0ipbuz.js → avatar-cropper-DlNZ1v12.js} +1 -1
- package/out/renderer/assets/{blockDiagram-JOT3LUYC-BX-DQQld.js → blockDiagram-JOT3LUYC-DJvSMoVj.js} +1 -1
- package/out/renderer/assets/{book-open-B_tNY4KA.js → book-open-Cp8uKo-d.js} +1 -1
- package/out/renderer/assets/browser-page-onX8FqEA.js +1 -0
- package/out/renderer/assets/{browser-webauthn-prompt-GZSUrY94.js → browser-webauthn-prompt-CHryNF4a.js} +1 -1
- package/out/renderer/assets/{building-2-S91Q-HFt.js → building-2-DjXAKQ-_.js} +1 -1
- package/out/renderer/assets/{c4Diagram-VJAJSXHY-BtqbckVB.js → c4Diagram-VJAJSXHY-BxuD4dqm.js} +1 -1
- package/out/renderer/assets/channel-Dpjqf8Pr.js +1 -0
- package/out/renderer/assets/{chunk-4BMEZGHF-CxrhkLzw.js → chunk-4BMEZGHF-B-9ZkOo4.js} +1 -1
- package/out/renderer/assets/{chunk-A2AXSNBT-BH6_YcXd.js → chunk-A2AXSNBT-DYX_2Wnw.js} +1 -1
- package/out/renderer/assets/{chunk-AEK57VVT-BfSHypbQ.js → chunk-AEK57VVT-Bt8NwGtc.js} +1 -1
- package/out/renderer/assets/{chunk-D6G4REZN-CEf3Ob5y.js → chunk-D6G4REZN-Cgk8iMci.js} +1 -1
- package/out/renderer/assets/{chunk-RZ5BOZE2-B1oObDF1.js → chunk-RZ5BOZE2-BjDeLAwH.js} +1 -1
- package/out/renderer/assets/{chunk-XZIHB7SX-NzAsvJnk.js → chunk-XZIHB7SX-PPlj1JKr.js} +1 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-Bd3jAzCq.js +1 -0
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-Bd3jAzCq.js +1 -0
- package/out/renderer/assets/clone-BgtnSptX.js +1 -0
- package/out/renderer/assets/{console-mirror-B21mv5xh.js → console-mirror-Icddfzc5.js} +14 -14
- package/out/renderer/assets/{consoleCapture-DbuMCHv1.js → consoleCapture-D0hv_YWG.js} +1 -1
- package/out/renderer/assets/{conversation-input-sync-OWxmq4zX.js → conversation-input-sync-D9Xccwx1.js} +4 -4
- package/out/renderer/assets/{dagre-OKDRZEBW-TI8wrMwZ.js → dagre-OKDRZEBW-YoenwJF-.js} +1 -1
- package/out/renderer/assets/{diagram-SSKATNLV-DiuvjlIQ.js → diagram-SSKATNLV-BxRRTg9E.js} +1 -1
- package/out/renderer/assets/{diagram-VNBRO52H-SBCP7W0-.js → diagram-VNBRO52H-CwmxlyUn.js} +1 -1
- package/out/renderer/assets/{erDiagram-Q7BY3M3F-Be-kevat.js → erDiagram-Q7BY3M3F-10_uYtjI.js} +1 -1
- package/out/renderer/assets/{error-boundary-iNbBBB3v.js → error-boundary-DfFcgZm0.js} +1 -1
- package/out/renderer/assets/{flowDiagram-4HSFHLVR-ChKlZnvv.js → flowDiagram-4HSFHLVR-BIi6hVks.js} +1 -1
- package/out/renderer/assets/{ganttDiagram-APWFNJXF-m7hdnycR.js → ganttDiagram-APWFNJXF-D_OgK0jY.js} +1 -1
- package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-CHmzBlmf.js → gitGraphDiagram-7IBYFJ6S-DL22eEyk.js} +1 -1
- package/out/renderer/assets/{graph-BGrC6Hfx.js → graph-BD4wR-0f.js} +1 -1
- package/out/renderer/assets/{heart-DMfZg11o.js → heart-bD3ezZjX.js} +1 -1
- package/out/renderer/assets/{index-qz7T7xAV.js → index-C5MuLj2j.js} +1 -1
- package/out/renderer/assets/{index-D-BaobqX.js → index-CSQMTsGZ.js} +1 -1
- package/out/renderer/assets/{index-DoVjJu6F.js → index-CVc_oCb8.js} +1 -1
- package/out/renderer/assets/{index-5nnHkCvU.js → index-zeRfNJaS.js} +3 -3
- package/out/renderer/assets/infoDiagram-PH2N3AL5-M2sSQges.js +2 -0
- package/out/renderer/assets/{installer-CVV6WR5Y.js → installer-Ddkg6-C5.js} +1 -1
- package/out/renderer/assets/{journeyDiagram-U35MCT3I-C0KHA5Fo.js → journeyDiagram-U35MCT3I-ClJJE5-O.js} +1 -1
- package/out/renderer/assets/{kanban-definition-NDS4AKOZ-D5LqjQe3.js → kanban-definition-NDS4AKOZ-Vmh-ffzp.js} +1 -1
- package/out/renderer/assets/{layout-CofsTb_n.js → layout-viZOtHI3.js} +1 -1
- package/out/renderer/assets/{legacy-agents-page-RoKJOLAC.js → legacy-agents-page-CUK9HFM4.js} +1 -1
- package/out/renderer/assets/{library-page-D364qPaH.js → library-page-d7jnJ1cM.js} +3 -3
- package/out/renderer/assets/{log-in-BMURtcLk.js → log-in-DRqGQiMM.js} +1 -1
- package/out/renderer/assets/{mermaid.core-CRutHT7B.js → mermaid.core-ZnA0Lmkj.js} +5 -5
- package/out/renderer/assets/{mesh-page-CNqutPsU.js → mesh-page-C972n1XX.js} +1 -1
- package/out/renderer/assets/{messages-CjI8V3o6.js → messages-BdH-KMeX.js} +10 -10
- package/out/renderer/assets/{mindmap-definition-ALO5MXBD-BMHv6mmG.js → mindmap-definition-ALO5MXBD-oyMq2Ffx.js} +1 -1
- package/out/renderer/assets/{mini-hQqzZmLY.js → mini-XTqXeT0x.js} +1 -1
- package/out/renderer/assets/{notebook-pen-B9De8HRk.js → notebook-pen-CgBQhdFa.js} +1 -1
- package/out/renderer/assets/{notifications-page-DnRTPmsg.js → notifications-page-C0pIdEuW.js} +1 -1
- package/out/renderer/assets/{org-access-CSvWotkU.js → org-access-D_YDOtGr.js} +1 -1
- package/out/renderer/assets/{org-surface-gate-D1cQMCPq.js → org-surface-gate-BRBzEvbn.js} +1 -1
- package/out/renderer/assets/{page-header-FRvAuVa5.js → page-header-Bz2lz4LI.js} +1 -1
- package/out/renderer/assets/{pieDiagram-IB7DONF6-B3dl8PAh.js → pieDiagram-IB7DONF6-CJ7Aytd-.js} +1 -1
- package/out/renderer/assets/{project-markdown-B6i3hW9x.js → project-markdown-DYciqMBs.js} +1 -1
- package/out/renderer/assets/{projects-page-DbLor3Wq.js → projects-page-JmH0vUnI.js} +1 -1
- package/out/renderer/assets/{publication-validation-CcVpgrCU.js → publication-validation-quCeNj-v.js} +1 -1
- package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-BNCSmGNZ.js → quadrantDiagram-7GDLP6J5-CLPvPjaT.js} +1 -1
- package/out/renderer/assets/{radar-MK3ICKWK-CjpC5GXo.js → radar-MK3ICKWK-Dl4nMpzG.js} +1 -1
- package/out/renderer/assets/{radient-auth-buttons-r1SLaVYS.js → radient-auth-buttons-DKI9Bh07.js} +1 -1
- package/out/renderer/assets/{requirementDiagram-KVF5MWMF-b-bdNYve.js → requirementDiagram-KVF5MWMF-B3VtoeFm.js} +1 -1
- package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-Bk2jSYW-.js → sankeyDiagram-QLVOVGJD-D0ll6mUD.js} +1 -1
- package/out/renderer/assets/{schedules-page-DkoUCdGL.js → schedules-page-Bj-EKraP.js} +1 -1
- package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-CrWu9Act.js → sequenceDiagram-X6HHIX6F-DI1TMyGm.js} +1 -1
- package/out/renderer/assets/{settings-page-DS-Emp0f.js → settings-page-DTjdJ7Xe.js} +15 -15
- package/out/renderer/assets/{smartart-Dt5OHgL0.js → smartart-89hlq0Z-.js} +1 -1
- package/out/renderer/assets/{stateDiagram-DGXRK772-CPEB-zup.js → stateDiagram-DGXRK772-AlwHo7F1.js} +1 -1
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-BMk0V1sn.js +1 -0
- package/out/renderer/assets/{team-bridge-page-BYsUTX6d.js → team-bridge-page-vIR1dP5K.js} +1 -1
- package/out/renderer/assets/{team-bridge-scope-preference-DarSp0-H.js → team-bridge-scope-preference-Dlf6h_m5.js} +1 -1
- package/out/renderer/assets/{timeline-definition-BDJGKUSR-DRCjj8mV.js → timeline-definition-BDJGKUSR-B7rXhxSU.js} +1 -1
- package/out/renderer/assets/{use-download-agent-mutation-D0VLYK_u.js → use-download-agent-mutation-DPsC_HGf.js} +1 -1
- package/out/renderer/assets/{use-session-snapshot-CwV-f4ml.js → use-session-snapshot-DO0nbiYH.js} +1 -1
- package/out/renderer/assets/{xychartDiagram-VJFVF3MP-DY5NVy6E.js → xychartDiagram-VJFVF3MP-B5a0ZuzY.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 +6 -2
- package/out/renderer/assets/agent-hub-page-CI0_3cgV.js +0 -7
- package/out/renderer/assets/browser-page-BHpD48Cg.js +0 -1
- package/out/renderer/assets/channel-Qv6Kv9n_.js +0 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-ja7Pq_F9.js +0 -1
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-ja7Pq_F9.js +0 -1
- package/out/renderer/assets/clone-bejLhD1C.js +0 -1
- package/out/renderer/assets/infoDiagram-PH2N3AL5-CjGQEcoF.js +0 -2
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-Ds89SmF1.js +0 -1
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
import{r as x,j as Tg,b as Wl,D as Cg,l as bc,m as jf,n as vc,o as Og}from"./index-qz7T7xAV.js";import{c as mn,t as _,a as Pg}from"./messages-CjI8V3o6.js";import{P as Mg,i as yc,a as wc,p as $f}from"./roles-D1pcbxAx.js";const Gl=new Map,zl=new Map,Kl=new Map,Vl=new Map;function kc(e){return e===void 0?"":JSON.stringify(e)}function Sc(e,t){const n=`${e}\0${kc(t)}`;let r=Gl.get(n);return r===void 0&&(r=new Intl.DateTimeFormat(e,t),Gl.set(n,r)),r}function jg(e,t){const n=`${e}\0${kc(t)}`;let r=zl.get(n);return r===void 0&&(r=new Intl.NumberFormat(e,t),zl.set(n,r)),r}function BC(e,t,n){return Sc(n??mn(),t).format(e)}function HC(e,t,n){return Sc(n??mn(),t).format(e)}function WC(e,t,n){return Sc(n??mn(),t).format(e)}function GC(e,t,n){return jg(n??mn(),t).format(e)}function zC(e,t,n,r){const o=r??mn(),s=`${o}\0${kc(n)}`;let a=Kl.get(s);return a===void 0&&(a=new Intl.RelativeTimeFormat(o,n),Kl.set(s,a)),a.format(e,t)}function ws(e,t){const n=mn();let r=Vl.get(n);return r===void 0&&(r=new Intl.ListFormat(n,{type:"conjunction",style:"narrow"}),Vl.set(n,r)),r.format(e)}const $g={zh:";",ja:";",ur:"؛ ",ar:"؛ "};function KC(e,t){const n=mn().split("-")[0]?.toLowerCase();return e.join($g[n??""]??"; ")}var Ho=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(){}},tr=typeof window>"u"||"Deno"in globalThis;function It(){}function Dg(e,t){return typeof e=="function"?e(t):e}function ha(e){return typeof e=="number"&&e>=0&&e!==1/0}function Df(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Er(e,t){return typeof e=="function"?e(t):e}function Ut(e,t){return typeof e=="function"?e(t):e}function Zl(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:s,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==Ec(a,t.options))return!1}else if(!_o(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 Yl(e,t){const{exact:n,status:r,predicate:o,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(go(t.options.mutationKey)!==go(s))return!1}else if(!_o(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Ec(e,t){return(t?.queryKeyHashFn||go)(e)}function go(e){return JSON.stringify(e,(t,n)=>ga(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function _o(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>_o(e[n],t[n])):!1}function Nf(e,t){if(e===t)return e;const n=Ql(e)&&Ql(t);if(n||ga(e)&&ga(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]=Nf(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return o===a&&l===o?e:c}return t}function ma(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 Ql(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ga(e){if(!Xl(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Xl(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Xl(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ng(e){return new Promise(t=>{setTimeout(t,e)})}function _a(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Nf(e,t):t}function Lg(e){return e}function Fg(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Ug(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ac=Symbol();function Lf(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ac?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Bg=class extends Ho{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!tr&&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"}},Rc=new Bg,Hg=class extends Ho{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!tr&&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}},Cs=new Hg;function ba(){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 Wg(e){return Math.min(1e3*2**e,3e4)}function Ff(e){return(e??"online")==="online"?Cs.isOnline():!0}var Uf=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function xi(e){return e instanceof Uf}function Bf(e){let t=!1,n=0,r=!1,o;const s=ba(),a=b=>{r||(h(new Uf(b)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>Rc.isFocused()&&(e.networkMode==="always"||Cs.isOnline())&&e.canRun(),u=()=>Ff(e.networkMode)&&e.canRun(),f=b=>{r||(r=!0,e.onSuccess?.(b),o?.(),s.resolve(b))},h=b=>{r||(r=!0,e.onError?.(b),o?.(),s.reject(b))},m=()=>new Promise(b=>{o=v=>{(r||d())&&b(v)},e.onPause?.()}).then(()=>{o=void 0,r||e.onContinue?.()}),y=()=>{if(r)return;let b;const v=n===0?e.initialPromise:void 0;try{b=v??e.fn()}catch(p){b=Promise.reject(p)}Promise.resolve(b).then(f).catch(p=>{if(r)return;const E=e.retry??(tr?0:3),k=e.retryDelay??Wg,C=typeof k=="function"?k(n,p):k,N=E===!0||typeof E=="number"&&n<E||typeof E=="function"&&E(n,p);if(t||!N){h(p);return}n++,e.onFail?.(n,p),Ng(C).then(()=>d()?void 0:m()).then(()=>{t?h(p):y()})})};return{promise:s,cancel:a,continue:()=>(o?.(),s),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?y():m().then(y),s)}}var Gg=e=>setTimeout(e,0);function zg(){let e=[],t=0,n=c=>{c()},r=c=>{c()},o=Gg;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=zg(),Hf=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ha(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(tr?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},Kg=class extends Hf{#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=Vg(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=_a(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(It).catch(It):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>Ut(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ac||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||!Df(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=Lf(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=>{xi(c)&&c.silent||this.#s({type:"error",error:c}),xi(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#o=Bf({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,...Wf(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 xi(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 Wf(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ff(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Vg(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 Zg=class extends Ho{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,o=t.queryHash??Ec(r,t);let s=this.get(o);return s||(s=new Kg({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=>Zl(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Zl(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()})})}},Yg=class extends Hf{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||Qg(),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=Bf({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 Qg(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Xg=class extends Ho{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 Yg({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=es(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=es(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=es(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=es(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=>Yl(t,n))}findAll(e={}){return this.getAll().filter(t=>Yl(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(It))))}};function es(e){return e.options.scope?.id}function Jl(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=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},h=Lf(t.options,t.fetchOptions),m=async(y,b,v)=>{if(u)return Promise.reject();if(b==null&&y.pages.length)return Promise.resolve(y);const p={client:t.client,queryKey:t.queryKey,pageParam:b,direction:v?"backward":"forward",meta:t.options.meta};f(p);const E=await h(p),{maxPages:k}=t.options,C=v?Ug:Fg;return{pages:C(y.pages,E,k),pageParams:C(y.pageParams,b,k)}};if(o&&s.length){const y=o==="backward",b=y?Gf:va,v={pages:s,pageParams:a},p=b(r,v);c=await m(v,p,y)}else{const y=e??s.length;do{const b=l===0?a[0]??r.initialPageParam:va(r,c);if(l>0&&b==null)break;c=await m(c,b),l++}while(l<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function va(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 Gf(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function VC(e,t){return t?va(e,t)!=null:!1}function ZC(e,t){return!t||!e.getPreviousPageParam?!1:Gf(e,t)!=null}var Jg=class{#t;#e;#n;#r;#o;#a;#i;#s;constructor(e={}){this.#t=e.queryCache||new Zg,this.#e=e.mutationCache||new Xg,this.#n=e.defaultOptions||{},this.#r=new Map,this.#o=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#i=Rc.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#s=Cs.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(Er(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=Dg(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(It).catch(It)}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(It)),o.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(It)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(Er(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(It).catch(It)}fetchInfiniteQuery(e){return e.behavior=Jl(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(It).catch(It)}ensureInfiniteQueryData(e){return e.behavior=Jl(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Cs.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(go(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{_o(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#o.set(go(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(r=>{_o(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Ec(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ac&&(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()}},qg=class extends Ho{constructor(e,t){super(),this.options=t,this.#t=e,this.#s=null,this.#i=ba(),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),ql(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ya(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ya(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 Ut(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&&!ma(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&ed(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||Ut(this.options.enabled,this.#e)!==Ut(t.enabled,this.#e)||Er(this.options.staleTime,this.#e)!==Er(t.staleTime,this.#e))&&this.#g();const o=this.#_();r&&(this.#e!==n||Ut(this.options.enabled,this.#e)!==Ut(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 t_(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(It)),t}#g(){this.#y();const e=Er(this.options.staleTime,this.#e);if(tr||this.#r.isStale||!ha(e))return;const n=Df(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,!(tr||Ut(this.options.enabled,this.#e)===!1||!ha(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||Rc.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&&ql(e,t),S=g&&ed(e,n,t,r);(w||S)&&(u={...u,...Wf(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:b}=u;h=u.data;let v=!1;if(t.placeholderData!==void 0&&h===void 0&&b==="pending"){let g;o?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(g=o.data,v=!0):g=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,g!==void 0&&(b="success",h=_a(o?.data,g,t),f=!0)}if(t.select&&h!==void 0&&!v)if(o&&h===s?.data&&t.select===this.#m)h=this.#f;else try{this.#m=t.select,h=t.select(h),h=_a(o?.data,h,t),this.#f=h,this.#s=null}catch(g){this.#s=g}this.#s&&(m=this.#s,h=this.#f,y=Date.now(),b="error");const p=u.fetchStatus==="fetching",E=b==="pending",k=b==="error",C=E&&p,N=h!==void 0,R={status:b,fetchStatus:u.fetchStatus,isPending:E,isSuccess:b==="success",isError:k,isInitialLoading:C,isLoading:C,data:h,dataUpdatedAt:u.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:p,isRefetching:p&&!E,isLoadingError:k&&!N,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:k&&N,isStale:xc(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=ba();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),ma(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 e_(e,t){return Ut(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function ql(e,t){return e_(e,t)||e.state.data!==void 0&&ya(e,t,t.refetchOnMount)}function ya(e,t,n){if(Ut(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&xc(e,t)}return!1}function ed(e,t,n,r){return(e!==t||Ut(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&xc(e,n)}function xc(e,t){return Ut(t.enabled,e)!==!1&&e.isStaleByTime(Er(t.staleTime,e))}function t_(e,t){return!ma(e.getCurrentResult(),t)}var Ic=x.createContext(void 0),n_=e=>{const t=x.useContext(Ic);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]),Tg.jsx(Ic.Provider,{value:e,children:t})),zf=x.createContext(!1),r_=()=>x.useContext(zf);zf.Provider;function o_(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var s_=x.createContext(o_()),i_=()=>x.useContext(s_);function a_(e,t){return typeof e=="function"?e(...t):!!e}function td(){}var c_=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},l_=e=>{x.useEffect(()=>{e.clearReset()},[e])},d_=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(o&&e.data===void 0||a_(n,[e.error,r])),u_=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)))},f_=(e,t)=>e.isLoading&&e.isFetching&&!t,p_=(e,t)=>e?.suspense&&t.isPending,nd=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function h_(e,t,n){const r=n_(n),o=r_(),s=i_(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=o?"isRestoring":"optimistic",u_(a),c_(a,s),l_(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)):td;return l.updateResult(),h},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),x.useEffect(()=>{l.setOptions(a)},[a,l]),p_(a,d))throw nd(a,l,s);if(d_({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&&!tr&&f_(d,o)&&(c?nd(a,l,s):r.getQueryCache().get(a.queryHash)?.promise)?.catch(td).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function Kf(e,t){return h_(e,qg,t)}const m_=()=>{const e=x.useContext(Ic)??null,t=x.useMemo(()=>new Jg({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 QC(e){return e!=="detached"&&e!=="wedged"}function Vf(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function XC(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=Vf(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 wa;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(wa||(wa={}));const B=ve.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),an=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"]),g_=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Et 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 Et))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()}}Et.create=e=>new Et(e);const Cr=(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 Zf=Cr;function __(e){Zf=e}function Os(){return Zf}const Ps=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}},b_=[];function U(e,t){const n=Os(),r=Ps({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Cr?void 0:Cr].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"}),yr=e=>({status:"dirty",value:e}),dt=e=>({status:"valid",value:e}),ka=e=>e.status==="aborted",Sa=e=>e.status==="dirty",nr=e=>e.status==="valid",bo=e=>typeof Promise<"u"&&e instanceof Promise;function Ms(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 Yf(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 no,ro;class qt{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 rd=(e,t)=>{if(nr(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 Et(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 an(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:an(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:an(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(bo(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:an(t)},s=this._parseSync({data:t,path:o.path,parent:o});return rd(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:an(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:o});return nr(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=>nr(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:an(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(bo(o)?o:Promise.resolve(o));return rd(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 Gt({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 Xt.create(this,this._def)}nullable(){return Mn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Wt.create(this)}promise(){return Pr.create(this,this._def)}or(t){return ko.create([this,t],this._def)}and(t){return So.create(this,t,this._def)}transform(t){return new Gt({...ce(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Io({...ce(this._def),innerType:this,defaultValue:n,typeName:X.ZodDefault})}brand(){return new Tc({typeName:X.ZodBranded,type:this,...ce(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new To({...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 Wo.create(this,t)}readonly(){return Co.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const v_=/^c[^\s-]{8,}$/i,y_=/^[0-9a-z]+$/,w_=/^[0-9A-HJKMNP-TV-Z]{26}$/i,k_=/^[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,S_=/^[a-z0-9_-]{21}$/i,E_=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,A_=/^[-+]?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)?)??$/,R_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,x_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ii;const I_=/^(?:(?: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])$/,T_=/^(?:(?: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])$/,C_=/^(([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]))$/,O_=/^(([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])$/,P_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,M_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qf="((\\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])))",j_=new RegExp(`^${Qf}$`);function Xf(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 $_(e){return new RegExp(`^${Xf(e)}$`)}function Jf(e){let t=`${Qf}T${Xf(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 D_(e,t){return!!((t==="v4"||!t)&&I_.test(e)||(t==="v6"||!t)&&C_.test(e))}function N_(e,t){if(!E_.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 L_(e,t){return!!((t==="v4"||!t)&&T_.test(e)||(t==="v6"||!t)&&O_.test(e))}class Ht 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")R_.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")Ii||(Ii=new RegExp(x_,"u")),Ii.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")k_.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")S_.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")v_.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")y_.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")w_.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"?Jf(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"?j_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?$_(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"?A_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"duration",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?D_(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"?N_(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"?L_(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"?P_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?M_.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 Ht({...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 Ht({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ht({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ht({...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}}Ht.create=e=>{var t;return new Ht({checks:[],typeName:X.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};function F_(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 Cn 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"?F_(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 Cn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new Cn({...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)}}Cn.create=e=>new Cn({checks:[],typeName:X.ZodNumber,coerce:e?.coerce||!1,...ce(e)});class On 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 On({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new On({...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}}On.create=e=>{var t;return new On({checks:[],typeName:X.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};class vo 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)}}vo.create=e=>new vo({typeName:X.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});class rr 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 rr({...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}}rr.create=e=>new rr({checks:[],coerce:e?.coerce||!1,typeName:X.ZodDate,...ce(e)});class js 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)}}js.create=e=>new js({typeName:X.ZodSymbol,...ce(e)});class yo 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)}}yo.create=e=>new yo({typeName:X.ZodUndefined,...ce(e)});class wo 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)}}wo.create=e=>new wo({typeName:X.ZodNull,...ce(e)});class Or extends le{constructor(){super(...arguments),this._any=!0}_parse(t){return dt(t.data)}}Or.create=e=>new Or({typeName:X.ZodAny,...ce(e)});class Yn extends le{constructor(){super(...arguments),this._unknown=!0}_parse(t){return dt(t.data)}}Yn.create=e=>new Yn({typeName:X.ZodUnknown,...ce(e)});class un extends le{_parse(t){const n=this._getOrReturnCtx(t);return U(n,{code:j.invalid_type,expected:B.never,received:n.parsedType}),J}}un.create=e=>new un({typeName:X.ZodNever,...ce(e)});class $s 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)}}$s.create=e=>new $s({typeName:X.ZodVoid,...ce(e)});class Wt 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 qt(n,a,n.path,c)))).then(a=>lt.mergeArray(r,a));const s=[...n.data].map((a,c)=>o.type._parseSync(new qt(n,a,n.path,c)));return lt.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new Wt({...this._def,minLength:{value:t,message:K.toString(n)}})}max(t,n){return new Wt({...this._def,maxLength:{value:t,message:K.toString(n)}})}length(t,n){return new Wt({...this._def,exactLength:{value:t,message:K.toString(n)}})}nonempty(t){return this.min(1,t)}}Wt.create=(e,t)=>new Wt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...ce(t)});function hr(e){if(e instanceof Ue){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Xt.create(hr(r))}return new Ue({...e._def,shape:()=>t})}else return e instanceof Wt?new Wt({...e._def,type:hr(e.element)}):e instanceof Xt?Xt.create(hr(e.unwrap())):e instanceof Mn?Mn.create(hr(e.unwrap())):e instanceof en?en.create(e.items.map(t=>hr(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 un&&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 qt(o,f,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof un){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 qt(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 hr(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 Xt;)s=s._def.innerType;n[r]=s}}),new Ue({...this._def,shape:()=>n})}keyof(){return qf(ve.objectKeys(this.shape))}}Ue.create=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strip",catchall:un.create(),typeName:X.ZodObject,...ce(t)});Ue.strictCreate=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strict",catchall:un.create(),typeName:X.ZodObject,...ce(t)});Ue.lazycreate=(e,t)=>new Ue({shape:e,unknownKeys:"strip",catchall:un.create(),typeName:X.ZodObject,...ce(t)});class ko 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 Et(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 Et(l));return U(n,{code:j.invalid_union,unionErrors:c}),J}}get options(){return this._def.options}}ko.create=(e,t)=>new ko({options:e,typeName:X.ZodUnion,...ce(t)});const rn=e=>e instanceof Ao?rn(e.schema):e instanceof Gt?rn(e.innerType()):e instanceof Ro?[e.value]:e instanceof Pn?e.options:e instanceof xo?ve.objectValues(e.enum):e instanceof Io?rn(e._def.innerType):e instanceof yo?[void 0]:e instanceof wo?[null]:e instanceof Xt?[void 0,...rn(e.unwrap())]:e instanceof Mn?[null,...rn(e.unwrap())]:e instanceof Tc||e instanceof Co?rn(e.unwrap()):e instanceof To?rn(e._def.innerType):[];class oi 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=rn(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 oi({typeName:X.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...ce(r)})}}function Ea(e,t){const n=an(e),r=an(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=Ea(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=Ea(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 So extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(s,a)=>{if(ka(s)||ka(a))return J;const c=Ea(s.value,a.value);return c.valid?((Sa(s)||Sa(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}))}}So.create=(e,t,n)=>new So({left:e,right:t,typeName:X.ZodIntersection,...ce(n)});class en 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 qt(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 en({...this._def,rest:t})}}en.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new en({items:e,typeName:X.ZodTuple,rest:null,...ce(t)})};class Eo 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 qt(r,c,r.path,c)),value:a._parse(new qt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?lt.mergeObjectAsync(n,o):lt.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof le?new Eo({keyType:t,valueType:n,typeName:X.ZodRecord,...ce(r)}):new Eo({keyType:Ht.create(),valueType:t,typeName:X.ZodRecord,...ce(n)})}}class Ds 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 qt(r,c,r.path,[d,"key"])),value:s._parse(new qt(r,l,r.path,[d,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of a){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return 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}}}}Ds.create=(e,t,n)=>new Ds({valueType:t,keyType:e,typeName:X.ZodMap,...ce(n)});class or 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 qt(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new or({...this._def,minSize:{value:t,message:K.toString(n)}})}max(t,n){return new or({...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)}}or.create=(e,t)=>new or({valueType:e,minSize:null,maxSize:null,typeName:X.ZodSet,...ce(t)});class Ar 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 Ps({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Os(),Cr].filter(d=>!!d),issueData:{code:j.invalid_arguments,argumentsError:l}})}function o(c,l){return Ps({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Os(),Cr].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 Pr){const c=this;return dt(async function(...l){const d=new Et([]),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 Et([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,s);if(!f.success)throw new Et([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Ar({...this._def,args:en.create(t).rest(Yn.create())})}returns(t){return new Ar({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Ar({args:t||en.create([]).rest(Yn.create()),returns:n||Yn.create(),typeName:X.ZodFunction,...ce(r)})}}class Ao 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})}}Ao.create=(e,t)=>new Ao({getter:e,typeName:X.ZodLazy,...ce(t)});class Ro 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}}Ro.create=(e,t)=>new Ro({value:e,typeName:X.ZodLiteral,...ce(t)});function qf(e,t){return new Pn({values:e,typeName:X.ZodEnum,...ce(t)})}class Pn extends le{constructor(){super(...arguments),no.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(Ms(this,no)||Yf(this,no,new Set(this._def.values)),!Ms(this,no).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 Pn.create(t,{...this._def,...n})}exclude(t,n=this._def){return Pn.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}no=new WeakMap;Pn.create=qf;class xo extends le{constructor(){super(...arguments),ro.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(Ms(this,ro)||Yf(this,ro,new Set(ve.getValidEnumValues(this._def.values))),!Ms(this,ro).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}}ro=new WeakMap;xo.create=(e,t)=>new xo({values:e,typeName:X.ZodNativeEnum,...ce(t)});class Pr 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})))}}Pr.create=(e,t)=>new Pr({type:e,typeName:X.ZodPromise,...ce(t)});class Gt 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"?yr(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"?yr(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(!nr(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=>nr(a)?Promise.resolve(o.transform(a.value,s)).then(c=>({status:n.value,value:c})):a);ve.assertNever(o)}}Gt.create=(e,t,n)=>new Gt({schema:e,typeName:X.ZodEffects,effect:t,...ce(n)});Gt.createWithPreprocess=(e,t,n)=>new Gt({schema:t,effect:{type:"preprocess",transform:e},typeName:X.ZodEffects,...ce(n)});class Xt extends le{_parse(t){return this._getType(t)===B.undefined?dt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Xt.create=(e,t)=>new Xt({innerType:e,typeName:X.ZodOptional,...ce(t)});class Mn extends le{_parse(t){return this._getType(t)===B.null?dt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Mn.create=(e,t)=>new Mn({innerType:e,typeName:X.ZodNullable,...ce(t)});class Io 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}}Io.create=(e,t)=>new Io({innerType:e,typeName:X.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});class To 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 bo(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Et(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Et(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}To.create=(e,t)=>new To({innerType:e,typeName:X.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});class Ns 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}}}Ns.create=e=>new Ns({typeName:X.ZodNaN,...ce(e)});const U_=Symbol("zod_brand");class Tc 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 Wo 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(),yr(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 Wo({in:t,out:n,typeName:X.ZodPipeline})}}class Co extends le{_parse(t){const n=this._def.innerType._parse(t),r=o=>(nr(o)&&(o.value=Object.freeze(o.value)),o);return bo(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}Co.create=(e,t)=>new Co({innerType:e,typeName:X.ZodReadonly,...ce(t)});function od(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ep(e,t={},n){return e?Or.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=od(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=od(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})}}):Or.create()}const B_={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 H_=(e,t={message:`Input not instance of ${e.name}`})=>ep(n=>n instanceof e,t),tp=Ht.create,np=Cn.create,W_=Ns.create,G_=On.create,rp=vo.create,z_=rr.create,K_=js.create,V_=yo.create,Z_=wo.create,Y_=Or.create,Q_=Yn.create,X_=un.create,J_=$s.create,q_=Wt.create,eb=Ue.create,tb=Ue.strictCreate,nb=ko.create,rb=oi.create,ob=So.create,sb=en.create,ib=Eo.create,ab=Ds.create,cb=or.create,lb=Ar.create,db=Ao.create,ub=Ro.create,fb=Pn.create,pb=xo.create,hb=Pr.create,sd=Gt.create,mb=Xt.create,gb=Mn.create,_b=Gt.createWithPreprocess,bb=Wo.create,vb=()=>tp().optional(),yb=()=>np().optional(),wb=()=>rp().optional(),kb={string:e=>Ht.create({...e,coerce:!0}),number:e=>Cn.create({...e,coerce:!0}),boolean:e=>vo.create({...e,coerce:!0}),bigint:e=>On.create({...e,coerce:!0}),date:e=>rr.create({...e,coerce:!0})},Sb=J;var i=Object.freeze({__proto__:null,defaultErrorMap:Cr,setErrorMap:__,getErrorMap:Os,makeIssue:Ps,EMPTY_PATH:b_,addIssueToContext:U,ParseStatus:lt,INVALID:J,DIRTY:yr,OK:dt,isAborted:ka,isDirty:Sa,isValid:nr,isAsync:bo,get util(){return ve},get objectUtil(){return wa},ZodParsedType:B,getParsedType:an,ZodType:le,datetimeRegex:Jf,ZodString:Ht,ZodNumber:Cn,ZodBigInt:On,ZodBoolean:vo,ZodDate:rr,ZodSymbol:js,ZodUndefined:yo,ZodNull:wo,ZodAny:Or,ZodUnknown:Yn,ZodNever:un,ZodVoid:$s,ZodArray:Wt,ZodObject:Ue,ZodUnion:ko,ZodDiscriminatedUnion:oi,ZodIntersection:So,ZodTuple:en,ZodRecord:Eo,ZodMap:Ds,ZodSet:or,ZodFunction:Ar,ZodLazy:Ao,ZodLiteral:Ro,ZodEnum:Pn,ZodNativeEnum:xo,ZodPromise:Pr,ZodEffects:Gt,ZodTransformer:Gt,ZodOptional:Xt,ZodNullable:Mn,ZodDefault:Io,ZodCatch:To,ZodNaN:Ns,BRAND:U_,ZodBranded:Tc,ZodPipeline:Wo,ZodReadonly:Co,custom:ep,Schema:le,ZodSchema:le,late:B_,get ZodFirstPartyTypeKind(){return X},coerce:kb,any:Y_,array:q_,bigint:G_,boolean:rp,date:z_,discriminatedUnion:rb,effect:sd,enum:fb,function:lb,instanceof:H_,intersection:ob,lazy:db,literal:ub,map:ab,nan:W_,nativeEnum:pb,never:X_,null:Z_,nullable:gb,number:np,object:eb,oboolean:wb,onumber:yb,optional:mb,ostring:vb,pipeline:bb,preprocess:_b,promise:hb,record:ib,set:cb,strictObject:tb,string:tp,symbol:K_,transformer:sd,tuple:sb,undefined:V_,union:nb,unknown:Q_,void:J_,NEVER:Sb,ZodIssueCode:j,quotelessJson:g_,ZodError:Et});const id=i.enum(["app_start","sign_in","window_focus","surface_open"]),op=i.object({id:i.string().min(1),state:i.enum(["active","paused","disabled"])}).passthrough(),Eb=i.object({tenant_id:i.string().min(1),tenant_name:i.string().optional(),eligible:i.boolean(),endpoint:op.nullable()}).passthrough(),Ab=i.object({code:i.string(),message:i.string(),details:i.record(i.unknown()).optional(),retry_after_seconds:i.number().optional()}).passthrough(),Rb=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),xb=i.object({in_force:i.boolean(),notice_pending:i.boolean().catch(!1)}).passthrough().optional().catch(void 0),JC=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(Eb)}).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:Ab.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:Rb,default_on:xb}).passthrough(),Ib=i.object({version:i.string().min(1),consented_at:i.string().min(1),consented_via:i.string().min(1),current:i.boolean()}).passthrough(),qC=i.object({endpoint:op.extend({tenant_id:i.string().min(1),label:i.string().optional(),consent:Ib.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(),Tb=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"),ad=i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:Tb,id:i.string().optional()}).passthrough(),cd=i.object({mode:i.enum(["class_default","listed_only"]),allow:i.number(),deny:i.number()}).passthrough(),eO=i.object({allowlist:i.object({tenant_id:i.string().min(1),entries:i.array(ad)}).passthrough(),view:i.object({tenant_id:i.string().nullable(),entries:i.array(ad),directions:i.object({send:cd,receive:cd}),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(),tO=i.object({onboarding:i.literal("seen")}).passthrough();function Cb(e){return e?.default_on?.in_force===!0}function nO(e,t){const n=Ob(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function rO(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function oO(e,t){if(!e||!t||Cb(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 Ob(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const Pb=8,Aa=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],Mb=6*1024,jb=512;function Ls(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const o=[];for(const s of n){if(o.length===jb)break;const c=new URLSearchParams({order_ids:s}).toString().length+1;if(r+c>Mb)break;e.append("order_ids",s),o.push(s),r+=c}return o}function $b(e,t,n){return Ls(new URLSearchParams(n),t,e)}const sO=3,Db=4096,iO=128,aO=/^[0-9a-f]{32}$/,Nb=/^\.+$/,Lb=new RegExp("\\p{Cf}","u"),Fb=/[/\\:]/,A=i.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),Ub=i.string().min(1).max(128),ts=i.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),ns=i.string().min(1).max(32768),Bb=/^[a-f0-9]{12}$/,G=i.string().regex(Bb),Ti=i.string().regex(/^[a-f0-9]{12}$/),Ci=i.string().min(1).max(128),Hb=i.string().min(1).max(4096),Hr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),Oi=i.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),rs=i.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),ld=i.string().regex(/^[a-f0-9]{32}$/),Wb=/^(\/|[A-Za-z]:[\\/])/,Pi=i.string().min(1).max(4096).regex(Wb),dd=/^[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}$/),ud=i.string().min(1).max(512).nullish(),ur=i.string().regex(/^[A-Za-z0-9_-]{1,128}$/),Wr=i.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),Gb=["credential_finite_share","credential_inheritance"],Fs=/^sha256:[0-9a-f]{64}$/,fd={operation:i.enum(Gb),requestDigest:i.string().regex(Fs),disclosureDigest:i.string().regex(Fs)},Gr=i.string().regex(/^la_[0-9a-f]{16}$/),zr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),pd=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(),zb=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(),hd=2e5,md=8,Kb=256,Vb=100,gd=16,Zb=256,Yb=100,Qb=200,Xb=1e6,Jb=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)),os=i.object({kind:i.enum(["agent","team"]),name:nt}).strict(),sp=i.enum(["claude","codex","omp"]),qb=i.record(i.string(),i.array(i.string().min(1).max(512)).max(5e3)),_d={sources:i.array(sp).max(3).optional(),sessionIds:qb.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()},Mi=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(),bd=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(),vd=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:Jb.nullable().optional()}).strict()).max(128).optional(),instructions:i.string().max(8e3).optional(),project:i.string().max(8e3).optional()}).strict(),ev=i.record(i.array(i.string().max(1024)).max(100)),ji=i.array(A).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),tv=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"),yd=i.enum(["minutes","hours","days"]);function nv(e){return!Nb.test(e)}const cO=e=>ks.safeParse(e).success,ks=i.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(nv),wd=i.enum(["str","int","float","bool","list","dict"]),kd=i.string().max(16384),rv=2e3,Sd=i.string().min(1).max(rv),Ed=i.string().min(1).max(64),ov=i.string().min(1).max(64),sv=i.string().min(1).max(64),Ad=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(),iv=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(),Ra=128,Rd=2e3,xd=8e3,Id=64,Td=64,si=e=>[...e].length,xa=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,av=e=>e===9||e===10||e===11||e===12||e===13||e===133,cv=e=>e<=31||e>=127&&e<=159,lv=e=>Lb.test(String.fromCodePoint(e)),dv=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,ss=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},ip=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&xa(t[n].codePointAt(0)??0);)n++;for(;r>n&&xa(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},uv=e=>{let t="",n=!1;for(const r of e){if(xa(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function fv(e){const t=ip(e);if(!t)return"must not be empty";if(si(t)>Ra)return`must be at most ${Ra} characters`;if(Fb.test(t))return'must not contain "/", "\\" or ":"';if(ss(t,dv))return"must not contain Unicode bidirectional override characters";if(ss(t,av))return"must not contain whitespace";if(ss(t,cv))return"must not contain control characters";if(ss(t,lv))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 lO(e){return uv(ip(e).normalize("NFKC").toLowerCase())}function pv(e){return e.trim()?si(e)>Rd?`must be at most ${Rd} characters`:null:"must not be empty"}function hv(e){return e.trim()?si(e)>xd?`must be at most ${xd} characters`:null:"must not be empty"}function mv(e){if(e.length>Td)return`must hold at most ${Td} items`;for(const t of e)if(!t.trim()||si(t)>Id)return`must hold items of 1 to ${Id} characters`;return null}const gv=e=>fv(e)===null,_v=i.string().refine(gv,{message:"That is not a name the hub can publish."}),bv=i.string().refine(e=>hv(e)===null,{message:"That instruction body cannot be published."}),vv=i.string().refine(e=>pv(e)===null,{message:"That description cannot be published."}),yv=i.array(i.string()).refine(e=>mv(e)===null,{message:"That tool list cannot be published."}),$i={requestId:ue.optional(),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()},Cd=i.object({name:_v,description:vv,instructions:bv,kind:i.enum(["role","specialist"]),when_to_use:i.string(),tools:yv,effort:i.string(),delegate:i.boolean(),version:i.string(),categories:i.array(i.string()),tags:i.array(i.string())}).partial().strict(),wv=i.enum(["team","agent"]),kv=i.string().min(1).max(64),Sv=i.string().min(1).max(256),ap=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Di=i.string().regex(ap,{message:"Letters, digits, dot, underscore and dash; no spaces."}),Ev=["planning","active","qa","validation","done","paused","archived"],Od=i.enum(Ev),is=i.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),Pd=i.array(i.string().min(1).max(24)).max(8),wn=i.string().min(1).max(64),Av=1e3,Md=240,jd=80,Rv=256,xv=100,Iv=200,Tv=/^[a-z0-9][a-z0-9_-]{0,23}$/;function dO(e){return e?ap.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 uO(e){return Tv.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const as=i.enum(["agent","team","skill"]),Ni=i.string().min(1).max(128).regex(/\S/),$d=i.enum(Aa),Cv=i.object({visible:i.array($d).max(Aa.length),more:i.array($d).max(Aa.length)}).strict(),cn=i.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),Dd=i.object({selectionToken:i.string().min(1).max(512),reconcileIds:i.array(cn).max(500).optional(),excludedIds:i.array(cn).max(500).optional()}).strict(),Ov=i.object({operationToken:i.string().min(1).max(512),reconcileIds:i.array(cn).max(500).optional()}).strict(),Nd=i.union([i.object({throughSeq:i.number().int().min(0).optional(),receipt:i.literal(!0).optional(),reconcileIds:i.array(cn).max(500).optional(),items:i.array(i.object({id:cn,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:cn,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:cn,revision:i.number().int().min(1)}).strict()).max(500)}).strict()]),Pv={pointer:"pointerdown",key:"keydown",wheel:"wheel"},Mv=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:sp,includeSubagents:i.boolean().optional()}).strict(),i.object({op:i.literal("imports.preview"),..._d}).strict(),i.object({op:i.literal("imports.start"),..._d}).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:bd,expectedDefinitionRevision:ud.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:bd.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:as.optional(),name:nt.optional(),localId:Ni.optional()}).strict(),i.object({op:i.literal("hub.apply"),requestId:ue,kind:as.optional(),name:nt.optional(),localId:Ni.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:as.optional()}).strict(),i.object({op:i.literal("hub.retry"),requestId:ue,kind:as.optional(),name:nt.optional(),localId:Ni.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:vd,expectedDefinitionRevision:ud.optional()}).strict(),i.object({op:i.literal("teams.create"),requestId:ue,fields:vd.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:wv.optional(),scope_name:kv.optional(),cursor:Sv.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(Kb),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:os.optional(),purpose:i.literal("agents-config").optional(),model:Mi.optional(),draftId:G.optional(),peer:ur.optional()}).strict(),i.object({op:i.literal("sessions.preview"),requestId:ue,cwd:i.string().min(1).max(4096),target:os.optional(),model:Mi.optional()}).strict(),i.object({op:i.literal("sessions.draft"),requestId:ue,cwd:i.string().min(1).max(4096),target:os.optional(),model:Mi.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(gd).optional(),limit:i.number().int().min(1).max(gd).optional()}).strict(),i.object({op:i.literal("sessions.find"),sessionId:G,q:i.string().min(1).max(Zb),limit:i.number().int().min(1).max(Qb).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(hd),images:i.array(pd).max(md).optional(),files:i.array(zb).max(Pb).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(hd).optional(),images:i.array(pd).max(md).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(dd),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:Ti,anchor:Ci}).strict(),i.object({op:i.literal("supplements.restart"),sessionId:G,job:Ti,anchor:Ci}).strict(),i.object({op:i.literal("supplements.steer"),sessionId:G,job:Ti,anchor:Ci,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:ks,value:kd,type:wd}).strict(),i.object({op:i.literal("sessions.variables.update"),sessionId:G,key:ks,value:kd,type:wd}).strict(),i.object({op:i.literal("sessions.variables.delete"),sessionId:G,key:ks}).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:Cd.optional(),...$i,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:Cd.optional(),...$i,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("team.publish"),teamId:A,...$i,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(Ra)}).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:Ad.extend({prompt:i.string().max(64e3),interval:i.number().int().min(1),unit:yd})}).strict(),i.object({op:i.literal("legacy.schedule.get"),scheduleId:A}).strict(),i.object({op:i.literal("legacy.schedule.edit"),scheduleId:A,schedule:Ad.extend({prompt:i.string().max(64e3).nullish(),interval:i.number().int().min(1).nullish(),unit:yd.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(Xb)}).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:Ub.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:Hb.optional(),name:Hr.optional()}).strict(),i.object({op:i.literal("skills.create"),requestId:ue,name:Hr,copyFrom:Hr}).strict(),i.object({op:i.literal("skills.update"),requestId:ue,name:Hr,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:Hr,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:ts.optional(),value:ns.optional(),confirmed:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.fork"),sessionId:G,requestId:ue,message:i.string().max(2e5).optional(),boundary:i.enum(["next_safe","at_entry"]).optional(),entryId:i.string().max(128).optional(),autoTag:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.stop"),requestId:ue,targets:i.array(G).min(1).max(100),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside"),sessionId:G,requestId:ue,text:i.string().min(1).max(32768),asideId:ue.optional(),subscriptionId:i.string().regex(dd).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:os.optional(),message:Sd,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:Ed,message:Sd.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:Ed}).strict(),i.object({op:i.literal("monitors.cancel"),sessionId:G,monitorId:ov}).strict(),i.object({op:i.literal("jobs.cancel"),sessionId:G,jobId:sv}).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:Oi.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(rs).optional(),url:i.string().max(4096).optional(),headers:i.record(rs).optional(),oauth:i.boolean().optional(),confirmed:i.boolean().optional(),operation_id:ld.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog"),cwd:Pi.optional(),sessionId:G.optional()}).strict(),i.object({op:i.literal("mcp.catalog.control"),cwd:Pi.optional(),control:i.object({action:i.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:Oi.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(rs).optional(),url:i.string().max(4096).optional(),headers:i.record(rs).optional(),confirmed:i.boolean().optional(),operation_id:ld.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog.credentials"),header:i.string().min(1).max(128).optional(),cwd:Pi.optional(),name:Oi,values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("radient.request"),control:i.object({operation:i.enum(["account","prices","credits","usage","provision","application.create","agents.list","agents.get","agents.create","agents.update","agents.delete","agents.like","agents.unlike","agents.liked","agents.like_count","agents.favourite","agents.unfavourite","agents.favourited","agents.favourite_count","agents.download_count","agents.statuses","comments.list","comments.create","comments.update","comments.delete","account.agents","memberships.list","org_agents.list","org_team.get","org_teams.list","org_skills.list","org_skill.get","signup.resend","team_trial.eligibility","team_trial.start","team_trial.status"]),request_id:ue.optional(),tenant_id:A.optional(),account_id:A.optional(),agent_id:A.optional(),comment_id:A.optional(),team_id:A.optional(),skill_id:A.optional(),query:i.record(i.union([i.string().max(1024),i.number().int()])).optional(),payload:i.record(i.unknown()).optional(),confirmed:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("providers.list")}).strict(),i.object({op:i.literal("accounts.list")}).strict(),i.object({op:i.literal("accounts.remove"),accountId:i.number().int().positive(),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("tunnel.setup.read"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.plan"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.run"),credentialId:i.number().int().positive(),acceptMonthlyPrice:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("auth.start"),provider:A}).strict(),i.object({op:i.literal("auth.status"),id:A}).strict(),i.object({op:i.literal("auth.input"),id:A,promptId:A,value:ns}).strict(),i.object({op:i.literal("auth.cancel"),id:A}).strict(),i.object({op:i.literal("auth.key"),provider:A,value:ns}).strict(),i.object({op:i.literal("auth.logout"),provider:A}).strict(),i.object({op:i.literal("agent_messages.status"),boundary:id}).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:ji.optional(),files:i.array(A).min(1).max(10).refine(e=>new Set(e).size===e.length,"Duplicate file").optional(),mentions:tv.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:ji.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:ji.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:id.optional()}).strict(),i.object({op:i.literal("team_bridge.link_preview.resolve"),url:i.string().min(1).max(Db),index:i.number().int().nonnegative(),expectedAccountId:A}).strict(),i.object({op:i.literal("settings.list")}).strict(),i.object({op:i.literal("settings.edit"),key:ts,value:i.unknown().refine(e=>e!==void 0,"A setting value is required."),base:ev.optional()}).strict(),i.object({op:i.literal("settings.reset"),key:ts}).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:iv}).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:ts,value:ns}).strict(),i.object({op:i.literal("peers.list")}).strict(),i.object({op:i.literal("networks.list")}).strict(),i.object({op:i.literal("networks.invite"),networkId:ur,role:i.enum(["read","drive","admin"]),deviceId:ur.optional()}).strict(),i.object({op:i.literal("networks.member.remove"),networkId:ur,deviceId:ur,confirm:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("sessions.transfer"),sessionId:G,to:i.union([i.literal("local"),ur]),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:Wr}).strict(),i.object({op:i.literal("approvals.deny"),approvalId:Wr}).strict(),...["approvals.approveOperation","approvals.applyOperation"].map(e=>i.object({op:i.literal(e),approvalId:Wr,operation:i.literal("profile_save"),requestDigest:i.string().regex(Fs),disclosureDigest:i.string().regex(Fs)}).strict()),i.object({op:i.literal("approvals.approveCredential"),approvalId:Wr,...fd}).strict(),i.object({op:i.literal("approvals.applyCredential"),approvalId:Wr,...fd}).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:wn}).strict(),i.object({op:i.literal("projects.create"),name:Di,description:i.string().max(Md).optional(),status:Od.optional(),tags:Pd.optional()}).strict(),i.object({op:i.literal("projects.update"),key:wn,fields:i.object({name:Di.optional(),title:i.string().max(80).optional(),owner:i.string().max(80).optional(),team:i.string().max(80).optional(),description:i.string().max(Md).optional(),status:Od.optional(),progress:i.string().max(Av).optional(),tags:Pd.optional(),start_date:is.optional(),target_date:is.optional(),completed_at:is.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:wn,confirmed_name:Di}).strict(),i.object({op:i.literal("projects.link"),key:wn,sessionId:G}).strict(),i.object({op:i.literal("projects.unlink"),key:wn,sessionId:G}).strict(),i.object({op:i.literal("projects.milestone"),key:wn,name:i.string().min(1).max(jd),targetDate:is.optional(),completed:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.milestone.remove"),key:wn,name:i.string().min(1).max(jd)}).strict(),i.object({op:i.literal("projects.request_update"),key:wn}).strict(),i.object({op:i.literal("projects.search"),q:i.string().min(1).max(Rv),limit:i.number().int().min(1).max(Iv).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:Gr}).strict(),i.object({op:i.literal("library.update"),id:Gr,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:zr,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:zr}).strict(),i.object({op:i.literal("library.tags.merge"),id:zr,into:zr}).strict(),i.object({op:i.literal("library.tags.assign"),id:Gr,tags:i.array(zr).max(64),primary:i.string().max(128).optional()}).strict(),i.object({op:i.literal("library.chat.link"),id:Gr,sessionId:G}).strict(),i.object({op:i.literal("library.chat.clear"),id:Gr}).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:Cv}).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:cn}).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([Nd,Dd,Ov])}).strict(),i.object({op:i.literal("notifications.dismiss"),verb:i.enum(["dismiss","undismiss"]),target:i.union([Nd,Dd])}).strict(),i.object({op:i.literal("notifications.seen"),items:i.array(i.object({id:cn,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()]);Mv.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 Ct={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},jv={runtimeUnreachable:"runtime_unreachable"},ii="runtime_busy",cp="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 lp=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(),$v=i.object({path:i.string(),size:i.number().nullish(),preview:i.string().nullish(),preview_truncated:i.boolean().nullish()}).passthrough(),Dv=lp.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($v).nullish(),files_total:i.number().nullish(),files_truncated:i.boolean().nullish(),publish_budget:i.object({limit:i.number(),total:i.number()}).passthrough().nullish()}).passthrough(),fO=i.object({skills:i.array(lp),scope:i.string().nullish(),detail:i.string().nullish(),skill_detail:Dv.nullish(),warning_count:i.number().nullish(),version:i.string().nullish()}).passthrough(),pO=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(),hO="aside_adopt_refused",Nv=["session_closed","open_tool_batch","turn_running"];function mO(e){if(typeof e!="object"||e===null)return;const t=e.reason;return Nv.find(n=>n===t)}const Lv={[Ct.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[Ct.refused]:"ui.common.errors.desktop_refusal.refused",[Ct.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[Ct.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed"},Ia={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 ai(e){return e!==void 0&&Object.values(Ct).includes(e)}function Fv(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return Ct.refused;if(t===503)return Ct.planeClosed}}const gO=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(),_O=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),Uv=88e4,Bv=11e5,Hv=2e4,Wv=9e4,Gv=new Set(["analytics.get","analytics.models","sessions.report"]),zv=new Set(["usage.get"]),Kv=new Set(["networks.list","peers.list"]),Vv=new Set(["usage.reset"]),Zv=new Set([...Gv,...zv,...Kv,...Vv]),Yv=90,Qv=30,Xv=300,Jv=10,dp=15,qv=1e4;function ey(e){const n=e.to==="local"||e.keep?Xv:Qv,r=Math.max(0,e.waitS??0);return(Yv+n+Jv+dp)*1e3+r*1e3}const ty=18e4,ny=ty+15e3,ry=120,oy=135e3,sy=93e4,up=(ry+30+dp)*1e3,iy=6e4,ay=5*up,cy=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function ly(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 up;case"hub.check":return iy;case"hub.applyAll":return ay;default:return null}}function dy(e){if(typeof e!="string"&&e.op==="sessions.transfer")return ey(e)+qv;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return ny;if(t==="tunnel.setup.run")return sy;if(t==="tunnel.setup.plan")return oy;const n=ly(t);return n!==null?n:Zv.has(t)?Wv:Hv}const uy=5e3;function fp(e){return dy(e)+uy}const Cc="deadline_exceeded",pp="foreground_required",hp="View these completions in the foreground before marking them read.",fy=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"]),py=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function hy(e,t){const n=Math.round(t/1e3),r=Cc;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.`}:cy.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:fy.has(e)?{code:r,message:py.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 bO=Uv,vO=Bv;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 my(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function Ld(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 Li(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 Fi(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 Fd(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 Kr(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 Ui(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function gy(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:Fd(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:Fd(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??Vb)});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"),Ls(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),Ls(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??Yb)});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":{Fi(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??{},...Li(e)}}}case"agent.republish":{Fi(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??{},...Li(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{Fi(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:Li(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,...my(e),message:e.message,...Ld(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...Ld(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${Ui(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${Ui(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)}${Ui(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"?"":Kr(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${Kr(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)}${Kr(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)}${Kr(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}${Kr(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??xv)})}`,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,..._y(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:Pv[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function _y(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 yO=64,wO=64*1024*1024,kO="superseded_completion_token",SO="store_busy",by="session_is_remote",vy="owner_build_behind";function EO(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 wr(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 yy(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const AO=e=>typeof e?.goal_status=="string",RO=e=>(e?.goal??"").trim().length>0;function wy(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function ky(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 lo={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 Sy(e){return e?e===lo.notPaired?"notPaired":e===lo.serverDown?"serverDown":e===lo.frameBudget?"frameTooLarge":"lost":"lost"}const Ud=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},Ey=e=>e?Ud(e):Ud,Ay=e=>e;function Ry(e,t=Ay){const n=Wl.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return Wl.useDebugValue(n),n}const Bd=e=>{const t=Ey(e),n=r=>Ry(t,r);return Object.assign(n,t),n},Go=e=>e?Bd(e):Bd;function mp(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 Ta=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Ta(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Ta(r)(n)}}}},xy=(e,t)=>(n,r,o)=>{let s={storage:mp(()=>localStorage),partialize:b=>b,version:0,merge:(b,v)=>({...v,...b}),...t},a=!1;const c=new Set,l=new Set;let d=s.storage;if(!d)return e((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),n(...b)},r,o);const u=()=>{const b=s.partialize({...r()});return d.setItem(s.name,{state:b,version:s.version})},f=o.setState;o.setState=(b,v)=>{f(b,v),u()};const h=e((...b)=>{n(...b),u()},r,o);o.getInitialState=()=>h;let m;const y=()=>{var b,v;if(!d)return;a=!1,c.forEach(E=>{var k;return E((k=r())!=null?k:h)});const p=((v=s.onRehydrateStorage)==null?void 0:v.call(s,(b=r())!=null?b:h))||void 0;return Ta(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,N]=E;if(m=s.merge(N,(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:b=>{s={...s,...b},b.storage&&(d=b.storage)},clearStorage:()=>{d?.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>y(),hasHydrated:()=>a,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(l.add(b),()=>{l.delete(b)})},s.skipHydration||y(),m||h},ci=xy,Iy=(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 Ty(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 gp=Go()(ci(e=>({notice:null,receive:t=>e(n=>Iy(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:mp(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function Oc(e){return _(Lv[e])}async function _p(e){if(window.api?.desktop)try{return await Cy(window.api.desktop.request(e),e)}catch(n){throw n instanceof Pe?n:Dy(n)?new jn(hp,pp):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 Cy(e,t){const n=fp(t);let r;return Promise.race([e,new Promise((o,s)=>{r=setTimeout(()=>{const a=hy(t.op,n);s(new Pe(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const bp="This server did not answer the request for its desktop controls.",Oy=()=>_("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 jn extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function Pc(e,t){return e instanceof Pe||e instanceof jn?ai(e.code)?Oc(e.code):e.message===bp?Oy():e.message:t}function Py(e,t,n,r){return typeof r=="string"?r:n===Ia.noCredential?Ct.noCredential:n===Ia.transportFailed?Ct.transportFailed:Fv(gy(e).path,t)}async function Ye(e){const t=await _p(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??bp,void 0,Py(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"&&My(n?.result),n?.result}function My(e){if(typeof e!="object"||e===null)return;const t=Ty(e.delegated_cleanup_notice);t&&gp.getState().receive(t)}async function jy(){try{await Ye({op:"delegated_cleanup_notice.ack"})}catch{}}async function xO(){gp.getState().dismiss(),await jy()}function $y(e){return e instanceof Pe&&e.code===Cc}function IO(e){if(!(e instanceof Pe))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===vy:e.code===by}function TO(e){return e instanceof jn&&e.code===pp}function Dy(e){return e instanceof Error&&e.message.includes(hp)}async function CO(e){const t=await _p(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function OO(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 Ny(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"),Ls(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:lo.ended}),o.close())},()=>{o.close(),t({kind:"end"})}}async function PO(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&&ai(a)?a:s===Ia.noCredential?Ct.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 MO(e){return e.kind==="error"?ai(e.code)?new jn(Oc(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function Ly(e){if($y(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 vp={unreachable:"",deadline:"",unauthorized:"",get outdated(){return _("ui.common.connection.backend.remedy_outdated")},unknown:""},Ca={get unreachable(){return _("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return _("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return _("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return _("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function Fy(e,t){const n=Ly(t);return[e,Ca[n],vp[n]].filter(Boolean).join(" ")}const Oa={get successor(){return _("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return _("ui.common.connection.backend.pairing_unpaired")}},Uy={get successor(){return _("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return _("ui.common.connection.backend.pane_unpaired")}};function jO(e,t){return e!=="unpaired"?null:Uy[t??"unpaired"]}function $O(e,t){return e!=="unpaired"?null:Oa[t??"unpaired"]}function DO(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 NO(e){const{kind:t,unpaired:n,missing:r,answered:o,cause:s=null}=e;if(s!==null)return Oa[s];if(!o){if(t==="unreachable")return _("ui.common.connection.backend.compatibility_unreachable",{diagnosis:Ca.unreachable});if(t==="unauthorized")return _("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return _("ui.common.connection.backend.compatibility_deadline",{diagnosis:Ca.deadline});if(t==="outdated")return _("ui.common.connection.backend.compatibility_outdated",{remedy:vp.outdated})}return n?Oa.unpaired:o?_("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):_("ui.common.connection.backend.compatibility_unknown")}const By=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function LO(e,t=null){return t!==null||!e?!0:By.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function Hy(e,t){return t instanceof Pe&&t.status===null?!1:e<1}function FO(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 Wy={get successor(){return _("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.card_credential_refused")},get unpaired(){return _("ui.common.connection.backend.card_unpaired")}};function UO(e,t,n){return e===null?{sentence:Fy(t,n),remedy:!0}:{sentence:Wy[e],remedy:Vf(e)}}const yp={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]},Gy=3e4,zy=15e3;function Ky(e){return e?.desktop_available===!0}function BO(){const{client:e,provided:t}=m_();return Kf({enabled:t,queryKey:yp.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=>Ky(n.state.data)?Gy:zy,refetchIntervalInBackground:!0},e)}function Vy(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function HO(e,t,n=1){return Vy(e,t,n)==="enabled"}function WO(e){return Kf({queryKey:yp.providers,queryFn:()=>Ye({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:Hy})}let li=!1,Us=!1;const Bs=[];function GO(){typeof window>"u"||!window.__loDevDriver?.armed||(li=!0,Us=!1,Bs.length=0)}function Zy(){return li}function Yy(e){if(li)try{if(Bs.length>=256){Us=!0;return}Bs.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{Us=!0}}function zO(){return{armed:li,fault:Us,receipts:Bs.map(e=>({...e}))}}const Vr=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function Qy(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=Vr(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=Vr(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>Vr(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=Vr(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=Vr(a);c!==null&&o.has(c)?(s.push(a),o.delete(c)):c===null&&s.push(a)}return s}const Pa=e=>({revision:xt(e),demand:e.orderDemand}),Qn=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Mr(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 y of a.records){const b=y.sourceEntryId??(y.kind==="tool"||y.kind==="supplement"?null:y.id);typeof b=="string"&&b.length>0&&b.length<=128&&m.set(b,h)}l={...l,...m.size>0?{journalBodyOwed:m}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(h,m,y)=>{if(!Qn(y))return;const b=d.get(h);b&&b.seq>=y||(d===u&&(d=new Map(d)),d.set(h,{entryId:m,seq:y}))};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 Mc(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 wp(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 kp(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 Xy=Number.MAX_SAFE_INTEGER;function Jy(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:Xy})}}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 Sp(e,t){return{floor:qy(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:Jy(e,t)}}function Ep(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 Ap(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 qy(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 Rp(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 Hs(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 xp(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return e0(e,t);const n=e.journalGeneration,r=e.journalPositions;let o=!1,s=!1;const a=t.map(b=>{b.sourcePrecedes!==void 0&&(s=!0);let p=[r?.get(b.sourceEntryId??b.id),r?.get(b.id)].filter(C=>C!==void 0).sort((C,N)=>N.seq-C.seq)[0];if(b.journalGeneration===n&&Qn(b.journalSeq)&&(!p||b.journalSeq>p.seq)&&(p={entryId:b.sourceEntryId??b.id,seq:b.journalSeq}),!p||!n||!(b.kind==="user"&&(b.provisional===!0||b.local===!0))&&b.sourceEntryId===p.entryId&&b.journalSeq===p.seq&&b.journalGeneration===n)return b;o=!0;let k={...b,sourceEntryId:p.entryId,journalSeq:p.seq,journalGeneration:n};if(k.kind==="user"){const{provisional:C,local:N,...O}=k;k=O}return k});wp(a,b=>b.journalGeneration===n&&Qn(b.journalSeq))&&(o=!0);const l=new Map,d=new Map(a.map(b=>[b.id,b])),u=Rp(d,b=>b!==void 0&&b.journalGeneration===n&&Qn(b.journalSeq)?b.journalSeq:void 0),f=b=>u(b)!==void 0,h=s?Sp(a,u):void 0,m=(b,v)=>{const p=u(b);if(b.kind==="user"&&b.provisional===!0&&p===void 0)return[1,0,0,0,v];const E=b.kind==="supplement"?b.anchor:b.kind==="tool"?e.journalCallOwners?.get(b.toolCallId)??e.argsByCall.get(b.toolCallId)?.anchorId:void 0,k=typeof E=="string"?u(d.get(E)):void 0,C=k===void 0&&p===void 0?Ep(b,d,u,h):void 0,N=p===void 0&&C===void 0?kp(b,d,f,u,l):void 0,O=k??p??C?.seq??N;if(O===void 0){const R=Ap(b,d,h);return[1,R?.slot??v,R?-R.depth:0,0,v]}return[0,O,k!==void 0?1:p!==void 0?0:C!==void 0?C.slot:2,p??Number.MAX_SAFE_INTEGER,v]},y=a.map((b,v)=>({record:b,index:v,rank:m(b,v)}));return y.sort((b,v)=>{for(let p=0;p<b.rank.length;p++){const E=b.rank[p]-v.rank[p];if(E)return E}return 0}),!o&&y.every((b,v)=>b.index===v)?Hs(e,t):Hs(e,y.map(b=>b.record))}function e0(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,N)=>N.seq-C.seq)[0];p.journalGeneration===n&&Qn(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();wp(l,p=>p.journalGeneration===n&&Qn(p.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(p=>[p.id,p])),h=Rp(f,p=>a(p)?.seq),m=p=>h(p)!==void 0,y=s?Sp(l,h):void 0,b=(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,N=typeof C=="string"?h(f.get(C)):void 0,O=N===void 0&&k===void 0?Ep(p,f,h,y):void 0,R=k===void 0&&O===void 0?kp(p,f,m,h,u):void 0,g=N??k??O?.seq??R;if(g===void 0){const w=Ap(p,f,y);return[1,w?.slot??E,w?-w.depth:0,0,E]}return[0,g,N!==void 0?1:k!==void 0?0:O!==void 0?O.slot:2,k??Number.MAX_SAFE_INTEGER,E]},v=l.map((p,E)=>({record:p,index:E,rank:b(p,E)}));return v.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&&v.every((p,E)=>p.index===E)?Hs(e,t):Hs(e,v.map(p=>p.record))}function Vt(e){const t=e.records.filter(o=>o.kind==="user"&&o.provisional===!0),n=e.records.filter(o=>o.journalGeneration!==e.journalGeneration||!Qn(o.journalSeq)),r=[...t,...n].map(o=>o.sourceEntryId??(o.kind==="tool"||o.kind==="supplement"?null:o.id));if(r.push(...jc(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 jc(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 Ip(e,t){const n=e.journalPositions;return Vt(e).filter(r=>!n?.has(r)&&!t?.has(r))}const xt=e=>e.orderRevision??0;async function t0(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"?jc(c):l==="lookup"?Ip(c):Vt(c);let o=e.getTranscript().journalGeneration,s=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=Pa(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",h=$b(r(c,f).filter(v=>!n(f).has(v)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),m=await e.read(h,f);if(!e.isCurrent()||xt(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(m,d,l),!e.isCurrent())return{kind:"stale"};const y=e.getTranscript(),b=e.page(m);if(b.journal_order_state==="ready"&&b.journal_generation===y.journalGeneration){b.journal_generation!==o&&(t.clear(),o=b.journal_generation);for(const E of h)n(f).add(E);if(y.orderNeedsReconcile){if(y.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear();continue}if(f==="payload"){const E=(b.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 v=e.sweep?.(y,n);if(v?.kind==="none")return{kind:"complete",transcript:y};const p=v?.kind??"authority";if(r(y,p).some(E=>!n(p).has(E)))continue;return{kind:"complete",transcript:y}}if(!y.orderNeedsReconcile||y.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 Bi(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function Hd(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function KO(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=Bi(s.action_count);if(a===null)continue;const c={actions:a,workedSeconds:Hd(s.worked_seconds),failed:Bi(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:Bi(s.cross_session_action_count),crossSessionWorkedSeconds:Hd(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 n0(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 r0(e,t,n){const r=n0(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 $c=new Set,$n="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Dc=new RegExp(`[${$n}]`),o0=new RegExp(`[${$n}]+`),VO=new RegExp(`[${$n}]+`,"g"),s0=new RegExp(`^[${$n}]+|[${$n}]+$`,"g"),i0=new RegExp(`^[${$n}]+`),ZO=new RegExp(`[^${$n}]`);function Jt(e){return e.replace(s0,"")}function Oo(e){return e.replace(i0,"")}function Tp(e,t){return t===0||Dc.test(e[t-1])}function Cp(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&Tp(e,n)&&t.push(n);return t}function Nc(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 Lg,b as Jl,D as Fg,l as Ac,m as Bf,n as Rc,o as Ug}from"./index-C5MuLj2j.js";import{c as _n,t as _,a as Bg}from"./messages-BdH-KMeX.js";import{P as Hg,i as xc,a as Ic,p as Hf}from"./roles-D1pcbxAx.js";const Xl=new Map,Ql=new Map,ql=new Map,ed=new Map;function Tc(e){return e===void 0?"":JSON.stringify(e)}function Cc(e,t){const n=`${e}\0${Tc(t)}`;let r=Xl.get(n);return r===void 0&&(r=new Intl.DateTimeFormat(e,t),Xl.set(n,r)),r}function Wg(e,t){const n=`${e}\0${Tc(t)}`;let r=Ql.get(n);return r===void 0&&(r=new Intl.NumberFormat(e,t),Ql.set(n,r)),r}function oO(e,t,n){return Cc(n??_n(),t).format(e)}function sO(e,t,n){return Cc(n??_n(),t).format(e)}function iO(e,t,n){return Cc(n??_n(),t).format(e)}function aO(e,t,n){return Wg(n??_n(),t).format(e)}function cO(e,t,n,r){const o=r??_n(),s=`${o}\0${Tc(n)}`;let a=ql.get(s);return a===void 0&&(a=new Intl.RelativeTimeFormat(o,n),ql.set(s,a)),a.format(e,t)}function Es(e,t){const n=_n();let r=ed.get(n);return r===void 0&&(r=new Intl.ListFormat(n,{type:"conjunction",style:"narrow"}),ed.set(n,r)),r.format(e)}const Gg={zh:";",ja:";",ur:"؛ ",ar:"؛ "};function lO(e,t){const n=_n().split("-")[0]?.toLowerCase();return e.join(Gg[n??""]??"; ")}var zo=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(){}},or=typeof window>"u"||"Deno"in globalThis;function It(){}function zg(e,t){return typeof e=="function"?e(t):e}function va(e){return typeof e=="number"&&e>=0&&e!==1/0}function Wf(e,t){return Math.max(e+(t||0)-Date.now(),0)}function xr(e,t){return typeof e=="function"?e(t):e}function Ut(e,t){return typeof e=="function"?e(t):e}function td(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:s,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==Oc(a,t.options))return!1}else if(!yo(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 nd(e,t){const{exact:n,status:r,predicate:o,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(vo(t.options.mutationKey)!==vo(s))return!1}else if(!yo(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Oc(e,t){return(t?.queryKeyHashFn||vo)(e)}function vo(e){return JSON.stringify(e,(t,n)=>wa(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function yo(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>yo(e[n],t[n])):!1}function Gf(e,t){if(e===t)return e;const n=rd(e)&&rd(t);if(n||wa(e)&&wa(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]=Gf(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return o===a&&l===o?e:c}return t}function ya(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 rd(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function wa(e){if(!od(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!od(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function od(e){return Object.prototype.toString.call(e)==="[object Object]"}function Kg(e){return new Promise(t=>{setTimeout(t,e)})}function ka(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Gf(e,t):t}function Vg(e){return e}function Zg(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 Pc=Symbol();function zf(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Pc?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Jg=class extends zo{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!or&&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 Jg,Xg=class extends zo{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!or&&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}},Ms=new Xg;function Sa(){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 Qg(e){return Math.min(1e3*2**e,3e4)}function Kf(e){return(e??"online")==="online"?Ms.isOnline():!0}var Vf=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Ci(e){return e instanceof Vf}function Zf(e){let t=!1,n=0,r=!1,o;const s=Sa(),a=b=>{r||(h(new Vf(b)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>Mc.isFocused()&&(e.networkMode==="always"||Ms.isOnline())&&e.canRun(),u=()=>Kf(e.networkMode)&&e.canRun(),f=b=>{r||(r=!0,e.onSuccess?.(b),o?.(),s.resolve(b))},h=b=>{r||(r=!0,e.onError?.(b),o?.(),s.reject(b))},m=()=>new Promise(b=>{o=v=>{(r||d())&&b(v)},e.onPause?.()}).then(()=>{o=void 0,r||e.onContinue?.()}),y=()=>{if(r)return;let b;const v=n===0?e.initialPromise:void 0;try{b=v??e.fn()}catch(p){b=Promise.reject(p)}Promise.resolve(b).then(f).catch(p=>{if(r)return;const E=e.retry??(or?0:3),k=e.retryDelay??Qg,C=typeof k=="function"?k(n,p):k,N=E===!0||typeof E=="number"&&n<E||typeof E=="function"&&E(n,p);if(t||!N){h(p);return}n++,e.onFail?.(n,p),Kg(C).then(()=>d()?void 0:m()).then(()=>{t?h(p):y()})})};return{promise:s,cancel:a,continue:()=>(o?.(),s),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?y():m().then(y),s)}}var qg=e=>setTimeout(e,0);function e_(){let e=[],t=0,n=c=>{c()},r=c=>{c()},o=qg;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=e_(),Yf=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),va(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(or?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},t_=class extends Yf{#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=n_(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=ka(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(It).catch(It):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>Ut(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Pc||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||!Wf(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=zf(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=>{Ci(c)&&c.silent||this.#s({type:"error",error:c}),Ci(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#o=Zf({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,...Jf(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 Ci(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 Jf(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Kf(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function n_(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 r_=class extends zo{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,o=t.queryHash??Oc(r,t);let s=this.get(o);return s||(s=new t_({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=>td(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>td(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()})})}},o_=class extends Yf{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||s_(),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=Zf({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 s_(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var i_=class extends zo{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 o_({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=rs(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=rs(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=rs(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=rs(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=>nd(t,n))}findAll(e={}){return this.getAll().filter(t=>nd(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(It))))}};function rs(e){return e.options.scope?.id}function sd(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=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},h=zf(t.options,t.fetchOptions),m=async(y,b,v)=>{if(u)return Promise.reject();if(b==null&&y.pages.length)return Promise.resolve(y);const p={client:t.client,queryKey:t.queryKey,pageParam:b,direction:v?"backward":"forward",meta:t.options.meta};f(p);const E=await h(p),{maxPages:k}=t.options,C=v?Yg:Zg;return{pages:C(y.pages,E,k),pageParams:C(y.pageParams,b,k)}};if(o&&s.length){const y=o==="backward",b=y?Xf:Ea,v={pages:s,pageParams:a},p=b(r,v);c=await m(v,p,y)}else{const y=e??s.length;do{const b=l===0?a[0]??r.initialPageParam:Ea(r,c);if(l>0&&b==null)break;c=await m(c,b),l++}while(l<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function Ea(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 dO(e,t){return t?Ea(e,t)!=null:!1}function uO(e,t){return!t||!e.getPreviousPageParam?!1:Xf(e,t)!=null}var a_=class{#t;#e;#n;#r;#o;#a;#i;#s;constructor(e={}){this.#t=e.queryCache||new r_,this.#e=e.mutationCache||new i_,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=Ms.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(xr(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=zg(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(It).catch(It)}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(It)),o.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(It)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(xr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(It).catch(It)}fetchInfiniteQuery(e){return e.behavior=sd(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(It).catch(It)}ensureInfiniteQueryData(e){return e.behavior=sd(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ms.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(vo(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{yo(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#o.set(vo(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(r=>{yo(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=Oc(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===Pc&&(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()}},c_=class extends zo{constructor(e,t){super(),this.options=t,this.#t=e,this.#s=null,this.#i=Sa(),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),id(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Aa(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Aa(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 Ut(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&&!ya(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&ad(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||Ut(this.options.enabled,this.#e)!==Ut(t.enabled,this.#e)||xr(this.options.staleTime,this.#e)!==xr(t.staleTime,this.#e))&&this.#g();const o=this.#_();r&&(this.#e!==n||Ut(this.options.enabled,this.#e)!==Ut(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 d_(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(It)),t}#g(){this.#y();const e=xr(this.options.staleTime,this.#e);if(or||this.#r.isStale||!va(e))return;const n=Wf(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,!(or||Ut(this.options.enabled,this.#e)===!1||!va(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&&id(e,t),S=g&&ad(e,n,t,r);(w||S)&&(u={...u,...Jf(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:b}=u;h=u.data;let v=!1;if(t.placeholderData!==void 0&&h===void 0&&b==="pending"){let g;o?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(g=o.data,v=!0):g=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,g!==void 0&&(b="success",h=ka(o?.data,g,t),f=!0)}if(t.select&&h!==void 0&&!v)if(o&&h===s?.data&&t.select===this.#m)h=this.#f;else try{this.#m=t.select,h=t.select(h),h=ka(o?.data,h,t),this.#f=h,this.#s=null}catch(g){this.#s=g}this.#s&&(m=this.#s,h=this.#f,y=Date.now(),b="error");const p=u.fetchStatus==="fetching",E=b==="pending",k=b==="error",C=E&&p,N=h!==void 0,R={status:b,fetchStatus:u.fetchStatus,isPending:E,isSuccess:b==="success",isError:k,isInitialLoading:C,isLoading:C,data:h,dataUpdatedAt:u.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:p,isRefetching:p&&!E,isLoadingError:k&&!N,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:k&&N,isStale:jc(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=Sa();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),ya(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 l_(e,t){return Ut(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function id(e,t){return l_(e,t)||e.state.data!==void 0&&Aa(e,t,t.refetchOnMount)}function Aa(e,t,n){if(Ut(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&jc(e,t)}return!1}function ad(e,t,n,r){return(e!==t||Ut(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&jc(e,n)}function jc(e,t){return Ut(t.enabled,e)!==!1&&e.isStaleByTime(xr(t.staleTime,e))}function d_(e,t){return!ya(e.getCurrentResult(),t)}var $c=x.createContext(void 0),u_=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},fO=({client:e,children:t})=>(x.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),Lg.jsx($c.Provider,{value:e,children:t})),Qf=x.createContext(!1),f_=()=>x.useContext(Qf);Qf.Provider;function p_(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var h_=x.createContext(p_()),m_=()=>x.useContext(h_);function g_(e,t){return typeof e=="function"?e(...t):!!e}function cd(){}var __=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},b_=e=>{x.useEffect(()=>{e.clearReset()},[e])},v_=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(o&&e.data===void 0||g_(n,[e.error,r])),y_=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)))},w_=(e,t)=>e.isLoading&&e.isFetching&&!t,k_=(e,t)=>e?.suspense&&t.isPending,ld=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function S_(e,t,n){const r=u_(n),o=f_(),s=m_(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=o?"isRestoring":"optimistic",y_(a),__(a,s),b_(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)):cd;return l.updateResult(),h},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),x.useEffect(()=>{l.setOptions(a)},[a,l]),k_(a,d))throw ld(a,l,s);if(v_({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&&!or&&w_(d,o)&&(c?ld(a,l,s):r.getQueryCache().get(a.queryHash)?.promise)?.catch(cd).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function qf(e,t){return S_(e,c_,t)}const E_=()=>{const e=x.useContext($c)??null,t=x.useMemo(()=>new a_({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 pO(e){return e!=="detached"&&e!=="wedged"}function ep(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function hO(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=ep(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 Ra;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ra||(Ra={}));const B=ve.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),cn=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"]),A_=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Et 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 Et))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()}}Et.create=e=>new Et(e);const Mr=(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 tp=Mr;function R_(e){tp=e}function js(){return tp}const $s=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}},x_=[];function U(e,t){const n=js(),r=$s({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Mr?void 0:Mr].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 Q;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 Q;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 Q=Object.freeze({status:"aborted"}),Sr=e=>({status:"dirty",value:e}),dt=e=>({status:"valid",value:e}),xa=e=>e.status==="aborted",Ia=e=>e.status==="dirty",sr=e=>e.status==="valid",wo=e=>typeof Promise<"u"&&e instanceof Promise;function Ds(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 np(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 so,io;class en{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 dd=(e,t)=>{if(sr(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 Et(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 cn(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:cn(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:cn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(wo(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:cn(t)},s=this._parseSync({data:t,path:o.path,parent:o});return dd(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:cn(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:o});return sr(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=>sr(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:cn(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(wo(o)?o:Promise.resolve(o));return dd(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 zt({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 $n.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Wt.create(this)}promise(){return $r.create(this,this._def)}or(t){return Ao.create([this,t],this._def)}and(t){return Ro.create(this,t,this._def)}transform(t){return new zt({...ce(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Oo({...ce(this._def),innerType:this,defaultValue:n,typeName:X.ZodDefault})}brand(){return new Dc({typeName:X.ZodBranded,type:this,...ce(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Po({...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 Ko.create(this,t)}readonly(){return Mo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const I_=/^c[^\s-]{8,}$/i,T_=/^[0-9a-z]+$/,C_=/^[0-9A-HJKMNP-TV-Z]{26}$/i,O_=/^[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,P_=/^[a-z0-9_-]{21}$/i,M_=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,j_=/^[-+]?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)?)??$/,$_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,D_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Oi;const N_=/^(?:(?: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])$/,F_=/^(([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])$/,B_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,H_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rp="((\\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])))",W_=new RegExp(`^${rp}$`);function op(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 G_(e){return new RegExp(`^${op(e)}$`)}function sp(e){let t=`${rp}T${op(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 z_(e,t){return!!((t==="v4"||!t)&&N_.test(e)||(t==="v6"||!t)&&F_.test(e))}function K_(e,t){if(!M_.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 V_(e,t){return!!((t==="v4"||!t)&&L_.test(e)||(t==="v6"||!t)&&U_.test(e))}class Ht 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}),Q}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")$_.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")Oi||(Oi=new RegExp(D_,"u")),Oi.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")O_.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")P_.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")I_.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")T_.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")C_.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"?sp(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"?W_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?G_(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"?j_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"duration",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?z_(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"?K_(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"?V_(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"?B_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?H_.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 Ht({...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 Ht({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ht({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ht({...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}}Ht.create=e=>{var t;return new Ht({checks:[],typeName:X.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};function Z_(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 Pn 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}),Q}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"?Z_(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 Pn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new Pn({...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)}}Pn.create=e=>new Pn({checks:[],typeName:X.ZodNumber,coerce:e?.coerce||!1,...ce(e)});class Mn 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}),Q}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 Mn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new Mn({...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}}Mn.create=e=>{var t;return new Mn({checks:[],typeName:X.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};class ko extends le{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==B.boolean){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.boolean,received:r.parsedType}),Q}return dt(t.data)}}ko.create=e=>new ko({typeName:X.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});class ir 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}),Q}if(isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_date}),Q}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 ir({...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}}ir.create=e=>new ir({checks:[],coerce:e?.coerce||!1,typeName:X.ZodDate,...ce(e)});class Ns extends le{_parse(t){if(this._getType(t)!==B.symbol){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.symbol,received:r.parsedType}),Q}return dt(t.data)}}Ns.create=e=>new Ns({typeName:X.ZodSymbol,...ce(e)});class So extends le{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.undefined,received:r.parsedType}),Q}return dt(t.data)}}So.create=e=>new So({typeName:X.ZodUndefined,...ce(e)});class Eo extends le{_parse(t){if(this._getType(t)!==B.null){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.null,received:r.parsedType}),Q}return dt(t.data)}}Eo.create=e=>new Eo({typeName:X.ZodNull,...ce(e)});class jr extends le{constructor(){super(...arguments),this._any=!0}_parse(t){return dt(t.data)}}jr.create=e=>new jr({typeName:X.ZodAny,...ce(e)});class Xn extends le{constructor(){super(...arguments),this._unknown=!0}_parse(t){return dt(t.data)}}Xn.create=e=>new Xn({typeName:X.ZodUnknown,...ce(e)});class pn extends le{_parse(t){const n=this._getOrReturnCtx(t);return U(n,{code:j.invalid_type,expected:B.never,received:n.parsedType}),Q}}pn.create=e=>new pn({typeName:X.ZodNever,...ce(e)});class Ls extends le{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.void,received:r.parsedType}),Q}return dt(t.data)}}Ls.create=e=>new Ls({typeName:X.ZodVoid,...ce(e)});class Wt 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}),Q;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 en(n,a,n.path,c)))).then(a=>lt.mergeArray(r,a));const s=[...n.data].map((a,c)=>o.type._parseSync(new en(n,a,n.path,c)));return lt.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new Wt({...this._def,minLength:{value:t,message:K.toString(n)}})}max(t,n){return new Wt({...this._def,maxLength:{value:t,message:K.toString(n)}})}length(t,n){return new Wt({...this._def,exactLength:{value:t,message:K.toString(n)}})}nonempty(t){return this.min(1,t)}}Wt.create=(e,t)=>new Wt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...ce(t)});function _r(e){if(e instanceof Ue){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Qt.create(_r(r))}return new Ue({...e._def,shape:()=>t})}else return e instanceof Wt?new Wt({...e._def,type:_r(e.element)}):e instanceof Qt?Qt.create(_r(e.unwrap())):e instanceof $n?$n.create(_r(e.unwrap())):e instanceof tn?tn.create(e.items.map(t=>_r(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}),Q}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof pn&&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 en(o,f,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof pn){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 en(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 _r(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 ip(ve.objectKeys(this.shape))}}Ue.create=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strip",catchall:pn.create(),typeName:X.ZodObject,...ce(t)});Ue.strictCreate=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strict",catchall:pn.create(),typeName:X.ZodObject,...ce(t)});Ue.lazycreate=(e,t)=>new Ue({shape:e,unknownKeys:"strip",catchall:pn.create(),typeName:X.ZodObject,...ce(t)});class Ao 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 Et(c.ctx.common.issues));return U(n,{code:j.invalid_union,unionErrors:a}),Q}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 Et(l));return U(n,{code:j.invalid_union,unionErrors:c}),Q}}get options(){return this._def.options}}Ao.create=(e,t)=>new Ao({options:e,typeName:X.ZodUnion,...ce(t)});const on=e=>e instanceof Io?on(e.schema):e instanceof zt?on(e.innerType()):e instanceof To?[e.value]:e instanceof jn?e.options:e instanceof Co?ve.objectValues(e.enum):e instanceof Oo?on(e._def.innerType):e instanceof So?[void 0]:e instanceof Eo?[null]:e instanceof Qt?[void 0,...on(e.unwrap())]:e instanceof $n?[null,...on(e.unwrap())]:e instanceof Dc||e instanceof Mo?on(e.unwrap()):e instanceof Po?on(e._def.innerType):[];class ai extends le{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.object)return U(n,{code:j.invalid_type,expected:B.object,received:n.parsedType}),Q;const r=this.discriminator,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]}),Q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const s of n){const a=on(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 ai({typeName:X.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...ce(r)})}}function Ta(e,t){const n=cn(e),r=cn(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=Ta(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=Ta(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 Ro extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(s,a)=>{if(xa(s)||xa(a))return Q;const c=Ta(s.value,a.value);return c.valid?((Ia(s)||Ia(a))&&n.dirty(),{status:n.value,value:c.data}):(U(r,{code:j.invalid_intersection_types}),Q)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([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}))}}Ro.create=(e,t,n)=>new Ro({left:e,right:t,typeName:X.ZodIntersection,...ce(n)});class tn extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.array)return U(r,{code:j.invalid_type,expected:B.array,received:r.parsedType}),Q;if(r.data.length<this._def.items.length)return U(r,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q;!this._def.rest&&r.data.length>this._def.items.length&&(U(r,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new en(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 tn({...this._def,rest:t})}}tn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new tn({items:e,typeName:X.ZodTuple,rest:null,...ce(t)})};class xo extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.object)return U(r,{code:j.invalid_type,expected:B.object,received:r.parsedType}),Q;const o=[],s=this._def.keyType,a=this._def.valueType;for(const c in r.data)o.push({key:s._parse(new en(r,c,r.path,c)),value:a._parse(new en(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 xo({keyType:t,valueType:n,typeName:X.ZodRecord,...ce(r)}):new xo({keyType:Ht.create(),valueType:t,typeName:X.ZodRecord,...ce(n)})}}class Fs extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.map)return U(r,{code:j.invalid_type,expected:B.map,received:r.parsedType}),Q;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:o._parse(new en(r,c,r.path,[d,"key"])),value:s._parse(new en(r,l,r.path,[d,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of a){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return Q;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const l of a){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return Q;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}Fs.create=(e,t,n)=>new Fs({valueType:t,keyType:e,typeName:X.ZodMap,...ce(n)});class ar extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.set)return U(r,{code:j.invalid_type,expected:B.set,received:r.parsedType}),Q;const 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 Q;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 en(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new ar({...this._def,minSize:{value:t,message:K.toString(n)}})}max(t,n){return new ar({...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)}}ar.create=(e,t)=>new ar({valueType:e,minSize:null,maxSize:null,typeName:X.ZodSet,...ce(t)});class Ir extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.function)return U(n,{code:j.invalid_type,expected:B.function,received:n.parsedType}),Q;function r(c,l){return $s({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,js(),Mr].filter(d=>!!d),issueData:{code:j.invalid_arguments,argumentsError:l}})}function o(c,l){return $s({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,js(),Mr].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 $r){const c=this;return dt(async function(...l){const d=new Et([]),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 Et([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,s);if(!f.success)throw new Et([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Ir({...this._def,args:tn.create(t).rest(Xn.create())})}returns(t){return new Ir({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Ir({args:t||tn.create([]).rest(Xn.create()),returns:n||Xn.create(),typeName:X.ZodFunction,...ce(r)})}}class Io 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})}}Io.create=(e,t)=>new Io({getter:e,typeName:X.ZodLazy,...ce(t)});class To extends le{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return U(n,{received:n.data,code:j.invalid_literal,expected:this._def.value}),Q}return{status:"valid",value:t.data}}get value(){return this._def.value}}To.create=(e,t)=>new To({value:e,typeName:X.ZodLiteral,...ce(t)});function ip(e,t){return new jn({values:e,typeName:X.ZodEnum,...ce(t)})}class jn extends le{constructor(){super(...arguments),so.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}),Q}if(Ds(this,so)||np(this,so,new Set(this._def.values)),!Ds(this,so).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{received:n.data,code:j.invalid_enum_value,options:r}),Q}return 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 jn.create(t,{...this._def,...n})}exclude(t,n=this._def){return jn.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}so=new WeakMap;jn.create=ip;class Co extends le{constructor(){super(...arguments),io.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}),Q}if(Ds(this,io)||np(this,io,new Set(ve.getValidEnumValues(this._def.values))),!Ds(this,io).has(t.data)){const o=ve.objectValues(n);return U(r,{received:r.data,code:j.invalid_enum_value,options:o}),Q}return dt(t.data)}get enum(){return this._def.values}}io=new WeakMap;Co.create=(e,t)=>new Co({values:e,typeName:X.ZodNativeEnum,...ce(t)});class $r extends le{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.promise&&n.common.async===!1)return U(n,{code:j.invalid_type,expected:B.promise,received:n.parsedType}),Q;const r=n.parsedType===B.promise?n.data:Promise.resolve(n.data);return dt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}$r.create=(e,t)=>new $r({type:e,typeName:X.ZodPromise,...ce(t)});class zt 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 Q;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?Q:l.status==="dirty"||n.value==="dirty"?Sr(l.value):l});{if(n.value==="aborted")return Q;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?Q:c.status==="dirty"||n.value==="dirty"?Sr(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"?Q:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?Q:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!sr(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=>sr(a)?Promise.resolve(o.transform(a.value,s)).then(c=>({status:n.value,value:c})):a);ve.assertNever(o)}}zt.create=(e,t,n)=>new zt({schema:e,typeName:X.ZodEffects,effect:t,...ce(n)});zt.createWithPreprocess=(e,t,n)=>new zt({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 $n extends le{_parse(t){return this._getType(t)===B.null?dt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}$n.create=(e,t)=>new $n({innerType:e,typeName:X.ZodNullable,...ce(t)});class Oo 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}}Oo.create=(e,t)=>new Oo({innerType:e,typeName:X.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});class Po 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 wo(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Et(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Et(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Po.create=(e,t)=>new Po({innerType:e,typeName:X.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});class Us extends le{_parse(t){if(this._getType(t)!==B.nan){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.nan,received:r.parsedType}),Q}return{status:"valid",value:t.data}}}Us.create=e=>new Us({typeName:X.ZodNaN,...ce(e)});const Y_=Symbol("zod_brand");class Dc 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 Ko 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"?Q:s.status==="dirty"?(n.dirty(),Sr(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"?Q: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 Ko({in:t,out:n,typeName:X.ZodPipeline})}}class Mo extends le{_parse(t){const n=this._def.innerType._parse(t),r=o=>(sr(o)&&(o.value=Object.freeze(o.value)),o);return wo(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}Mo.create=(e,t)=>new Mo({innerType:e,typeName:X.ZodReadonly,...ce(t)});function ud(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ap(e,t={},n){return e?jr.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=ud(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=ud(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})}}):jr.create()}const J_={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 X_=(e,t={message:`Input not instance of ${e.name}`})=>ap(n=>n instanceof e,t),cp=Ht.create,lp=Pn.create,Q_=Us.create,q_=Mn.create,dp=ko.create,eb=ir.create,tb=Ns.create,nb=So.create,rb=Eo.create,ob=jr.create,sb=Xn.create,ib=pn.create,ab=Ls.create,cb=Wt.create,lb=Ue.create,db=Ue.strictCreate,ub=Ao.create,fb=ai.create,pb=Ro.create,hb=tn.create,mb=xo.create,gb=Fs.create,_b=ar.create,bb=Ir.create,vb=Io.create,yb=To.create,wb=jn.create,kb=Co.create,Sb=$r.create,fd=zt.create,Eb=Qt.create,Ab=$n.create,Rb=zt.createWithPreprocess,xb=Ko.create,Ib=()=>cp().optional(),Tb=()=>lp().optional(),Cb=()=>dp().optional(),Ob={string:e=>Ht.create({...e,coerce:!0}),number:e=>Pn.create({...e,coerce:!0}),boolean:e=>ko.create({...e,coerce:!0}),bigint:e=>Mn.create({...e,coerce:!0}),date:e=>ir.create({...e,coerce:!0})},Pb=Q;var i=Object.freeze({__proto__:null,defaultErrorMap:Mr,setErrorMap:R_,getErrorMap:js,makeIssue:$s,EMPTY_PATH:x_,addIssueToContext:U,ParseStatus:lt,INVALID:Q,DIRTY:Sr,OK:dt,isAborted:xa,isDirty:Ia,isValid:sr,isAsync:wo,get util(){return ve},get objectUtil(){return Ra},ZodParsedType:B,getParsedType:cn,ZodType:le,datetimeRegex:sp,ZodString:Ht,ZodNumber:Pn,ZodBigInt:Mn,ZodBoolean:ko,ZodDate:ir,ZodSymbol:Ns,ZodUndefined:So,ZodNull:Eo,ZodAny:jr,ZodUnknown:Xn,ZodNever:pn,ZodVoid:Ls,ZodArray:Wt,ZodObject:Ue,ZodUnion:Ao,ZodDiscriminatedUnion:ai,ZodIntersection:Ro,ZodTuple:tn,ZodRecord:xo,ZodMap:Fs,ZodSet:ar,ZodFunction:Ir,ZodLazy:Io,ZodLiteral:To,ZodEnum:jn,ZodNativeEnum:Co,ZodPromise:$r,ZodEffects:zt,ZodTransformer:zt,ZodOptional:Qt,ZodNullable:$n,ZodDefault:Oo,ZodCatch:Po,ZodNaN:Us,BRAND:Y_,ZodBranded:Dc,ZodPipeline:Ko,ZodReadonly:Mo,custom:ap,Schema:le,ZodSchema:le,late:J_,get ZodFirstPartyTypeKind(){return X},coerce:Ob,any:ob,array:cb,bigint:q_,boolean:dp,date:eb,discriminatedUnion:fb,effect:fd,enum:wb,function:bb,instanceof:X_,intersection:pb,lazy:vb,literal:yb,map:gb,nan:Q_,nativeEnum:kb,never:ib,null:rb,nullable:Ab,number:lp,object:lb,oboolean:Cb,onumber:Tb,optional:Eb,ostring:Ib,pipeline:xb,preprocess:Rb,promise:Sb,record:mb,set:_b,strictObject:db,string:cp,symbol:tb,transformer:fd,tuple:hb,undefined:nb,union:ub,unknown:sb,void:ab,NEVER:Pb,ZodIssueCode:j,quotelessJson:A_,ZodError:Et});const pd=i.enum(["app_start","sign_in","window_focus","surface_open"]),up=i.object({id:i.string().min(1),state:i.enum(["active","paused","disabled"])}).passthrough(),Mb=i.object({tenant_id:i.string().min(1),tenant_name:i.string().optional(),eligible:i.boolean(),endpoint:up.nullable()}).passthrough(),jb=i.object({code:i.string(),message:i.string(),details:i.record(i.unknown()).optional(),retry_after_seconds:i.number().optional()}).passthrough(),$b=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),Db=i.object({in_force:i.boolean(),notice_pending:i.boolean().catch(!1)}).passthrough().optional().catch(void 0),mO=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(Mb)}).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:jb.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:$b,default_on:Db}).passthrough(),Nb=i.object({version:i.string().min(1),consented_at:i.string().min(1),consented_via:i.string().min(1),current:i.boolean()}).passthrough(),gO=i.object({endpoint:up.extend({tenant_id:i.string().min(1),label:i.string().optional(),consent:Nb.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"),hd=i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:Lb,id:i.string().optional()}).passthrough(),md=i.object({mode:i.enum(["class_default","listed_only"]),allow:i.number(),deny:i.number()}).passthrough(),_O=i.object({allowlist:i.object({tenant_id:i.string().min(1),entries:i.array(hd)}).passthrough(),view:i.object({tenant_id:i.string().nullable(),entries:i.array(hd),directions:i.object({send:md,receive:md}),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(),bO=i.object({onboarding:i.literal("seen")}).passthrough();function Fb(e){return e?.default_on?.in_force===!0}function vO(e,t){const n=Ub(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function yO(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function wO(e,t){if(!e||!t||Fb(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 Bb=8,Ca=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],Hb=6*1024,Wb=512;function Bs(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const o=[];for(const s of n){if(o.length===Wb)break;const c=new URLSearchParams({order_ids:s}).toString().length+1;if(r+c>Hb)break;e.append("order_ids",s),o.push(s),r+=c}return o}function Gb(e,t,n){return Bs(new URLSearchParams(n),t,e)}const kO=3,zb=4096,SO=128,EO=/^[0-9a-f]{32}$/,Kb=/^\.+$/,Vb=new RegExp("\\p{Cf}","u"),Zb=/[/\\:]/,A=i.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),Yb=i.string().min(1).max(128),os=i.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),ss=i.string().min(1).max(32768),Jb=/^[a-f0-9]{12}$/,G=i.string().regex(Jb),Pi=i.string().regex(/^[a-f0-9]{12}$/),Mi=i.string().min(1).max(128),Xb=i.string().min(1).max(4096),zr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),ji=i.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),is=i.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),gd=i.string().regex(/^[a-f0-9]{32}$/),Qb=/^(\/|[A-Za-z]:[\\/])/,$i=i.string().min(1).max(4096).regex(Qb),_d=/^[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}$/),bd=i.string().min(1).max(512).nullish(),hr=i.string().regex(/^[A-Za-z0-9_-]{1,128}$/),Kr=i.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),qb=["credential_finite_share","credential_inheritance"],Hs=/^sha256:[0-9a-f]{64}$/,vd={operation:i.enum(qb),requestDigest:i.string().regex(Hs),disclosureDigest:i.string().regex(Hs)},Vr=i.string().regex(/^la_[0-9a-f]{16}$/),Zr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),yd=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(),ev=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(),wd=2e5,kd=8,tv=256,nv=100,Sd=16,rv=256,ov=100,sv=200,iv=1e6,av=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)),as=i.object({kind:i.enum(["agent","team"]),name:nt}).strict(),fp=i.enum(["claude","codex","omp"]),cv=i.record(i.string(),i.array(i.string().min(1).max(512)).max(5e3)),Ed={sources:i.array(fp).max(3).optional(),sessionIds:cv.optional(),all:i.boolean().optional(),includeSubagents:i.boolean().optional(),includeClearedSegments:i.boolean().optional(),includeMemory:i.boolean().optional(),includeInstructions:i.boolean().optional(),maxSessions:i.number().int().min(1).max(5e3).optional()},Di=i.object({provider:i.string().min(1).max(128),model_id:i.string().min(1).max(512),reasoning_effort:i.string().min(1).max(64).nullable(),fast_mode:i.boolean().nullable().optional()}).strict(),Ad=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(),Rd=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:av.nullable().optional()}).strict()).max(128).optional(),instructions:i.string().max(8e3).optional(),project:i.string().max(8e3).optional()}).strict(),lv=i.record(i.array(i.string().max(1024)).max(100)),Ni=i.array(A).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),dv=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"),xd=i.enum(["minutes","hours","days"]);function uv(e){return!Kb.test(e)}const AO=e=>As.safeParse(e).success,As=i.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(uv),Id=i.enum(["str","int","float","bool","list","dict"]),Td=i.string().max(16384),fv=2e3,Cd=i.string().min(1).max(fv),Od=i.string().min(1).max(64),pv=i.string().min(1).max(64),hv=i.string().min(1).max(64),Pd=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(),mv=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(),Oa=128,Md=2e3,jd=8e3,$d=64,Dd=64,ci=e=>[...e].length,Pa=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,gv=e=>e===9||e===10||e===11||e===12||e===13||e===133,_v=e=>e<=31||e>=127&&e<=159,bv=e=>Vb.test(String.fromCodePoint(e)),vv=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,cs=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},pp=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&Pa(t[n].codePointAt(0)??0);)n++;for(;r>n&&Pa(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},yv=e=>{let t="",n=!1;for(const r of e){if(Pa(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function wv(e){const t=pp(e);if(!t)return"must not be empty";if(ci(t)>Oa)return`must be at most ${Oa} characters`;if(Zb.test(t))return'must not contain "/", "\\" or ":"';if(cs(t,vv))return"must not contain Unicode bidirectional override characters";if(cs(t,gv))return"must not contain whitespace";if(cs(t,_v))return"must not contain control characters";if(cs(t,bv))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 RO(e){return yv(pp(e).normalize("NFKC").toLowerCase())}function kv(e){return e.trim()?ci(e)>Md?`must be at most ${Md} characters`:null:"must not be empty"}function Sv(e){return e.trim()?ci(e)>jd?`must be at most ${jd} characters`:null:"must not be empty"}function Ev(e){if(e.length>Dd)return`must hold at most ${Dd} items`;for(const t of e)if(!t.trim()||ci(t)>$d)return`must hold items of 1 to ${$d} characters`;return null}const Av=e=>wv(e)===null,Rv=i.string().refine(Av,{message:"That is not a name the hub can publish."}),xv=i.string().refine(e=>Sv(e)===null,{message:"That instruction body cannot be published."}),Iv=i.string().refine(e=>kv(e)===null,{message:"That description cannot be published."}),Tv=i.array(i.string()).refine(e=>Ev(e)===null,{message:"That tool list cannot be published."}),Li={requestId:fe.optional(),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()},Nd=i.object({name:Rv,description:Iv,instructions:xv,kind:i.enum(["role","specialist"]),when_to_use:i.string(),tools:Tv,effort:i.string(),delegate:i.boolean(),version:i.string(),categories:i.array(i.string()),tags:i.array(i.string())}).partial().strict(),Cv=i.enum(["team","agent"]),Ov=i.string().min(1).max(64),Pv=i.string().min(1).max(256),hp=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Fi=i.string().regex(hp,{message:"Letters, digits, dot, underscore and dash; no spaces."}),Mv=["planning","active","qa","validation","done","paused","archived"],Ld=i.enum(Mv),ls=i.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),Fd=i.array(i.string().min(1).max(24)).max(8),Sn=i.string().min(1).max(64),jv=1e3,Ud=240,Bd=80,$v=256,Dv=100,Nv=200,Lv=/^[a-z0-9][a-z0-9_-]{0,23}$/;function xO(e){return e?hp.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 IO(e){return Lv.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const ds=i.enum(["agent","team","skill"]),Ui=i.string().min(1).max(128).regex(/\S/),Hd=i.enum(Ca),Fv=i.object({visible:i.array(Hd).max(Ca.length),more:i.array(Hd).max(Ca.length)}).strict(),ln=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(ln).max(500).optional(),excludedIds:i.array(ln).max(500).optional()}).strict(),Uv=i.object({operationToken:i.string().min(1).max(512),reconcileIds:i.array(ln).max(500).optional()}).strict(),Gd=i.union([i.object({throughSeq:i.number().int().min(0).optional(),receipt:i.literal(!0).optional(),reconcileIds:i.array(ln).max(500).optional(),items:i.array(i.object({id:ln,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:ln,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:ln,revision:i.number().int().min(1)}).strict()).max(500)}).strict()]),Bv={pointer:"pointerdown",key:"keydown",wheel:"wheel"},Hv=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:fp,includeSubagents:i.boolean().optional()}).strict(),i.object({op:i.literal("imports.preview"),...Ed}).strict(),i.object({op:i.literal("imports.start"),...Ed}).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:fe,fields:Ad,expectedDefinitionRevision:bd.optional()}).strict(),i.object({op:i.literal("profiles.install"),name:nt,requestId:fe}).strict(),i.object({op:i.literal("profiles.create"),name:nt,requestId:fe,fields:Ad.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: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:fe,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:fe,linkId:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("hub.skillPublish"),requestId:fe,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: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:ds.optional(),name:nt.optional(),localId:Ui.optional()}).strict(),i.object({op:i.literal("hub.apply"),requestId:fe,kind:ds.optional(),name:nt.optional(),localId:Ui.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:ds.optional()}).strict(),i.object({op:i.literal("hub.retry"),requestId:fe,kind:ds.optional(),name:nt.optional(),localId:Ui.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:nt}).strict(),i.object({op:i.literal("teams.effective"),name:nt}).strict(),i.object({op:i.literal("teams.update"),name:nt,requestId:fe,fields:Rd,expectedDefinitionRevision:bd.optional()}).strict(),i.object({op:i.literal("teams.create"),requestId:fe,fields:Rd.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:Cv.optional(),scope_name:Ov.optional(),cursor:Pv.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(tv),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:as.optional(),purpose:i.literal("agents-config").optional(),model:Di.optional(),draftId:G.optional(),peer:hr.optional()}).strict(),i.object({op:i.literal("sessions.preview"),requestId:fe,cwd:i.string().min(1).max(4096),target:as.optional(),model:Di.optional()}).strict(),i.object({op:i.literal("sessions.draft"),requestId:fe,cwd:i.string().min(1).max(4096),target:as.optional(),model:Di.optional()}).strict(),i.object({op:i.literal("sessions.get"),sessionId:G,journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.files"),sessionId:G,scope:i.enum(["family","self"]).optional(),kind:i.string().max(256).optional(),q:i.string().max(256).optional(),sort:i.enum(["recent","name","kind","modified","created","size"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(8192).optional()}).strict(),i.object({op:i.literal("sessions.files.materialise"),sessionId:G,fileId:i.string().regex(/^[a-f0-9]{16}$/)}).strict(),i.object({op:i.literal("sessions.userAttachments"),sessionId:G}).strict(),i.object({op:i.literal("sessions.userAttachments.materialise"),sessionId:G,digest:i.string().regex(/^[a-f0-9]{32}$/)}).strict(),i.object({op:i.literal("sessions.history"),sessionId:G,beforeId:A.optional(),limit:i.number().int().min(1).max(500).optional(),openFrame:i.boolean().optional(),journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional(),sourceRead:i.enum(["metadata","payload"]).optional(),expectedJournalGeneration:i.string().min(1).max(128).optional()}).strict(),i.object({op:i.literal("sessions.checkpoints"),sessionId:G}).strict(),i.object({op:i.literal("sessions.checkpoints.warm"),sessionId:G,ids:i.array(A).max(Sd).optional(),limit:i.number().int().min(1).max(Sd).optional()}).strict(),i.object({op:i.literal("sessions.find"),sessionId:G,q:i.string().min(1).max(rv),limit:i.number().int().min(1).max(sv).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(wd),images:i.array(yd).max(kd).optional(),files:i.array(ev).max(Bb).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(wd).optional(),images:i.array(yd).max(kd).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(_d),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:Pi,anchor:Mi}).strict(),i.object({op:i.literal("supplements.restart"),sessionId:G,job:Pi,anchor:Mi}).strict(),i.object({op:i.literal("supplements.steer"),sessionId:G,job:Pi,anchor:Mi,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:As,value:Td,type:Id}).strict(),i.object({op:i.literal("sessions.variables.update"),sessionId:G,key:As,value:Td,type:Id}).strict(),i.object({op:i.literal("sessions.variables.delete"),sessionId:G,key:As}).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:Nd.optional(),...Li,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:Nd.optional(),...Li,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("team.publish"),teamId:A,...Li,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(Oa)}).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:Pd.extend({prompt:i.string().max(64e3),interval:i.number().int().min(1),unit:xd})}).strict(),i.object({op:i.literal("legacy.schedule.get"),scheduleId:A}).strict(),i.object({op:i.literal("legacy.schedule.edit"),scheduleId:A,schedule:Pd.extend({prompt:i.string().max(64e3).nullish(),interval:i.number().int().min(1).nullish(),unit:xd.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(iv)}).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:Xb.optional(),name:zr.optional()}).strict(),i.object({op:i.literal("skills.create"),requestId:fe,name:zr,copyFrom:zr}).strict(),i.object({op:i.literal("skills.update"),requestId:fe,name:zr,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:zr,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:os.optional(),value:ss.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(_d).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:as.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:Od,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:Od}).strict(),i.object({op:i.literal("monitors.cancel"),sessionId:G,monitorId:pv}).strict(),i.object({op:i.literal("jobs.cancel"),sessionId:G,jobId:hv}).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:ji.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(is).optional(),url:i.string().max(4096).optional(),headers:i.record(is).optional(),oauth:i.boolean().optional(),confirmed:i.boolean().optional(),operation_id:gd.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog"),cwd:$i.optional(),sessionId:G.optional()}).strict(),i.object({op:i.literal("mcp.catalog.control"),cwd:$i.optional(),control:i.object({action:i.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:ji.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(is).optional(),url:i.string().max(4096).optional(),headers:i.record(is).optional(),confirmed:i.boolean().optional(),operation_id:gd.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog.credentials"),header:i.string().min(1).max(128).optional(),cwd:$i.optional(),name:ji,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:ss}).strict(),i.object({op:i.literal("auth.cancel"),id:A}).strict(),i.object({op:i.literal("auth.key"),provider:A,value:ss}).strict(),i.object({op:i.literal("auth.logout"),provider:A}).strict(),i.object({op:i.literal("agent_messages.status"),boundary:pd}).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:Ni.optional(),files:i.array(A).min(1).max(10).refine(e=>new Set(e).size===e.length,"Duplicate file").optional(),mentions:dv.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:Ni.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:Ni.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:pd.optional()}).strict(),i.object({op:i.literal("team_bridge.link_preview.resolve"),url:i.string().min(1).max(zb),index:i.number().int().nonnegative(),expectedAccountId:A}).strict(),i.object({op:i.literal("settings.list")}).strict(),i.object({op:i.literal("settings.edit"),key:os,value:i.unknown().refine(e=>e!==void 0,"A setting value is required."),base:lv.optional()}).strict(),i.object({op:i.literal("settings.reset"),key:os}).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:mv}).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:os,value:ss}).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:hr,role:i.enum(["read","drive","admin"]),deviceId:hr.optional()}).strict(),i.object({op:i.literal("networks.member.remove"),networkId:hr,deviceId:hr,confirm:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("sessions.transfer"),sessionId:G,to:i.union([i.literal("local"),hr]),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:Kr}).strict(),i.object({op:i.literal("approvals.deny"),approvalId:Kr}).strict(),...["approvals.approveOperation","approvals.applyOperation"].map(e=>i.object({op:i.literal(e),approvalId:Kr,operation:i.literal("profile_save"),requestDigest:i.string().regex(Hs),disclosureDigest:i.string().regex(Hs)}).strict()),i.object({op:i.literal("approvals.approveCredential"),approvalId:Kr,...vd}).strict(),i.object({op:i.literal("approvals.applyCredential"),approvalId:Kr,...vd}).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:Sn}).strict(),i.object({op:i.literal("projects.create"),name:Fi,description:i.string().max(Ud).optional(),status:Ld.optional(),tags:Fd.optional()}).strict(),i.object({op:i.literal("projects.update"),key:Sn,fields:i.object({name:Fi.optional(),title:i.string().max(80).optional(),owner:i.string().max(80).optional(),team:i.string().max(80).optional(),description:i.string().max(Ud).optional(),status:Ld.optional(),progress:i.string().max(jv).optional(),tags:Fd.optional(),start_date:ls.optional(),target_date:ls.optional(),completed_at:ls.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:Sn,confirmed_name:Fi}).strict(),i.object({op:i.literal("projects.link"),key:Sn,sessionId:G}).strict(),i.object({op:i.literal("projects.unlink"),key:Sn,sessionId:G}).strict(),i.object({op:i.literal("projects.milestone"),key:Sn,name:i.string().min(1).max(Bd),targetDate:ls.optional(),completed:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.milestone.remove"),key:Sn,name:i.string().min(1).max(Bd)}).strict(),i.object({op:i.literal("projects.request_update"),key:Sn}).strict(),i.object({op:i.literal("projects.search"),q:i.string().min(1).max($v),limit:i.number().int().min(1).max(Nv).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:Vr}).strict(),i.object({op:i.literal("library.update"),id:Vr,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:Zr,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:Zr}).strict(),i.object({op:i.literal("library.tags.merge"),id:Zr,into:Zr}).strict(),i.object({op:i.literal("library.tags.assign"),id:Vr,tags:i.array(Zr).max(64),primary:i.string().max(128).optional()}).strict(),i.object({op:i.literal("library.chat.link"),id:Vr,sessionId:G}).strict(),i.object({op:i.literal("library.chat.clear"),id:Vr}).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:Fv}).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:ln}).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([Gd,Wd,Uv])}).strict(),i.object({op:i.literal("notifications.dismiss"),verb:i.enum(["dismiss","undismiss"]),target:i.union([Gd,Wd])}).strict(),i.object({op:i.literal("notifications.seen"),items:i.array(i.object({id:ln,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()]);Hv.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 Ct={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},Wv={runtimeUnreachable:"runtime_unreachable"},li="runtime_busy",mp="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 gp=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(),Gv=i.object({path:i.string(),size:i.number().nullish(),preview:i.string().nullish(),preview_truncated:i.boolean().nullish()}).passthrough(),zv=gp.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(Gv).nullish(),files_total:i.number().nullish(),files_truncated:i.boolean().nullish(),publish_budget:i.object({limit:i.number(),total:i.number()}).passthrough().nullish()}).passthrough(),TO=i.object({skills:i.array(gp),scope:i.string().nullish(),detail:i.string().nullish(),skill_detail:zv.nullish(),warning_count:i.number().nullish(),version:i.string().nullish()}).passthrough(),CO=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(),OO="aside_adopt_refused",Kv=["session_closed","open_tool_batch","turn_running"];function PO(e){if(typeof e!="object"||e===null)return;const t=e.reason;return Kv.find(n=>n===t)}const Vv={[Ct.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[Ct.refused]:"ui.common.errors.desktop_refusal.refused",[Ct.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[Ct.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed"},Ma={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 di(e){return e!==void 0&&Object.values(Ct).includes(e)}function Zv(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return Ct.refused;if(t===503)return Ct.planeClosed}}const MO=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(),jO=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),Yv=88e4,Jv=11e5,Xv=2e4,Qv=9e4,qv=new Set(["analytics.get","analytics.models","sessions.report"]),ey=new Set(["usage.get"]),ty=new Set(["networks.list","peers.list"]),ny=new Set(["usage.reset"]),ry=new Set([...qv,...ey,...ty,...ny]),oy=90,sy=30,iy=300,ay=10,_p=15,cy=1e4;function ly(e){const n=e.to==="local"||e.keep?iy:sy,r=Math.max(0,e.waitS??0);return(oy+n+ay+_p)*1e3+r*1e3}const dy=18e4,uy=dy+15e3,fy=120,py=135e3,hy=93e4,bp=(fy+30+_p)*1e3,my=6e4,gy=5*bp,_y=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function by(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 bp;case"hub.check":return my;case"hub.applyAll":return gy;default:return null}}function vy(e){if(typeof e!="string"&&e.op==="sessions.transfer")return ly(e)+cy;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return uy;if(t==="tunnel.setup.run")return hy;if(t==="tunnel.setup.plan")return py;const n=by(t);return n!==null?n:ry.has(t)?Qv:Xv}const yy=5e3;function vp(e){return vy(e)+yy}const Nc="deadline_exceeded",yp="foreground_required",wp="View these completions in the foreground before marking them read.",wy=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"]),ky=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Sy(e,t){const n=Math.round(t/1e3),r=Nc;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.`}:_y.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:wy.has(e)?{code:r,message:ky.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 $O=Yv,DO=Jv;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 Ey(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function zd(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 Bi(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 Hi(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 Kd(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 Yr(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 Wi(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function Ay(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:Kd(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:Kd(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??nv)});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"),Bs(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),Bs(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??ov)});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":{Hi(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??{},...Bi(e)}}}case"agent.republish":{Hi(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??{},...Bi(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{Hi(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:Bi(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,...Ey(e),message:e.message,...zd(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...zd(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${Wi(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${Wi(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)}${Wi(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"?"":Yr(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${Yr(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)}${Yr(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)}${Yr(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}${Yr(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??Dv)})}`,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,...Ry(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:Bv[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function Ry(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 NO=64,LO=64*1024*1024,FO="superseded_completion_token",UO="store_busy",xy="session_is_remote",Iy="owner_build_behind";function BO(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 Er(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 Ty(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const HO=e=>typeof e?.goal_status=="string",WO=e=>(e?.goal??"").trim().length>0;function Cy(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function Oy(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 po={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 Py(e){return e?e===po.notPaired?"notPaired":e===po.serverDown?"serverDown":e===po.frameBudget?"frameTooLarge":"lost":"lost"}const Vd=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},My=e=>e?Vd(e):Vd,jy=e=>e;function $y(e,t=jy){const n=Jl.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return Jl.useDebugValue(n),n}const Zd=e=>{const t=My(e),n=r=>$y(t,r);return Object.assign(n,t),n},Vo=e=>e?Zd(e):Zd;function kp(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 ja=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return ja(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return ja(r)(n)}}}},Dy=(e,t)=>(n,r,o)=>{let s={storage:kp(()=>localStorage),partialize:b=>b,version:0,merge:(b,v)=>({...v,...b}),...t},a=!1;const c=new Set,l=new Set;let d=s.storage;if(!d)return e((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),n(...b)},r,o);const u=()=>{const b=s.partialize({...r()});return d.setItem(s.name,{state:b,version:s.version})},f=o.setState;o.setState=(b,v)=>{f(b,v),u()};const h=e((...b)=>{n(...b),u()},r,o);o.getInitialState=()=>h;let m;const y=()=>{var b,v;if(!d)return;a=!1,c.forEach(E=>{var k;return E((k=r())!=null?k:h)});const p=((v=s.onRehydrateStorage)==null?void 0:v.call(s,(b=r())!=null?b:h))||void 0;return ja(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,N]=E;if(m=s.merge(N,(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:b=>{s={...s,...b},b.storage&&(d=b.storage)},clearStorage:()=>{d?.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>y(),hasHydrated:()=>a,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(l.add(b),()=>{l.delete(b)})},s.skipHydration||y(),m||h},ui=Dy,Ny=(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 Sp=Vo()(ui(e=>({notice:null,receive:t=>e(n=>Ny(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:kp(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function Lc(e){return _(Vv[e])}let $a=null;function Fy(e){if(e===null){$a=null;return}$a={openFrame:e.openFrame===!0,journalOrder:e.journalOrder===!0,peerJournalSource:e.peerJournalSource===!0}}function Ep(){return $a}async function Ap(e){if(window.api?.desktop)try{return await Uy(window.api.desktop.request(e),e)}catch(n){throw n instanceof Pe?n:Ky(n)?new Dn(wp,yp):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 Uy(e,t){const n=vp(t);let r;return Promise.race([e,new Promise((o,s)=>{r=setTimeout(()=>{const a=Sy(t.op,n);s(new Pe(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const Rp="This server did not answer the request for its desktop controls.",By=()=>_("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 Dn extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function Fc(e,t){return e instanceof Pe||e instanceof Dn?di(e.code)?Lc(e.code):e.message===Rp?By():e.message:t}function Hy(e,t,n,r){return typeof r=="string"?r:n===Ma.noCredential?Ct.noCredential:n===Ma.transportFailed?Ct.transportFailed:Zv(Ay(e).path,t)}async function Ye(e){const t=await Ap(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??Rp,void 0,Hy(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"&&Wy(n?.result),n?.result}function Wy(e){if(typeof e!="object"||e===null)return;const t=Ly(e.delegated_cleanup_notice);t&&Sp.getState().receive(t)}async function Gy(){try{await Ye({op:"delegated_cleanup_notice.ack"})}catch{}}async function GO(){Sp.getState().dismiss(),await Gy()}function zy(e){return e instanceof Pe&&e.code===Nc}function zO(e){if(!(e instanceof Pe))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===Iy:e.code===xy}function KO(e){return e instanceof Dn&&e.code===yp}function Ky(e){return e instanceof Error&&e.message.includes(wp)}async function VO(e){const t=await Ap(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function ZO(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 Vy(e,t,n){const r=Jy(e);return r.record?(n?.("adopted"),Yd(e.sessionId,"adopted","none",Da(e),null),qy(r.record,t)):(Gt&&dn(),n?.("requested"),Yd(e.sessionId,"requested",r.refusal,Da(e),r.held),xp(e,t))}const Zy=6e4,Yy=512;function Da(e){return{openFrame:e.openFrame===!0,journalOrder:e.journalOrder===!0,peerJournalSource:e.peerJournalSource===!0}}let Gt=null,Qn=null;function dn(){Qn!==null&&(clearTimeout(Qn),Qn=null);const e=Gt;Gt=null,e&&(e.live=null,e.buffered=[],e.disposeTransport())}function YO(){return Gt?.sessionId??null}function JO(e){!e||Gt?.sessionId!==e||dn()}function XO(e,t){if(!e||Gt?.sessionId===e)return;dn();const n=Ep(),r={openFrame:n?.openFrame===!0,journalOrder:n?.journalOrder===!0,peerJournalSource:n?.peerJournalSource===!0&&t?.remoteOwned===!0};let o=!1;const s={sessionId:e,negotiation:r,buffered:[],live:null,ended:!1,disposeTransport:()=>{}};if(s.disposeTransport=xp({sessionId:e,...r.openFrame?{openFrame:!0}:{},...r.journalOrder?{journalOrder:!0}:{},...r.peerJournalSource?{peerJournalSource:!0}:{}},c=>{if(s.live){s.live(c);return}if(c.kind==="error"||c.kind==="end"){s.ended=!0,o=!0,dn();return}if(s.buffered.length>=Yy){o=!0,dn();return}s.buffered.push(c)}),o){s.disposeTransport();return}Gt=s;const a=setTimeout(()=>{Gt===s&&dn()},Zy);typeof a.unref=="function"&&a.unref(),Qn=a}function Jy(e){const t=Gt;if(!t)return{record:null,refusal:"none",held:null};if(t.ended)return dn(),{record:null,refusal:"ended",held:t.negotiation};if(t.sessionId!==e.sessionId)return{record:null,refusal:"other-session",held:null};const n=Da(e);return e.epoch!==void 0||e.afterSeq!==void 0||(e.orderIds?.length??0)>0?(dn(),{record:null,refusal:"resuming",held:t.negotiation}):n.openFrame!==t.negotiation.openFrame||n.journalOrder!==t.negotiation.journalOrder||n.peerJournalSource!==t.negotiation.peerJournalSource?(dn(),{record:null,refusal:"negotiation",held:t.negotiation}):{record:t,refusal:null,held:t.negotiation}}const Xy=/^[A-Za-z0-9_-]{1,80}$/,Qy="[stream-prewarm]";function Yd(e,t,n,r,o){if(t==="requested"&&n==="none")return;const s=Xy.test(e)?e:"?",a=l=>[l.openFrame?"1":"0",l.journalOrder?"1":"0",l.peerJournalSource?"1":"0"].join(","),c=[Qy,`session=${s}`,`decision=${t}`];t==="requested"&&(c.push(`why=${n}`,`asked=${a(r)}`),o&&c.push(`prewarm=${a(o)}`),n==="negotiation"&&c.push(`caps=${Ep()?"recorded":"absent"}`)),console.warn(c.join(" "))}function qy(e,t){const n=e.buffered;e.buffered=[],e.live=t,Qn!==null&&(clearTimeout(Qn),Qn=null),Gt===e&&(Gt=null);let r=!1;return queueMicrotask(()=>{if(!r)for(const o of n)t(o)}),()=>{r||(r=!0,e.live=null,e.disposeTransport())}}function xp(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"),Bs(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:po.ended}),o.close())},()=>{o.close(),t({kind:"end"})}}async function QO(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&&di(a)?a:s===Ma.noCredential?Ct.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 qO(e){return e.kind==="error"?di(e.code)?new Dn(Lc(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function e0(e){if(zy(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 Ip={unreachable:"",deadline:"",unauthorized:"",get outdated(){return _("ui.common.connection.backend.remedy_outdated")},unknown:""},Na={get unreachable(){return _("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return _("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return _("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return _("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function t0(e,t){const n=e0(t);return[e,Na[n],Ip[n]].filter(Boolean).join(" ")}const La={get successor(){return _("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return _("ui.common.connection.backend.pairing_unpaired")}},n0={get successor(){return _("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return _("ui.common.connection.backend.pane_unpaired")}};function eP(e,t){return e!=="unpaired"?null:n0[t??"unpaired"]}function tP(e,t){return e!=="unpaired"?null:La[t??"unpaired"]}function nP(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 rP(e){const{kind:t,unpaired:n,missing:r,answered:o,cause:s=null}=e;if(s!==null)return La[s];if(!o){if(t==="unreachable")return _("ui.common.connection.backend.compatibility_unreachable",{diagnosis:Na.unreachable});if(t==="unauthorized")return _("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return _("ui.common.connection.backend.compatibility_deadline",{diagnosis:Na.deadline});if(t==="outdated")return _("ui.common.connection.backend.compatibility_outdated",{remedy:Ip.outdated})}return n?La.unpaired:o?_("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):_("ui.common.connection.backend.compatibility_unknown")}const r0=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function oP(e,t=null){return t!==null||!e?!0:r0.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function o0(e,t){return t instanceof Pe&&t.status===null?!1:e<1}function sP(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 s0={get successor(){return _("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.card_credential_refused")},get unpaired(){return _("ui.common.connection.backend.card_unpaired")}};function iP(e,t,n){return e===null?{sentence:t0(t,n),remedy:!0}:{sentence:s0[e],remedy:ep(e)}}const Tp={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]},i0=3e4,a0=15e3;function c0(e){return e?.desktop_available===!0}function aP(){const{client:e,provided:t}=E_();return qf({enabled:t,queryKey:Tp.capabilities,queryFn:async()=>{try{const n=await Ye({op:"capabilities"});return Fy(d0(n)),n}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>c0(n.state.data)?i0:a0,refetchIntervalInBackground:!0},e)}function l0(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function Gi(e,t,n=1){return l0(e,t,n)==="enabled"}function d0(e){return{openFrame:Gi(e,"open_frame"),journalOrder:Gi(e,"journal_order"),peerJournalSource:Gi(e,"peer_journal_source")}}function cP(e){return qf({queryKey:Tp.providers,queryFn:()=>Ye({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:o0})}let fi=!1,Ws=!1;const Gs=[];function lP(){typeof window>"u"||!window.__loDevDriver?.armed||(fi=!0,Ws=!1,Gs.length=0)}function u0(){return fi}function f0(e){if(fi)try{if(Gs.length>=256){Ws=!0;return}Gs.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{Ws=!0}}function dP(){return{armed:fi,fault:Ws,receipts:Gs.map(e=>({...e}))}}const Jr=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function p0(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=Jr(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=Jr(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>Jr(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=Jr(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=Jr(a);c!==null&&o.has(c)?(s.push(a),o.delete(c)):c===null&&s.push(a)}return s}const Fa=e=>({revision:xt(e),demand:e.orderDemand}),qn=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Dr(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 y of a.records){const b=y.sourceEntryId??(y.kind==="tool"||y.kind==="supplement"?null:y.id);typeof b=="string"&&b.length>0&&b.length<=128&&m.set(b,h)}l={...l,...m.size>0?{journalBodyOwed:m}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(h,m,y)=>{if(!qn(y))return;const b=d.get(h);b&&b.seq>=y||(d===u&&(d=new Map(d)),d.set(h,{entryId:m,seq:y}))};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 Uc(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 Cp(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 Op(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 h0=Number.MAX_SAFE_INTEGER;function m0(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:h0})}}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 Pp(e,t){return{floor:g0(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:m0(e,t)}}function Mp(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 jp(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 g0(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 $p(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 zs(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 _0(e,t);const n=e.journalGeneration,r=e.journalPositions;let o=!1,s=!1;const a=t.map(b=>{b.sourcePrecedes!==void 0&&(s=!0);let p=[r?.get(b.sourceEntryId??b.id),r?.get(b.id)].filter(C=>C!==void 0).sort((C,N)=>N.seq-C.seq)[0];if(b.journalGeneration===n&&qn(b.journalSeq)&&(!p||b.journalSeq>p.seq)&&(p={entryId:b.sourceEntryId??b.id,seq:b.journalSeq}),!p||!n||!(b.kind==="user"&&(b.provisional===!0||b.local===!0))&&b.sourceEntryId===p.entryId&&b.journalSeq===p.seq&&b.journalGeneration===n)return b;o=!0;let k={...b,sourceEntryId:p.entryId,journalSeq:p.seq,journalGeneration:n};if(k.kind==="user"){const{provisional:C,local:N,...O}=k;k=O}return k});Cp(a,b=>b.journalGeneration===n&&qn(b.journalSeq))&&(o=!0);const l=new Map,d=new Map(a.map(b=>[b.id,b])),u=$p(d,b=>b!==void 0&&b.journalGeneration===n&&qn(b.journalSeq)?b.journalSeq:void 0),f=b=>u(b)!==void 0,h=s?Pp(a,u):void 0,m=(b,v)=>{const p=u(b);if(b.kind==="user"&&b.provisional===!0&&p===void 0)return[1,0,0,0,v];const E=b.kind==="supplement"?b.anchor:b.kind==="tool"?e.journalCallOwners?.get(b.toolCallId)??e.argsByCall.get(b.toolCallId)?.anchorId:void 0,k=typeof E=="string"?u(d.get(E)):void 0,C=k===void 0&&p===void 0?Mp(b,d,u,h):void 0,N=p===void 0&&C===void 0?Op(b,d,f,u,l):void 0,O=k??p??C?.seq??N;if(O===void 0){const R=jp(b,d,h);return[1,R?.slot??v,R?-R.depth:0,0,v]}return[0,O,k!==void 0?1:p!==void 0?0:C!==void 0?C.slot:2,p??Number.MAX_SAFE_INTEGER,v]},y=a.map((b,v)=>({record:b,index:v,rank:m(b,v)}));return y.sort((b,v)=>{for(let p=0;p<b.rank.length;p++){const E=b.rank[p]-v.rank[p];if(E)return E}return 0}),!o&&y.every((b,v)=>b.index===v)?zs(e,t):zs(e,y.map(b=>b.record))}function _0(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,N)=>N.seq-C.seq)[0];p.journalGeneration===n&&qn(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();Cp(l,p=>p.journalGeneration===n&&qn(p.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(p=>[p.id,p])),h=$p(f,p=>a(p)?.seq),m=p=>h(p)!==void 0,y=s?Pp(l,h):void 0,b=(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,N=typeof C=="string"?h(f.get(C)):void 0,O=N===void 0&&k===void 0?Mp(p,f,h,y):void 0,R=k===void 0&&O===void 0?Op(p,f,m,h,u):void 0,g=N??k??O?.seq??R;if(g===void 0){const w=jp(p,f,y);return[1,w?.slot??E,w?-w.depth:0,0,E]}return[0,g,N!==void 0?1:k!==void 0?0:O!==void 0?O.slot:2,k??Number.MAX_SAFE_INTEGER,E]},v=l.map((p,E)=>({record:p,index:E,rank:b(p,E)}));return v.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&&v.every((p,E)=>p.index===E)?zs(e,t):zs(e,v.map(p=>p.record))}function Zt(e){const t=e.records.filter(o=>o.kind==="user"&&o.provisional===!0),n=e.records.filter(o=>o.journalGeneration!==e.journalGeneration||!qn(o.journalSeq)),r=[...t,...n].map(o=>o.sourceEntryId??(o.kind==="tool"||o.kind==="supplement"?null:o.id));if(r.push(...Bc(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 Bc(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 Np(e,t){const n=e.journalPositions;return Zt(e).filter(r=>!n?.has(r)&&!t?.has(r))}const xt=e=>e.orderRevision??0;async function b0(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"?Bc(c):l==="lookup"?Np(c):Zt(c);let o=e.getTranscript().journalGeneration,s=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=Fa(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",h=Gb(r(c,f).filter(v=>!n(f).has(v)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),m=await e.read(h,f);if(!e.isCurrent()||xt(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(m,d,l),!e.isCurrent())return{kind:"stale"};const y=e.getTranscript(),b=e.page(m);if(b.journal_order_state==="ready"&&b.journal_generation===y.journalGeneration){b.journal_generation!==o&&(t.clear(),o=b.journal_generation);for(const E of h)n(f).add(E);if(y.orderNeedsReconcile){if(y.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear();continue}if(f==="payload"){const E=(b.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 v=e.sweep?.(y,n);if(v?.kind==="none")return{kind:"complete",transcript:y};const p=v?.kind??"authority";if(r(y,p).some(E=>!n(p).has(E)))continue;return{kind:"complete",transcript:y}}if(!y.orderNeedsReconcile||y.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 zi(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function Jd(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function uP(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=zi(s.action_count);if(a===null)continue;const c={actions:a,workedSeconds:Jd(s.worked_seconds),failed:zi(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:zi(s.cross_session_action_count),crossSessionWorkedSeconds:Jd(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 v0(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 y0(e,t,n){const r=v0(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 Hc=new Set,Nn="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Wc=new RegExp(`[${Nn}]`),w0=new RegExp(`[${Nn}]+`),fP=new RegExp(`[${Nn}]+`,"g"),k0=new RegExp(`^[${Nn}]+|[${Nn}]+$`,"g"),S0=new RegExp(`^[${Nn}]+`),pP=new RegExp(`[^${Nn}]`);function qt(e){return e.replace(k0,"")}function jo(e){return e.replace(S0,"")}function Lp(e,t){return t===0||Wc.test(e[t-1])}function Fp(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&Lp(e,n)&&t.push(n);return t}function Gc(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
|
|
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 E0(e,t){if(t.size===0)return null;for(const n of Fp(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 zc(e,t,n){const r=E0(e,n);let o=null;for(const s of Fp(e)){if(s===r)return t>s?s:o;s<=t&&(o=s)}return o}function A0(e,t=null,n=Hc){const{line:r,lineStart:o,column:s}=Gc(e,t),a=zc(r,s,n);if(a===null)return null;let c=a+1;for(;c<r.length&&!Wc.test(r[c]);)c++;return s>c?null:{start:o+a,query:r.slice(a+1,c),end:o+c}}function hP(e,t=null,n=Hc){const{line:r,lineStart:o,column:s}=Gc(e,t),a=zc(r,s,n);return a===null?null:{start:o+a,end:o+r.length}}function R0(e,t,n=null,r=Hc){const{line:o,lineStart:s,column:a}=Gc(e,n),c=r.size>0?r:new Set(t.map(m=>m.toLowerCase())),l=zc(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 Xd(e,t){return qt(e.slice(0,t))===""}function mP(e,t,n,r){const o=R0(e,r,t,n);if(o!==null&&Xd(e,o.tokenStart))return"argument";const s=A0(e,t,n);return s!==null&&Xd(e,s.start)?"command":null}function gP(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 x0=1e3,I0=900,T0=40,Up=3;function C0(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(T0,n))}function Bp(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n?n===r?x0:r.startsWith(n)?I0:C0(n,r):0}function O0(e){const n=qt(e).split(w0).pop()??"";return n.startsWith("/")?n.slice(1):n}function P0(e,t){const n=O0(e),r=[];return t.forEach((o,s)=>{let a=0,c=o.name;for(const l of[o.name,...o.aliases]){const d=Bp(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 _P(e,t){if(!e)return t.map(s=>({name:s.name,command:s}));const n=P0(`/${e}`,t);if(e.length>=Up)return n;const r=e.toLowerCase(),o=n.filter(({name:s})=>s.toLowerCase().startsWith(r));return o.length>0?o:n}function Qd(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=>Bp(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 qd=/^-+/;function bP(e,t,n,r,o){if(o)return!0;const s=qt(e).toLowerCase(),a=qt(t).toLowerCase();return s===a||s.length>0&&s.replace(qd,"")===a.replace(qd,"")?!0:!r&&n<=1}const M0=new RegExp("\\p{Ll}","u");function Hp(e){for(const t of e)if(M0.test(t))return!0;return!1}function vP(e,t,n){if(n){if(!e)return t.map(a=>({name:a.name,choice:a}));const r=Qd(e,t);if(e.length>=Up)return r;const o=e.toLowerCase(),s=r.filter(a=>a.name.toLowerCase().startsWith(o));return s.length>0?s:r}return Hp(e)?Qd(e,t).filter(r=>r.name.startsWith(e)):[]}const j0=/<skill name="([^"]*)" invocation="([^"]*)">/,$0=/[A-Za-z0-9]/,D0=/[A-Za-z0-9._-]/,N0=/[._-]/;function L0(e,t){if(t>=e.length||!$0.test(e[t]))return t;let n=t+1;for(;n<e.length&&D0.test(e[n]);)n++;return n}function F0(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!Lp(e,n)){n+=1;continue}const r=L0(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 U0(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||Hp(c)){const l=o.get(c.toLowerCase());if(l!==void 0)return{end:a,name:l}}if(a>t+2&&N0.test(e[a-1])){a-=1;continue}return null}}function B0(e,t,n={}){return Wp(e,t,n.skipSpans??[],!0)}function yP(e,t,n={}){return Wp(e,t,n.skipSpans??[],!1)}function Wp(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 F0(e)){if(n.some(([f,h])=>f<=l.start&&l.start<h))continue;const d=jo(e.slice(0,l.start))==="",u=U0(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 Ar="<operator-skills>",Ks="</operator-skills>",ao=`
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
${
|
|
8
|
-
</skill>`);return
|
|
9
|
-
`)){if(o>0){s.startsWith("</skill>")&&(o-=1);continue}const a=
|
|
10
|
-
---`);r!==-1&&(t=n.slice(r+4))}return
|
|
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
|
|
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
|
+
`,Gp="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>`.",Kc="",H0=Ar.replace("<",`<${Kc}`),W0=Ks.replace("<",`<${Kc}`),G0=`<${Kc}skill name=`,z0=/^<skill name="([^"]*)">/;function K0(e){return e.replace(/<\/operator-skills>/g,W0).replace(/<operator-skills>/g,H0).replace(/<skill name="/g,G0)}function wP(e){const t=e.map(({name:n,body:r})=>`<skill name="${n}">
|
|
7
|
+
${K0(r)}
|
|
8
|
+
</skill>`);return Ar+ao+Gp+ao+t.join(ao)+ao+Ks}function Vc(e){const t=[],n=Ar+ao+Gp;let r=0;for(;;){const o=e.indexOf(n,r);if(o===-1)return t;const s=e.indexOf(Ks,o+n.length),a=e.indexOf(Ar,o+Ar.length);if(s===-1||a!==-1&&a<s){r=o+Ar.length;continue}const c=s+Ks.length;t.push([o,c]),r=c}}function V0(e){const t=[];for(const[n,r]of Vc(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=z0.exec(s);a!==null&&(t.push(a[1]),o=1)}}return t}function kP(e,t){const n=Vc(e),r=B0(e,t,{skipSpans:n});if(r.length===0)return[];const o=new Set(V0(e));return r.filter(s=>!o.has(s.name))}const eu=new RegExp(`[${Nn}]+$`);function zp(e){const t=Vc(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(eu,"")),r=a}n.push(e.slice(r).replace(eu,""));let o="";for(const s of n)s&&(o&&!Wc.test(s[0])&&(o+=" "),o+=s);return o}function SP(e){if(!e||qt(e)==="")return!1;let t=jo(e);if(t.startsWith("---")){const n=t.slice(3),r=n.indexOf(`
|
|
10
|
+
---`);r!==-1&&(t=n.slice(r+4))}return qt(t)!==""}function Z0(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 Y0(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 Ki;const J0=new Uint8Array(16);function X0(){if(!Ki){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ki=crypto.getRandomValues.bind(crypto)}return Ki(J0)}const Q0=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),tu={randomUUID:Q0};function q0(e,t,n){if(tu.randomUUID&&!e)return tu.randomUUID();e=e||{};const r=e.random??e.rng?.()??X0();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,Y0(r)}const Kp=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,Ua=e=>{let t=e;for(;;){const n=Kp.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},nu=e=>{const t=[];let n=e;for(;;){const r=Kp.exec(n);if(r===null)break;t.push({id:q0(),text:r[1]}),n=n.slice(r[0].length)}return{replies:t,remainingContent:n.trim()}};function pi(e){return Zc(e)?.skill}const ew=/^\s/,tw=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,nw=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function rw(e){const t=jo(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 ow(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function ru(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,"'"):ow(a);return c===""?null:c}return null}function sw(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!==""&&tw.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(!ew.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 ru(c,'"');if(c.startsWith("'"))return ru(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function Zc(e){const{prefix:t,rest:n}=Ua(e),r=n.slice(0,n.length-jo(n).length),o=jo(n),s=nw.exec(o);if(s===null)return null;const a=j0.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=rw(d),f=u===null?null:sw(d.slice(0,u)),h=a[1],m=Z0(a[2]);return{text:t+r+m,skill:{name:h,token:`$${h}`,request:qt(o.slice(l+8)),purpose:f,body:qt(u===null?d:d.slice(u))}}}function EP(e){const t=Zc(e);if(t!==null)return t.text;const n=zp(e);return n===e?e:qt(n)}function iw(e){const t=Zc(e);if(t===null){const r=zp(e);if(r===e)return null;const{prefix:o}=Ua(e);return{replies:nu(e).replies,text:r.slice(o.length).trimStart()}}const{prefix:n}=Ua(e);return{replies:nu(e).replies,text:t.text.slice(n.length).trimStart()}}function AP(e){return iw(e)?.text??e}const aw=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"]]),cw=/\blabel=(['"])(.*?)\1/,lw=/\bjob=(['"])(.*?)\1/,dw=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function Ba(e){const t=typeof e.text=="string"?e.text:"",n=dw.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:
|
|
17
|
-
`,1)[0])?.[2])),sender:
|
|
15
|
+
`)??-1,a=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&o>=0?aw.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:Nr(e.label??(n&&cw.exec(n[0].split(`
|
|
16
|
+
`,1)[0])?.[2])),jobId:Nr(e.job_id??(n&&lw.exec(n[0].split(`
|
|
17
|
+
`,1)[0])?.[2])),sender:Qp(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 RP(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 uw(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 xP(e){return uw(e)!==null}const Vp=/\s+/,fw=/[\\/]+$/,pw=/[\\/]/,Zp=`
|
|
18
18
|
|
|
19
|
-
`,
|
|
20
|
-
`)){const n=
|
|
19
|
+
`,hw=" — cancel with wake(",mw=120,Yp=/(?:\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,gw=new RegExp("\\p{Cf}","gu"),_w=4096;function Nr(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(Yp,"").replace(gw,"").split(Vp).filter(Boolean).join(" ").slice(0,mw)}const IP={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function Jp(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(fw,"");if(t){const n=t.split(pw).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function Xp(e){const{name:t,quoted:n}=Jp(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function bw(e){const{name:t,quoted:n}=Jp(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 TP(e,t){return t.trim()?!0:bw(e)!==Xp(e)}function vw(e){for(const t of e.slice(0,_w).split(`
|
|
20
|
+
`)){const n=Nr(t);if(n)return n}return""}function CP(e,t){const n=Xp(e),r=vw(t);return r?`${n} · ${r}`:n}function Vi(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const yw=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,ww=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,kw=/^<peer-session-message[^>]*>/,Sw=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function Qp(e){const t=String(e.text??e.detail??""),n=yw.exec(t.trim()),r={};if(n)for(const d of n[1].matchAll(Sw))r[d[1]]=d[2]??d[3]??d[4]??"";const o=n?n[2]:"",a=(String(e.body??"").trim()||o||(n?"":t.trim().replace(kw,""))).replace(ww,"").trim(),c=e.sender??{},l=(d,u)=>Nr(d)||Nr(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 Ew(e){return!!e.wake_catchup}function Aw(e){return e.hidden===!0}function OP(e){let t=e.split(Zp)[0]??"";t=t.split(Vp).filter(Boolean).join(" "),t=t.split(hw)[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 PP(e){const t=e.indexOf(Zp);return t===-1?"":e.slice(t+2).trim()}const us=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},Xr=e=>typeof e=="string"?Nr(e):"";function Rw(e){const t=us(e.bridge_receipt),n=t.v===1,r=us(n?t.sender:e.sender),o=n?us(t.conversation):{},s=n?t.attachment_count:void 0;return{sender:{name:Xr(r.name),...r.kind==="human"||r.kind==="agent"?{kind:r.kind}:{},...Xr(r.organization)?{organization:Xr(r.organization)}:{}},conversation:{...o.kind==="dm"||o.kind==="group"||o.kind==="channel"?{kind:o.kind}:{},...Xr(o.label)?{label:Xr(o.label)}:{}},...typeof s=="number"&&Number.isSafeInteger(s)&&s>=0?{attachmentCount:s}:{}}}const xw=new Set(["channel_post","channel_create","channel_history","channel_thread","react","shared_history"]),Iw=new Set(["channel_post","dm","send","reply"]),Tw=new Set(["take_up","ack","send","reply","channels","channel_create","channel_post","channel_history","react","channel_thread","directory","dm","shared_conversations","shared_history"]),Cw=/^(?:bcv|bcmsg|acc|ep)_/i,Ow=/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]|\x9b[0-?]*[ -/]*[@-~]/g,Pw=/[\x00-\x08\x0e-\x1f\x7f-\x9f]/g,qp=new RegExp("(?![\\u200c\\u200d])\\p{Cf}","gu");function MP(e){return e.replace(qp,"")}const Mw=/[\t\n\r\v\f ]+/,jw=/\r\n|\r|\n/,$w=/^bcv_\S+$/,Dw=200;function $o(e){return typeof e!="string"?null:e.replace(Ow,"").replace(Pw,"").replace(qp,"").split(Mw).filter(Boolean).join(" ").slice(0,Dw)||null}function Zn(e){const t=$o(e);return t&&!Cw.test(t)?t:null}const Nw=/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d{1,9}[.)]\s+)+/u,Lw=/!?\[([^\]]*)\]\([^)]*\)/gu,Fw=/\*\*|__|~~|`+/gu,Uw=/(?<![\p{L}\p{N}_*])[*_](?=[^\s*_])|(?<=[^\s*_])[*_](?![\p{L}\p{N}_*])/gu,Bw=/^[-=*_~`#> ]*$/;function Hw(e){return e.replace(Nw,"").replace(Lw,"$1").replace(Fw,"").replace(Uw,"")}function Zi(e){if(typeof e!="string")return null;for(const t of e.split(jw)){const n=$o(Hw(t));if(n&&!Bw.test(n))return n}return null}const hn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function eh(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 Rw(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 Kp(e){return dw.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function Vp(e,t,n){const r=Kn(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?Kn(c.slice(0,l)):null;if(d)return d}}if(e==="channel_create"){const a=fn(zp(n?.content)),c=Kn(a?.name);if(c)return c}if(e==="channel_create"){const a=Kn(t.name);if(a)return a}const o=Kp(e);if(o!=="person"&&o!=="dm")return null;const s=fn(t.to);return Kn(s?.name)}function xw(e,t,n){const r=Kp(e);return r==="none"||r==="message"||r==="directory"?{kind:r,label:null}:{kind:r,label:Vp(e,t,n)}}function Iw(e){if(Array.isArray(e))return e.length;const t=fn(e);if(!t)return null;for(const n of["conversations","items","data"])if(Array.isArray(t[n]))return t[n].length;return null}function Tw(e,t){if(!t)return null;const n=zp(t.content),r=fn(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=fn(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"?Iw(n):null}function Cw(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=Po(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 ui(e,t){const n=e??{},r=Po(n.op)??"",o=fn(t),s=fw.has(r),a=uw.has(r)||r==="take_up"?Gi(n.body)??Gi(n.text)??Gi(o?.text):null;return{op:r,action:Rw(r,n,o),target:s?xw(r,n,o):{kind:"none",label:null},preview:a,count:s&&o?.ok===!0?Tw(r,o):null,emoji:r==="react"?Po(n.emoji):null,...s?Cw(r,o):{outcome:null,code:null}}}function Zp(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&bw.test(n.trim()))return n.trim();return null}const Ow=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"]),Yp=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return Ow.has(t)?t:"unknown"},Pw={channel_post:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function $a(e){return Pw[Yp(e)]()}function Qp(e,t=null){const{kind:n}=e.target,r=e.target.label??Kn(t);return r?n==="channel"&&!r.startsWith("#")?`#${r}`:r:e.op==="shared_history"?"":n==="channel"?_("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?_("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?_("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?_("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function Da(e,t,n,r){const o=Zp(t,r),s=!e.target.label&&o&&n?n(o):null,a=Qp(e,s),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?a:_("ui.chat.canonical.tool_row.bridge.summary.messages",{target:a,count:e.count}).trim();switch(Yp(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?_("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?"":_("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":_("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 Mw(e){return e.outcome==="refused"?e.code?_("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):_("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?_("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):_("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const jw=["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 Xp(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const r=fn(t);if(!r)return n??null;const{_images:o,...s}=r;return n&&Dw(n,s)?n:s}function $w(e){const t=fn(e);if(!t)return null;const n=t.destination_type==="conversation_dm"?"dm":t.state==="created"?"channel_create":"channel_post";return Vp(n,{},t)}function Jp(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:fn(t)?$w(t):n??null}function Dw(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 Nw={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"},Lw=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function Qd(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function mP(e,t){const n=e.args??{},r=e.details??null,o=ui(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=Zp(n,r),c=!s.target.label&&a&&t?t(a):null,l=Qp(s,c),d=s.outcome==="refused"||s.outcome==="failed",u=e.failed||d?$a(s.action).failed:null,f=u??$a(s.action).settled,h=Da({...s,preview:null,emoji:null},n,t,r),m=s.target.label??Kn(c)??_("ui.chat.canonical.tool_row.bridge.fallback.teammate"),y=s.op==="dm"?_("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:m}):h?_("ui.chat.canonical.tool_row.bridge.detail.headline.target",{verb:f,target:h}):f,b=[n.body,n.text,r?.text].find(S=>typeof S=="string"&&S.trim()!==""),v=typeof r?.seq=="number"?r.seq:null,p=Qd(r?.error),E=(s.target.kind==="channel"||s.target.kind==="dm")&&l?l:_("ui.chat.canonical.tool_row.bridge.fallback.conversation"),k=p?p.replace(Lw,(S,I)=>I.toLowerCase()==="bcv"?E:"…"):null,C=s.outcome==="refused"||s.outcome==="failed"?k&&s.code?_(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&&v!==null?_("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:v}):null,N=[],O=new Set,R=(S,I)=>{const F=Qd(I);F===null||O.has(S)||(O.add(S),N.push({key:S,value:F}))};for(const S of jw)R(S,r?.[S]);p&&p!==k&&R("error",p);for(const[S,I]of Object.entries(Nw))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:Da(s,n,t,r),failedVerb:u,failureWord:Mw(s),headline:y,body:b??null,outcome:C,internals:N,raw:w}}const qp="profile_save",Fw="profile_revert",Hc=["agent","team"],Uw=["create","update","revert"],Bw={agent:["label","description","tags","categories","model","instructions"],team:["label","description","manager","members","aliases","instructions","project"]},Na=i.string().max(1e5),Sn=e=>i.string().max(e),Rn=i.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/),Mo=i.string().regex(/^sha256:[0-9a-f]{64}$/),Xd=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:Rn,name:i.string().min(1).max(128),label:Sn(256),description:Sn(16e3),tags:i.array(Sn(512)).max(128),categories:i.array(Sn(128)).max(32),model:Sn(512).nullable(),instructions:Na}).strict();i.object({id:Rn,name:i.string().min(1).max(128),label:Sn(256),description:Sn(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(Sn(128)).max(32),instructions:Na,project:Na}).strict();const eh=i.object({version:i.literal(1),operation:i.literal(qp),approval_id:i.string().min(1).max(64),profile_kind:i.enum(Hc),scope:i.literal("global"),profile_operation:i.enum(Uw),target_id:Rn,profile_name:i.string().min(1).max(128),session_id:Rn,tool_call_id:Rn,receipt_id:Rn,changed_fields:i.array(i.string().max(64)).max(32),before:i.record(i.string(),Xd).nullable(),after:i.record(i.string(),Xd),base_commitment:Mo,after_commitment:Mo,expires_at:i.number().finite(),signing_principal:i.string().min(1).max(160)}).strict(),Hw=i.object({action:i.string().min(1).max(64),operation:i.literal(qp),request_digest:Mo,assurance:i.string().max(64).optional(),unproven_human:i.boolean().optional(),disclosure:eh.nullable().optional(),disclosure_digest:Mo.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(),Ww=["queued","applied"],Gw=i.object({status:i.enum(Ww),approval_id:i.string().min(1).max(64).optional(),request_digest:Mo.optional(),expires_at:i.number().finite().optional(),receipt_id:Rn.optional(),profile_kind:i.enum(Hc),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(),zw=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 Kw(e){const t=zw.safeParse(e);return t.success?t.data:null}const th=i.object({schema:i.literal(1),kind:i.literal(Fw),action_id:i.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),label:i.string().min(1).max(64),profile_kind:i.enum(Hc),profile_name:i.string().min(1).max(128),receipt_id:Rn}).strict();function Vw(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 Zw(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:typeof t=="object"&&t!==null?Vw(t):"").filter(t=>t!=="").join(", "):""}function Jd(e,t){return e===null?{presence:"absent",text:""}:Object.prototype.hasOwnProperty.call(e,t)?e[t]===null?{presence:"unset",text:""}:{presence:"set",text:Zw(e[t])}:{presence:"absent",text:""}}function gP(e){const t=Bw[e.profile_kind],n=[];for(const r of e.changed_fields){if(!t.includes(r))continue;const o=Jd(e.before,r),s=Jd(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 _P(e){const t=th.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 Yw(e){const t=eh.safeParse(e);return t.success?t.data:null}function bP(e){const t=Hw.safeParse(e);return t.success?t.data:null}function Rr(e){const t=Gw.safeParse(e);return t.success?t.data:null}function Qw(e){const t=th.safeParse(e);return t.success?t.data:null}const Xw=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),Jw=new Set(["true","yes","y","t","on","1"]),qw={hub:{steps:e=>{const t=xr(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=xr(e);return t!==null&&t>0?`· ${ih(t/1e3)}`:""}}};function xr(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 qd="mcp__",ek=/^\/(?:Users|home)\/[^/]+\//,tk=/\s+/;function nk(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(ek,"~/")}function St(e){return typeof e=="string"?nk(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function rk(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function ok(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(tk).filter(Boolean).join(" ")||"?"}function sk(e){return[rk(e),St(ok(e))||"?",St(e.message)].filter(Boolean).join(" · ")}const ik=new Set(["delivered","mailbox","unconfirmed","failed"]);function ak(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:r}=ui({op:n},t);return r==="inbox_only"?"inbox_only":r==="awaiting_acceptance"?"awaiting_acceptance":r==="unconfirmed"?"unconfirmed":null}function ck(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return ak(e);const n=e.delivery;if(!n||typeof n!="object")return null;const r=n.state;return typeof r=="string"&&ik.has(r)?r:null}function nh(e,t,n){return!e||typeof e!="object"?t??null:ck(e,n)}function lk(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 dk=["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 uk(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 fk=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function pk(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:fk.every(s=>s==="cost"?n.cost?.basis===o.cost?.basis:n[s]===o[s])})}function hk(e,t){for(const n of dk){const r=e[n],o=t[n];if(n==="artifacts"){if(!pk(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(!uk(r,o))return!1;continue}if(r!==o)return!1}return!0}function rh(e,t){const n=lk(e);return n?t&&hk(n,t)?t:n:t??null}const mk={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},gk={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."},_k={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."},bk={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function oh(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const zo=e=>e.trim().toLowerCase()==="bridge";function vP(e,t=""){return e?e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&zo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):mk[e]??null:null}function yP(e,t){return e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&zo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function wP(e,t=""){if(e)return e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&zo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):gk[e]}function kP(e,t=""){return e?e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&zo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):bk[e]??null:null}function SP(e,t=""){return e?e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&zo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):_k[e]??null:null}function EP(e){return oh(e)?"partial":null}function AP(e){return e==="failed"?"Attempted":null}function RP(e,t){return e!==!0?!1:!oh(t)}function eu(e){const t=xr(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:St(e.session)||St(e.target)||"?"}function vk(e){const t=St(e.query);if(t){const a=xr(e.steps);return a!==null&&Number.isInteger(a)&&a>=0?`search ${t} · ${a} around`:`search ${t}`}const n=xr(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=xr(e.head);if(r!==null&&Number.isInteger(r)&&r>=0)return`first ${r}`;if(e.digest===!0)return"digest";const o=St(e.before_id);if(o)return`before ${o}`;const s=St(e.around_id);return s?`around ${s}`:""}function yk(e){const t=Ek(e);if(t==="spawn"){const n=St(e.visibility)||"workstream",r=St(e.name)||St(e.prompt);return[n,r].filter(Boolean).join(" · ")}if(t==="stop"||t==="resume"||t==="info")return eu(e);if(t==="peek")return[eu(e),vk(e)].filter(Boolean).join(" · ");if(t==="list"){const n=[];e.include_stored===!0&&n.push("stored");const r=St(e.query);return r&&n.push(r),n.join(" · ")}return null}function xP(e,t,n,r){const o=e.trim();if(o.toLowerCase()==="bridge")return Da(ui(t,n),t,r,n);if(!t)return o;if(o==="send")return sk(t)||o;if(o.toLowerCase()==="sessions"){const c=yk(t);if(c!==null)return c||o}const s=Ak(o)?Object.entries(t).filter(([c])=>!ah.has(c)):Object.entries(t);let a=s.filter(([c])=>Xw.has(c)).map(([,c])=>St(c)).filter(Boolean);if(a.length===0){const c=qw[o.toLowerCase()];a=s.map(([l,d])=>c?.[l]?.(d)||St(d)).filter(Boolean)}return a.slice(0,2).join(" ")||o}function sh(e){const t=e.trim();if(!t.toLowerCase().startsWith(qd))return t;const n=t.slice(qd.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function wk(e,t){return e===t||e===sh(t)}const kk=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,Sk="… ";function IP(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 Ww(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 th(e){return xw.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function nh(e,t,n){const r=Zn(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?Zn(c.slice(0,l)):null;if(d)return d}}if(e==="channel_create"){const a=hn(eh(n?.content)),c=Zn(a?.name);if(c)return c}if(e==="channel_create"){const a=Zn(t.name);if(a)return a}const o=th(e);if(o!=="person"&&o!=="dm")return null;const s=hn(t.to);return Zn(s?.name)}function Gw(e,t,n){const r=th(e);return r==="none"||r==="message"||r==="directory"?{kind:r,label:null}:{kind:r,label:nh(e,t,n)}}function zw(e){if(Array.isArray(e))return e.length;const t=hn(e);if(!t)return null;for(const n of["conversations","items","data"])if(Array.isArray(t[n]))return t[n].length;return null}function Kw(e,t){if(!t)return null;const n=eh(t.content),r=hn(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=hn(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"?zw(n):null}function Vw(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=$o(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 hi(e,t){const n=e??{},r=$o(n.op)??"",o=hn(t),s=Tw.has(r),a=Iw.has(r)||r==="take_up"?Zi(n.body)??Zi(n.text)??Zi(o?.text):null;return{op:r,action:Ww(r,n,o),target:s?Gw(r,n,o):{kind:"none",label:null},preview:a,count:s&&o?.ok===!0?Kw(r,o):null,emoji:r==="react"?$o(n.emoji):null,...s?Vw(r,o):{outcome:null,code:null}}}function rh(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&$w.test(n.trim()))return n.trim();return null}const Zw=new Set(["channel_post","dm","send","reply","channels","channel_create","channel_history","channel_thread","react","react_remove","directory","shared_conversations","shared_history","take_up","ack_working","ack_done"]),oh=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return Zw.has(t)?t:"unknown"},Yw={channel_post:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function Ha(e){return Yw[oh(e)]()}function sh(e,t=null){const{kind:n}=e.target,r=e.target.label??Zn(t);return r?n==="channel"&&!r.startsWith("#")?`#${r}`:r:e.op==="shared_history"?"":n==="channel"?_("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?_("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?_("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?_("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function Wa(e,t,n,r){const o=rh(t,r),s=!e.target.label&&o&&n?n(o):null,a=sh(e,s),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?a:_("ui.chat.canonical.tool_row.bridge.summary.messages",{target:a,count:e.count}).trim();switch(oh(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?_("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?"":_("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":_("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 Jw(e){return e.outcome==="refused"?e.code?_("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):_("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?_("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):_("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const Xw=["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 ih(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const r=hn(t);if(!r)return n??null;const{_images:o,...s}=r;return n&&qw(n,s)?n:s}function Qw(e){const t=hn(e);if(!t)return null;const n=t.destination_type==="conversation_dm"?"dm":t.state==="created"?"channel_create":"channel_post";return nh(n,{},t)}function ah(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:hn(t)?Qw(t):n??null}function qw(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 ek={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"},tk=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function ou(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function jP(e,t){const n=e.args??{},r=e.details??null,o=hi(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=rh(n,r),c=!s.target.label&&a&&t?t(a):null,l=sh(s,c),d=s.outcome==="refused"||s.outcome==="failed",u=e.failed||d?Ha(s.action).failed:null,f=u??Ha(s.action).settled,h=Wa({...s,preview:null,emoji:null},n,t,r),m=s.target.label??Zn(c)??_("ui.chat.canonical.tool_row.bridge.fallback.teammate"),y=s.op==="dm"?_("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:m}):h?_("ui.chat.canonical.tool_row.bridge.detail.headline.target",{verb:f,target:h}):f,b=[n.body,n.text,r?.text].find(S=>typeof S=="string"&&S.trim()!==""),v=typeof r?.seq=="number"?r.seq:null,p=ou(r?.error),E=(s.target.kind==="channel"||s.target.kind==="dm")&&l?l:_("ui.chat.canonical.tool_row.bridge.fallback.conversation"),k=p?p.replace(tk,(S,I)=>I.toLowerCase()==="bcv"?E:"…"):null,C=s.outcome==="refused"||s.outcome==="failed"?k&&s.code?_(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&&v!==null?_("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:v}):null,N=[],O=new Set,R=(S,I)=>{const F=ou(I);F===null||O.has(S)||(O.add(S),N.push({key:S,value:F}))};for(const S of Xw)R(S,r?.[S]);p&&p!==k&&R("error",p);for(const[S,I]of Object.entries(ek))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:Wa(s,n,t,r),failedVerb:u,failureWord:Jw(s),headline:y,body:b??null,outcome:C,internals:N,raw:w}}const ch="profile_save",nk="profile_revert",Yc=["agent","team"],rk=["create","update","revert"],ok={agent:["label","description","tags","categories","model","instructions"],team:["label","description","manager","members","aliases","instructions","project"]},Ga=i.string().max(1e5),An=e=>i.string().max(e),In=i.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/),Do=i.string().regex(/^sha256:[0-9a-f]{64}$/),su=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:In,name:i.string().min(1).max(128),label:An(256),description:An(16e3),tags:i.array(An(512)).max(128),categories:i.array(An(128)).max(32),model:An(512).nullable(),instructions:Ga}).strict();i.object({id:In,name:i.string().min(1).max(128),label:An(256),description:An(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(An(128)).max(32),instructions:Ga,project:Ga}).strict();const lh=i.object({version:i.literal(1),operation:i.literal(ch),approval_id:i.string().min(1).max(64),profile_kind:i.enum(Yc),scope:i.literal("global"),profile_operation:i.enum(rk),target_id:In,profile_name:i.string().min(1).max(128),session_id:In,tool_call_id:In,receipt_id:In,changed_fields:i.array(i.string().max(64)).max(32),before:i.record(i.string(),su).nullable(),after:i.record(i.string(),su),base_commitment:Do,after_commitment:Do,expires_at:i.number().finite(),signing_principal:i.string().min(1).max(160)}).strict(),sk=i.object({action:i.string().min(1).max(64),operation:i.literal(ch),request_digest:Do,assurance:i.string().max(64).optional(),unproven_human:i.boolean().optional(),disclosure:lh.nullable().optional(),disclosure_digest:Do.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(),ik=["queued","applied"],ak=i.object({status:i.enum(ik),approval_id:i.string().min(1).max(64).optional(),request_digest:Do.optional(),expires_at:i.number().finite().optional(),receipt_id:In.optional(),profile_kind:i.enum(Yc),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(),ck=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 lk(e){const t=ck.safeParse(e);return t.success?t.data:null}const dh=i.object({schema:i.literal(1),kind:i.literal(nk),action_id:i.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),label:i.string().min(1).max(64),profile_kind:i.enum(Yc),profile_name:i.string().min(1).max(128),receipt_id:In}).strict();function dk(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 uk(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:typeof t=="object"&&t!==null?dk(t):"").filter(t=>t!=="").join(", "):""}function iu(e,t){return e===null?{presence:"absent",text:""}:Object.prototype.hasOwnProperty.call(e,t)?e[t]===null?{presence:"unset",text:""}:{presence:"set",text:uk(e[t])}:{presence:"absent",text:""}}function $P(e){const t=ok[e.profile_kind],n=[];for(const r of e.changed_fields){if(!t.includes(r))continue;const o=iu(e.before,r),s=iu(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 DP(e){const t=dh.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 fk(e){const t=lh.safeParse(e);return t.success?t.data:null}function NP(e){const t=sk.safeParse(e);return t.success?t.data:null}function Tr(e){const t=ak.safeParse(e);return t.success?t.data:null}function pk(e){const t=dh.safeParse(e);return t.success?t.data:null}const hk=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),mk=new Set(["true","yes","y","t","on","1"]),gk={hub:{steps:e=>{const t=Cr(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=Cr(e);return t!==null&&t>0?`· ${mh(t/1e3)}`:""}}};function Cr(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 au="mcp__",_k=/^\/(?:Users|home)\/[^/]+\//,bk=/\s+/;function vk(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(_k,"~/")}function St(e){return typeof e=="string"?vk(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function yk(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function wk(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(bk).filter(Boolean).join(" ")||"?"}function kk(e){return[yk(e),St(wk(e))||"?",St(e.message)].filter(Boolean).join(" · ")}const Sk=new Set(["delivered","mailbox","unconfirmed","failed"]);function Ek(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:r}=hi({op:n},t);return r==="inbox_only"?"inbox_only":r==="awaiting_acceptance"?"awaiting_acceptance":r==="unconfirmed"?"unconfirmed":null}function Ak(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return Ek(e);const n=e.delivery;if(!n||typeof n!="object")return null;const r=n.state;return typeof r=="string"&&Sk.has(r)?r:null}function uh(e,t,n){return!e||typeof e!="object"?t??null:Ak(e,n)}function Rk(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 xk=["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 Ik(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 Tk=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function Ck(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:Tk.every(s=>s==="cost"?n.cost?.basis===o.cost?.basis:n[s]===o[s])})}function Ok(e,t){for(const n of xk){const r=e[n],o=t[n];if(n==="artifacts"){if(!Ck(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(!Ik(r,o))return!1;continue}if(r!==o)return!1}return!0}function fh(e,t){const n=Rk(e);return n?t&&Ok(n,t)?t:n:t??null}const Pk={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},Mk={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."},jk={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."},$k={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function ph(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const Zo=e=>e.trim().toLowerCase()==="bridge";function LP(e,t=""){return e?e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&Zo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):Pk[e]??null:null}function FP(e,t){return e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&Zo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function UP(e,t=""){if(e)return e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&Zo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):Mk[e]}function BP(e,t=""){return e?e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&Zo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):$k[e]??null:null}function HP(e,t=""){return e?e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&Zo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):jk[e]??null:null}function WP(e){return ph(e)?"partial":null}function GP(e){return e==="failed"?"Attempted":null}function zP(e,t){return e!==!0?!1:!ph(t)}function cu(e){const t=Cr(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:St(e.session)||St(e.target)||"?"}function Dk(e){const t=St(e.query);if(t){const a=Cr(e.steps);return a!==null&&Number.isInteger(a)&&a>=0?`search ${t} · ${a} around`:`search ${t}`}const n=Cr(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=Cr(e.head);if(r!==null&&Number.isInteger(r)&&r>=0)return`first ${r}`;if(e.digest===!0)return"digest";const o=St(e.before_id);if(o)return`before ${o}`;const s=St(e.around_id);return s?`around ${s}`:""}function Nk(e){const t=Bk(e);if(t==="spawn"){const n=St(e.visibility)||"workstream",r=St(e.name)||St(e.prompt);return[n,r].filter(Boolean).join(" · ")}if(t==="stop"||t==="resume"||t==="info")return cu(e);if(t==="peek")return[cu(e),Dk(e)].filter(Boolean).join(" · ");if(t==="list"){const n=[];e.include_stored===!0&&n.push("stored");const r=St(e.query);return r&&n.push(r),n.join(" · ")}return null}function KP(e,t,n,r){const o=e.trim();if(o.toLowerCase()==="bridge")return Wa(hi(t,n),t,r,n);if(!t)return o;if(o==="send")return kk(t)||o;if(o.toLowerCase()==="sessions"){const c=Nk(t);if(c!==null)return c||o}const s=Hk(o)?Object.entries(t).filter(([c])=>!gh.has(c)):Object.entries(t);let a=s.filter(([c])=>hk.has(c)).map(([,c])=>St(c)).filter(Boolean);if(a.length===0){const c=gk[o.toLowerCase()];a=s.map(([l,d])=>c?.[l]?.(d)||St(d)).filter(Boolean)}return a.slice(0,2).join(" ")||o}function hh(e){const t=e.trim();if(!t.toLowerCase().startsWith(au))return t;const n=t.slice(au.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function Lk(e,t){return e===t||e===hh(t)}const Fk=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,Uk="… ";function VP(e,t=!1){if(!e||t)return null;for(const n of e.split(`
|
|
23
|
+
`)){const r=n.trim();if(r&&!Fk.test(r))return`${Uk}${r.slice(0,160)}`}return null}function mh(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 ZP(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`:mh(t)}function lu(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 YP(e){return e<1024?`${e} B`:e<1024*1024?`${lu(e/1024)} KB`:`${lu(e/(1024*1024))} MB`}function du(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const uu={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 JP(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(uu,t)?uu[t]:"plain"}function Bk(e){if(!e)return"";for(const t of gh){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"&&mk.has(o.toLowerCase());return r==="milestone"&&s?"milestone-remove":t==="op"&&(r==="react"||r==="ack")?hi(e).action:r}}return""}const gh=new Set(["op","action","method"]),Hk=e=>Object.prototype.hasOwnProperty.call(_h,e.trim().toLowerCase()),Wk={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"}},_h={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 Gk(e,t){const n=e.trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(n==="bridge"){const{settled:a,running:c}=Ha(r);return{settled:a,running:c,named:!0}}const o=r?_h[n]?.[r]:void 0;if(o)return{...o,named:!0};const s=Wk[n];return s?{...s,named:!0}:{settled:_("ui.chat.canonical.tool_row.generic_verb.settled"),running:_("ui.chat.canonical.tool_row.generic_verb.running"),named:!1}}function XP(e,t,n,r,o="",s=null){const a=Gk(e,o),c=Lk(t,e)?n??"":t;return{verb:r?a.running:s??a.settled,object:a.named?c:[hh(e),c].filter(Boolean).join(" ")}}const zk=new Set(["write","edit"]);function Kk(e){return zk.has(e.trim().toLowerCase())}function QP(e){return Kk(e.toolName)&&e.diff!==null&&!e.isError}function bh(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 Vk(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 vh(e,t){return e===null||Vk(e,t)?t:e}function yh(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:du(n.added),removed:du(n.removed)}}function Zk(e){return e.length>=2&&za(e[0])==="---"&&za(e[1])==="+++"?e.slice(2):e.slice()}const Yk=/\s+$/;function za(e){return e.replace(Yk,"")}function Jk(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const Xk=40;function qP(e){const t=Zk(e),n=t.slice(0,Xk);return{lines:n.map(r=>{const o=za(r);return{text:o,marker:o.slice(0,1),kind:Jk(o)}}),hidden:t.length-n.length}}function eM(e){return`… ${e} more diff line${e===1?"":"s"}`}const Qk=new Set(["agent","team"]),qk=1048576;function Jc(e,t){if(!Qk.has(e)||!t||typeof t!="object"||Array.isArray(t))return null;try{const n=JSON.stringify(t);if(new TextEncoder().encode(n).byteLength>qk)return null}catch{return null}return!lk(t)&&!Tr(t)&&!fk(t)?null:t}function wh(e,t,n){return Jc(e,t)??fh(t,n)}const eS=`Continue working toward this goal:
|
|
25
25
|
|
|
26
|
-
`,
|
|
26
|
+
`,tS=`
|
|
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.`,nS=`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.`,[Uk="",Bk=""]=Fk.split("{goal}"),Hk="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.",Wk="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.",Gk="Harness recovery notice: the last three tool batches repeated the same arguments and errors. Inspect the error and change approach; do not repeat the unchanged failing calls. If an external condition must change, use a supported wait operation or explain the blocker.";function ph(e){const t=e.trim();return t===Hk||t===Wk||t===Gk||t.startsWith(Nk)&&t.endsWith(Lk)||t.startsWith(Uk.trim())&&t.endsWith(Bk.trim())}const zk=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function Kk(e,t){const n=t?.match(zk)?.[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 mr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}const Vk=32,Zk=32*1024,Yk=256*1024;function Qk(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(y=>y.entry),...e]){if(m.type!=="prune"||!mr(m.payload))continue;const{target:y,replacement:b}=m.payload;if(typeof y!="string"||!Number.isFinite(m.ts)||!mr(b)||b.kind!=="message"||b.role!=="tool"||!Array.isArray(b.content)||!mr(b.provider_payload)||Object.keys(b).some(O=>!["kind","role","content","tool_call_id","tool_name","provider_payload"].includes(O))||b.content.length===0||b.content.some(O=>!mr(O)||typeof O.text!="string"||O.text.length>1e5||O.type!==void 0&&O.type!=="text"))continue;const v=b.tool_name;if(typeof v!="string"||typeof b.tool_call_id!="string"||b.tool_call_id.length===0)continue;const p=Wc(v,b.provider_payload.details),E=Rr(p),k=Qw(E?.profile_action);if(!E||E.status!=="applied"||E.profile_kind!==v||!k||k.receipt_id!==E.receipt_id||k.profile_kind!==E.profile_kind||k.profile_name!==E.profile_name)continue;const C=a.get(y),N=c.has(y)||!!(C&&JSON.stringify(C.entry.payload.replacement)!==JSON.stringify(b));a.set(y,{entry:C?.entry??m,...N||C?.conflict?{conflict:!0}:{}})}const l=[];let d=2;const u=m=>{if(new TextEncoder().encode(JSON.stringify(m.entry)).length>Zk)return;const y=new TextEncoder().encode(JSON.stringify(m)).length+(l.length?1:0);l.length<Vk&&d+y<=Yk&&(l.push(m),d+=y)};for(const m of a.values()){const{entry:y}=m,{target:b,replacement:v}=y.payload,p=v.tool_name,E=Rr(v.provider_payload.details);if(!E)continue;const k=r.get(b),C=k?void 0:t.find(F=>F.kind==="tool"&&F.sourceEntryId===b);if(m.conflict||!k&&(!C||C.kind!=="tool")){u(m);continue}const N=k?.payload,O=N&&mr(N.provider_payload)?N.provider_payload.details:C?.kind==="tool"?C.details:null,R=Rr(O),g=N?.tool_call_id??(C?.kind==="tool"?C.toolCallId:null),w=N?.tool_name??(C?.kind==="tool"?C.toolName:null),S=k?.ts??(C?C.ts/1e3:0);if(k&&(N?.role!=="tool"||k.type!=="message")||!R||w!==p||g!==v.tool_call_id||y.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:v}:{id:b,type:"message",ts:S,payload:v,...C?.journalSeq!==void 0?{journal_seq:C.journalSeq}:{}};k?o.set(b,I):s.set(y.id,I)}const f=e.map(m=>o.get(m.id)??s.get(m.id)??m);for(const[m,y]of s)e.some(b=>b.id===m)||f.push(y);const h=n.length===l.length&&l.every((m,y)=>m.entry===n[y].entry&&m.conflict===n[y].conflict);return{entries:f,pending:h?n:l}}function Xk(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||!mr(e.payload.provider_payload))return!1;const n=Rr(e.payload.provider_payload.details),r=Rr(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 hh(e){return e}const Fa="supplement_v1",Jk="superseded",Gs=120,Gc=480,qk=20,DP=500,eS=10,tS=["outside","sensitive","missing","too-large"];function mh(e,t){const n=[];let r=0;if(Array.isArray(e))for(const s of e.slice(0,eS)){if(!s||typeof s!="object")continue;const a=s,c=a.reason;if(!tS.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 zc(e){return`supplement:${e}`}function nS(e){const t=e.payload??{};if(String(t.custom_type??"")!==Fa)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?zc(r):null}function zs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function rS(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:zs(t.size_bytes)??0,mtime:zs(t.mtime)??0,why:typeof t.why=="string"?t.why:"",...t.pinned===!0?{pinned:!0}:{}}}function gh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=rS(n);r&&t.push(r)}return t}function oS(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!vh(n))return null;const r=zs(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?Gs:Math.min(Gc,Math.max(Gs,Math.round(r)))}}function _h(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=oS(n);r&&t.push(r)}return t}function sS(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return vh(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:zs(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 bh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=sS(n);r&&t.push(r)}return t}const iS=/^[a-f0-9]{32}$/,aS=/\s+/,cS=/\.0$/;function vh(e){return typeof e=="string"&&iS.test(e)}const lS={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function ou(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 NP(e,t){const n=e.state;if(e.error===Jk||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?lS[r]??r:r}const LP="Preparing highlights…",FP="Highlights cancelled",UP="Couldn't prepare highlights",BP="Adjust…",HP="Cancel",WP="Retry",dS=64,uS={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 GP(e){return typeof e=="string"&&e?uS[e]??"":""}function zi(e){return typeof e!="string"?"":e.replace(Up,"").split(aS).filter(Boolean).join(" ")}function zP(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function fS(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(cS,"")} ${n}`;return""}function KP(e){const t=zi(e.name)||zi(e.path),n=zi(e.path);return{name:t,path:n===t?"":n,size:fS(e.sizeBytes)}}function Ki(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function VP(e,t,n=e){return t?`Hide ${Ki(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${Ki(e,"graphic")}`:`Show ${Ki(e,"graphic")}`}function ZP(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const pS="supplement",hS=1,mS=["ready","resize","error","pong"],gS=["resize","error","pong"],_S=64,Kc=300,YP=5e3,QP=2e4;function XP(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==pS||n.v!==hS)return null;const r=n.t;if(typeof r!="string"||!mS.includes(r))return null;const o=r;if(gS.includes(o)&&(!t||t.length>_S||n.n!==t))return null;if(o==="error"){const s=n.msg;if(typeof s!="string"||s.length>Kc)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 JP(){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 bS=["--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"],vS=120;function yS(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 bS){const s=t.getPropertyValue(o).trim();s&&(n[o]=s.slice(0,vS))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function qP(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(yS()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function eM(e){return`data:text/html;base64,${wS(e)}`}function wS(e){const t=kS(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 kS(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 tM(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function SS(e){return Math.min(Gc,Math.max(Gs,e.heightHint))}function ES(e){return Math.min(Gc,Math.max(Gs,e))}function nM(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?ES(c):SS(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 AS=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,yh=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,RS=/kind=(auth|quota)\b/,xS=/kind=(transient|timeout)\b/;function wh(e){const t=a=>typeof a=="string"&&AS.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"&&(yh.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,s=typeof e.cause=="string"?e.cause.slice(0,dS):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...o?{detail:o}:{},...s?{cause:s}:{}}}function rM(e){if(!yh.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 oM(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return RS.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":xS.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 IS(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return kh(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:gh(e.files),..."withheld"in e||"withheld_more"in e?mh(e.withheld,e.withheld_more):{}}:{},...n==="done"?{components:_h(e.components),sounds:bh(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Kc)}:{},...wh(e),live:!Sh(n)}:null}function TS(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!kh(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,qk):[];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:gh(e.files),filesMore:r,more:o,components:_h(e.components),sounds:bh(e.sounds),...mh(e.withheld,e.withheld_more),...wh(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Kc)}:{}}}function su(e,t,n){const r=TS(t);if(!r)return null;const o=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return Eh(o,r,e)}function kh(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Sh(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function CS(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 OS(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 PS(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 MS(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 Eh(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&ou(t.state)<ou(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),y=t.live!==void 0?t.live===!0?!0:Sh(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:zc(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:CS(o,e?.files??[])?e?.files??[]:o,filesMore:d,more:jS(u,e?.more??[])?e?.more??[]:u,components:OS(s,e?.components??[])?e?.components??[]:s,sounds:PS(a,e?.sounds??[])?e?.sounds??[]:a,withheld:MS(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:y}}function jS(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const sM=e=>e.kind===void 0||e.kind==="image",Lt={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function Ah(e){return e==="skipped"||e==="aborted"}function iu(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function au(e,t,n,r){return iu(n.args)??(r?.kind==="tool"?r.args:null)??iu(e.argsByCall.get(t)?.arguments)}function Rh(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function xh(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 ls(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Zt(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!Rh(n)&&xh(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Zn(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:uo;const o=[];for(const s of r){const a=xh(s);if(s.type==="document"||a===null&&!Rh(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=ls(s.width),c.height=ls(s.height),c.sizeBytes=ls(s.size_bytes),c.durationS=ls(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?uo:n&&Vc(n,o)?n:o}const uo=[],Ua=[];function Ih(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Ua;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:Ua:n&&$S(n,o)?n:o}function $S(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 cu(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 Th(e,t,n){if(t.length===0)return e;if(e.length===0||Vc(e,t))return t;const r=cu(e),o=cu(t);return r!==o?r>o?e:t:n==="incoming"?e:t}function DS(e,t){return Th(e,t,"incoming")}function Vc(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 At(e){const t=new Map;return e.forEach((n,r)=>t.set(n.id,r)),t}function NS(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const pn=new Set;function Zc(e){return e.kind==="user"&&e.provisional===!0}function Ch(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{Zc(n)&&r<t&&(t=r)}),t}function jo(e,t=pn,n){if(n?.journalMode)return xp(n,e).map(hh);const r=e.map((a,c)=>({record:a,position:c})),o=Ch(e),s=a=>Zc(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 LS(e,t,n){if(!n||t<=0)return pn;let r=null;for(const o of e){if(!Zc(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&&Jc(c)&&(a=!0),s&&a)break;s&&a&&(r??=new Set,r.add(o.id))}return r??pn}function FS(e){const{provisional:t,...n}=e;return n}function Ba(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)&&Vc(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&&US(a,c))continue}return!1}return!0}function US(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(Ba(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=jo(a,pn,e);return{...e,records:c,index:At(c)}}const r=e.journalMode?jo([...e.records,t],pn,e):[...e.records,t],o=At(r);return{...e,records:r,index:o}}function Yc(e,t){if(!e.records.some(t))return e;const n=e.records.filter(r=>!t(r));return{...e,records:n,index:At(n)}}function Vi(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")?Yc(e,s=>s.id===n):e}function BS(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:At(s)}}const HS=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function Oh(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 WS(e,t){const n=bu(e),r=bu(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const Ph="Context compacted",GS=12e4;function Mh(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>GS||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 zS(e){const t=Mh(e.records);return t===e.records?e:{...e,records:t,index:At(t)}}const KS="peer_message",VS="ask_response",ZS="ask_timeout",jh="Completed — runtime retired/disposed",$h="Retired for an update — a turn was in flight and was cut; its earlier output is kept",YS="wake_prompt",QS="session_mcp_unavailable",XS=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),JS=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,lu=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,qS=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."]),Dh=/^\[[^\]]{1,32}\]\s*/,Ks="Reason:",eE=/[\n;,(]| [—–] /,tE=/^\d+\.$/,nE=/[A-Z]/,rE=/\s/,fo=160;function Ss(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",...cE(t,n)};let r;return e===QS?r=oE(t):XS.has(e)?r=iE(t.trim().replace(Dh,"")):r=lE(t),{level:"info",category:null,provider:null,...r}}function oE(e){const t=e.trim().replace(Dh,"").split(`
|
|
33
|
-
`).map(c=>c.trim()),n=t[0]??"",r=t[1]?.startsWith(
|
|
34
|
-
`),s=(r?`${n} ${r}`:n).trim();if(s.length<=
|
|
35
|
-
`)||null,d=`${n} ${c(a.leading,a.clause)}`;if(d.length<=
|
|
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=>!lu.test(c)&&!uE(c),r=t.find(n),o=t.find(c=>lu.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 Lh(s)}function uE(e){return qS.has(e.replace(/\s+/g," ").trim().toLowerCase())}function Lh(e){const t=e.trim();if(t.length<=fo)return t;const n=t.slice(0,fo),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const fE="harness_injected",Fh=e=>!e||typeof e!="object"?!1:e[fE]===!0;function Uh(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function Bh(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const pE="ask";function du(e,t){return t===!0&&String(e??"")===pE}function hE(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function Hh(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:Ph,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=Oh(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:jh,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:$h,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===Fa){const a=n.details??{};return su(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(HS.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=ja(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&Wi(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...Ss(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(h=>f[h]===u[h])?f:u,images:Zn(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===KS){const{body:u,sender:f}=Wp(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&Wi(t.sender,f)?t.sender:f}}if(a===YS){if(aw(c)||cw(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===VS){const u=c.answers,f={};if(u&&typeof u=="object")for(const[y,b]of Object.entries(u))f[String(y)]=Array.isArray(b)?b.map(v=>String(v)):[];const h=c.questions,m=Array.isArray(h)?h.flatMap(y=>{if(!y||typeof y!="object")return[];const b=y;return[{id:String(b.id??""),question:String(b.question??""),secret:b.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:r,askId:String(c.ask_id??""),status:String(c.status??"answered"),by:c.by&&typeof c.by=="object"?c.by:null,reason:typeof c.reason=="string"?c.reason:null,questions:m,answers:f,secretLost:c.secret_lost===!0}}if(a===ZS){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===Fa)return su(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?Kk(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:lw(c)}:{},attribution:n.attribution??"system",...Ss(a,d,c)}:null}const s=String(n.role??"");if(s==="user"){const a=Nh(n.provider_payload);if(a){const u=ja({...a,text:Zt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&Wi(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",...Ss("hub_message",u.envelope||u.body,{...a,text:Zt(n)}),receipt:f&&Object.keys(u).every(m=>f[m]===u[m])?f:u,images:Zn(n,e.id,h)}}}if(Fh(n.provider_payload))return null;const c=Zt(n);if(ph(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=di(c),d=Ih(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Zn(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=Zt(n);return!c&&a.length>0?{kind:"assistant",id:e.id,ts:r,text:"",streaming:!1,stopReason:String(n.stop_reason??"toolUse"),callsTools:!0,error:!1}:{kind:"assistant",id:e.id,ts:r,text:c,complete:!0,streaming:!1,callsTools:a.length>0,stopReason:n.stop_reason??null,error:!!n.is_error}}if(s==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(Bh(l))return null;const d=Ah(l.__fault);return{kind:"tool",id:`tool:${a}`,ts:r,toolCallId:a,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:Zt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Zn(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...uh(c.details,t?.kind==="tool"?t:null),diff:dh(lh(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:nh(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:Xp(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:Jp(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:fh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.details??null:null)}}return null}function mE(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 gE=/^(?:tool|compaction|local):/;function _E(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)&&!gE.test(t.id))return t.id}return null}function bE(e,t){const n=nS(t);if(n)return e.records[e.index.get(n)??-1]}function Qc(e){const t=xp(e,e.records);if(t===e.records)return e;const n=t.map(hh);return{...e,records:n,index:At(n)}}const $o=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Wh(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 vE(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&&$o(r.journalSeq)&&n.add(o))}return{carried:t,admitted:n}}function Xc(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function uu(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=Xc(a);return l!==a&&(r=!0),l});let s=r?{...e,records:o}:e;return s=Gh(s,n),s}function Gh(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=vE(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 Vs(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 Ko(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function zh(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function yE(e,t,n){let r=Mr(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=Mc(r,{...s.payload,id:s.id});const o=Ko(r,!1);return Qc(o.journalPeerSource===void 0&&!o.journalBodyOwed&&!o.journalSourceVoid&&o.journalSourceUnavailable===void 0?o:{...o,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function fu(e,t,n){let r=Mr(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=Ko(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=Gh(r,s));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=Vs(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=zh(r,t),Qc(r)}function wE(e,t,n,r){let o=Mr(e,t,[],!1,n,{peer:!0});o=Ko(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 y of l){if(typeof y.id!="string"||y.id===""||a(y.id))continue;const b=`tool:${String(y.payload?.tool_call_id??"")}`,v=f.get(y.id)??f.get(b),p=v===void 0?void 0:u[v];if(!p)continue;let E=Hh(y,p);E&&(E={...E,sourceEntryId:y.id,...p.sourcePrecedes?{sourcePrecedes:p.sourcePrecedes}:{}},$o(y.journal_seq)?(E=Wh(E,y.id,t.journal_generation,y.journal_seq),d.push(y.id)):E=Xc(E),m.set(p.id,E))}m.size>0&&(u=u.map(y=>m.get(y.id)??y),f=At(u))}let h=u===o.records?o:{...o,records:u,index:f};if(c){h=Vs(h,d,!1);const m=(t.source_missing_ids??[]).filter(y=>typeof y=="string"&&y.length>0&&y.length<=128&&!a(y));if(m.length>0){h=Vs(h,m,!1);const y=new Set(h.journalSourceVoid??[]);for(const b of m)y.add(b);h={...h,journalSourceVoid:y}}}return h=zh(h,t),Qc(h)}function ds(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function po(e,t,n={}){let r=e;const o=r,s=[];let a=e.profileHistoryPending;const c=T=>Ko(Vs(T.profileHistoryPending===a?T:{...T,profileHistoryPending:a},s,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Mr(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=Mc(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=Qk(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&&!FE(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]??bE(r,T);let Z=Hh(T,V);if(Xk(T,V)&&V&&(Z=V),Z&&(r.journalMode||Z.kind==="tool"&&Wc(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&&$o(T.journal_seq)?(Z=Wh(Z,T.id,t.journal_generation,T.journal_seq),s.push(T.id)):Z&&n.peerSource===!0&&(Z=Xc(Z)),!(Z&&V&&hE(V,n.readWitness))&&Z&&h.push(Z)}let m=r.argsByCall,y=!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)||(y||(m=new Map(m),y=!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 b=y?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,v=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)&&!v.has(T.id)):[],E=n.replace?p.length>0?{...Lt,records:p,index:At(p)}:Lt:{...r,records:b},k=new Map(E.records.map(T=>[T.id,T]));let C=r!==o||n.replace||!n.replace&&b!==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:Th(T.images,V.images,"current")};Ba(V,Z)||(C=!0,k.set(T.id,Z));continue}Ba(V,T)||(C=!0,k.set(T.id,T))}const N=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?pn:LS(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&&!N&&g.size===0)return c(r);const $=g.size===0?[...k.values()]:[...k.values()].map(T=>g.has(T.id)?FS(T):T),ne=Mh(jo($,n.statedByOwner===!1?pn:new Set(h.map(T=>T.id)),r));return n.keepPaging?c({...r,records:ne,index:At(ne),argsByCall:m}):c({...r,records:ne,index:At(ne),oldestId:w,oldestTs:S,hasMore:I,argsByCall:m,compacting:N?!1:r.compacting,compactingSince:N?0:r.compactingSince})}const kE=/^(?:local|notice|retry|subagent|compaction):/;function Jc(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!kE.test(e.id)}}function SE(e,t,n=pn){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(o=>!(o.ts<t.ts&&Jc(o)&&!n.has(o.id)));return r.length===e.records.length?e:{...e,records:r,index:At(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const nn={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function Zi(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function Ha(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=Mr(o,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=jo(d.records,pn,d);return d===o&&u===o.records?o:{...d,records:u,index:At(u)}}s&&(o=Mc(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=Zi(s);if(s===void 0||l===null)return nn.idlessFrameRefused+=1,o;const d=o.records[o.index.get(l)??-1];if(s.role==="user"){const u=Nh(s.provider_payload);if(u){const b=Zt(s),v=ja({...u,text:b});if(v.body.trim()){const p=d?.kind==="user"&&d.provisional===!0;return $e(o,{kind:"custom",id:l,ts:p?Zs(o,n):n,customType:"hub_message",text:v.envelope,attribution:"user",...Ss("hub_message",v.envelope||v.body,{...u}),receipt:v,images:Zn(s,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(Fh(s.provider_payload))return o;const f=Zt(s);if(ph(f))return o;const h=d?.kind==="user"&&d.provisional===!0,m=Ih(s,l,d?.kind==="user"?d.documents:void 0),y=di(f);return $e(o,{kind:"user",id:l,ts:h?Zs(o,n):n,text:f,images:Zn(s,l,d?.kind==="user"?d.images:void 0),...m.length?{documents:m}:{},...h?{provisional:!0}:{},...y?{skill:y}:{}})}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=Zi(s);if(s===void 0||l===null)return nn.idlessFrameRefused+=1,o;const d=o.index.get(l),u=String(t.delta??""),f=Zt(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 nn.settledAssistantUpdate+=1,o;if(r.seed!==!0&&a&&h.frame&&a.epoch===h.frame.epoch&&a.seq<=h.frame.seq)return nn.staleUpdateFrameDropped+=1,o;const m=NS(h.frame,a);if(r.seed===!0&&!f)return!h.text&&!u?o:(nn.seededDeltaWithheld+=h.text?1:0,$e(o,{...h,text:h.text||u,...m?{frame:m}:{},truncated:h.text?"interrupted":"prefix"}));let y;if(f){if(y=f+u,y.length<=h.text.length)return o}else{if(!u)return o;y=h.text+u}return $e(o,{...h,text:y,...m?{frame:m}:{},truncated:f?void 0:h.truncated})}case"message_end":{const l=Zi(s);if(s===void 0)return nn.idlessFrameRefused+=1,o;if(l===null){if(s.role!=="assistant")return nn.idlessFrameRefused+=1,o;let y;for(const p of o.records)if(!(p.kind!=="assistant"||!p.streaming)){if(y!==void 0)return nn.idlessFrameRefused+=1,o;y=p}if(y===void 0)return nn.idlessFrameRefused+=1,o;const b=Array.isArray(s.tool_calls)?s.tool_calls:[],v={...y,streaming:!1,settledAt:y.settledAt??n,callsTools:b.length>0,...y.text||b.length===0?{complete:!0}:{}};return $e(o,v)}if(s.role!=="assistant")return o;const d=o.index.get(l),u=Zt(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,y=o.journalPeerSource===!0||m,b=y&&u!==void 0&&u===o.journalGeneration,v=d.map(k=>String(k.id??"")).filter(k=>k.length>0&&k.length<=128),p={entries:d.map(k=>{const C=String(k.id??""),N=f?.[C],O=h?.[C];return{id:C,ts:b&&typeof O=="number"&&Number.isFinite(O)?O:n/1e3,type:"message",payload:{kind:k.custom_type?"custom":"message",...k},...b&&$o(N)?{journal_seq:N}:{}}}),has_more:o.hasMore,...b?{journal_generation:u}:{}};let E=po(o,p,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:y});if(y&&v.length>0)if(b){const k=v.filter(C=>!$o(f?.[C]));k.length>0&&(E=uu(E,k))}else E=uu(E,v),u!==void 0&&(E=Mr(E,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),E=Ko(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"?Vi(o,d):o;const b=String(t.not_run_reason??"").trim()||null,v=String(t.not_run_kind??"").trim()||null;if(du(t.tool_name,c)&&!b&&!m)return d?Vi(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:b?"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:uo,added:0,removed:0,diff:null,stopped:!1,notRunReason:b,notRunKind:b?v:null,neverSent:b!==null};return d&&h?.kind==="tool"&&f?.kind!=="tool"?BS(o,d,E):$e(d&&f?.kind==="tool"?Vi(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=au(o,l,t,u),h=f&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:f,anchoredAt:Ir(t)??n}):o.argsByCall,m=h===o.argsByCall?o:{...o,argsByCall:h};return du(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:Ir(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:uo,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=rh(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(Bh(f.details))return Zh(o,d);const h=au(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:uo,added:0,removed:0,diff:null,stopped:!1},y=h&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:h,anchoredAt:Ir(t)??n}):o.argsByCall,b=y===o.argsByCall?o:{...o,argsByCall:y},v=r.userStoppedAt??null,p=!!(t.is_error??f.is_error),E=Ah(f.details?.__fault),k=v!==null&&(typeof m.startedAt=="number"?m.startedAt<=v:p);return $e(b,{...m,args:h,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:Zt(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:DS(Zn(f,d,m.images),m.images),...uh(f.details,m),diff:dh(lh(f.details),m.diff),stopped:m.stopped||k||E,delivery:nh(f.details,m.delivery,m.toolName),bridge:Xp(m.toolName,f.details,m.bridge),bridgeLabel:Jp(m.toolName,f.details,m.bridgeLabel),details:fh(m.toolName,f.details,m.details)})}case"supplement_progress":{const l=IS(t);if(!l)return o;const d=zc(l.anchor),u=o.records[o.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,h=Eh(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:Oh(String(t.detail??"")),h=f?f.text:l&&d?WS(l,d):Ph,m=`compaction:${o.generation}:${l}:${d}`,y=o.compacting?{...o,compacting:!1,compactingSince:0}:o;return y.index.has(m)?y:f?$e(y,{kind:"notice",id:m,ts:n,text:h,level:f.level}):zS($e(y,{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 Ir(e){return yy(e.started_at_epoch)}function qc(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function EE(e){const t=qc(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function AE(e,t){const n=Ir(e);if(n!==null)return n;const r=qc(e);if(!r)return null;const o=t.argsByCall.get(r)?.anchoredAt;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}function RE(e,t){if(Ir(e)!==null)return!1;const n=qc(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<=Ch(t.records)}function el(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 fi(e){return e.type==="tool_execution_end"}function xE(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=Uh(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let h=n;const m=EE(f);if(m!==null&&!o.index.has(m)){const y=AE(f,o);if(y!==null)h=y,c=!0,RE(f,o)&&l.add(m);else if(fi(f)||el(f)||!s)continue}o=Ha(o,f,h,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return o;const d=jo(o.records,l,o);return{...o,records:d,index:At(d)}}function pu(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!fi(r)&&!el(r))continue;const o=String(r.tool_call_id??"");if(!o)continue;const s=Ir(r);s!==null&&t.set(o,s)}return t}function IE(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 TE=5e3;function CE(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 OE(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-TE}function hu(e,t){const n=[];for(const r of e??[]){if(!r)continue;const o=r;if(!fi(o)&&!el(o))continue;const s=String(o.tool_call_id??"");!s||n.includes(s)||t.has(s)||n.push(s)}return n}function mu(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 PE=3.25,Wa=100,tl=500;function gu(e){return e<=0?Wa:Math.min(tl,Wa+Math.ceil(PE*e))}function Yi(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 ME(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function jE(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 $E(e,t){return e&&t===0}function DE(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"&&!fi(r)&&!s)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function Kh(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 NE(e,t,n){return Kh(e,t,n).length}function _u(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 LE(e,t=Date.now()){return e.records.length===0&&!e.profileHistoryPending?.length?e:{...Lt,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function FE(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 bu(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function UE(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return Yc(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function Zs(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function Vh(e,t,n,r,o=Date.now(),s=Ua){if(e.index.has(t))return e;const a=di(n);return $e(e,{kind:"user",id:t,ts:Zs(e,o),text:n,images:r,...s.length?{documents:s}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function Zh(e,t){return Yc(e,n=>n.id===t)}let vu=0;function BE(e,t,n,r=Date.now()){return vu+=1,$e(e,{kind:"notice",id:`local:${r}:${vu}`,ts:Zs(e,r),text:t,level:n})}function iM(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"?jh:s==="retired"?$h:s==="error"?"Stopped with an error":"Interrupted",level:s==="closed"?"info":s==="retired"?"warning":s==="error"?"error":"warning"}))}const HE="compacting context…";function aM(e){return typeof e=="string"&&e.trim()===HE}const WE=[1500,5e3];async function cM(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of WE){await t(n);try{if(await e())return}catch{}}}function GE(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 zE=["routed","snapshot","content","painted","sendable"],KE=6e4,VE="[open-trace]",ZE=/^[A-Za-z0-9_-]{1,80}$/,YE=["sidebar","open","native"];function QE(e,t,n){const r=ZE.test(e.sessionId)?e.sessionId:"?",o=YE.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=[VE,`t=${e.token}`,`session=${r}`,`via=${o}`,`outcome=${t}`,...zE.map(u=>`${u}=${s(e.stages[u])}`),`settled=${s(l)}`];return n!==void 0&&d.push(`by=t${n}`),d.join(" ")}function XE(e){let t=0,n=null;const r=(s,a)=>{const c=n;if(c){n=null,e.clearTimer(c.timer),e.log(QE(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")},KE),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 JE=typeof window<"u";function qE(e,t,n){t(()=>n(e))}const eA=e=>{const t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)},yu=XE({now:()=>performance.now(),nextFrame:e=>{JE&&typeof requestAnimationFrame=="function"&&typeof MessageChannel=="function"?qE(e,t=>requestAnimationFrame(()=>t()),eA):setTimeout(e,0)},log:e=>console.warn(e),setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e)});function lM(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 wu=new Set(["openrouter","radient","radient-key"]),tA=new Set(["auto","openrouter/auto"]),nA=()=>_("ui.chat.session_readout.model.router_auto");function Yh(e){return e.slice(e.lastIndexOf("/")+1)||e}function rA(e,t){return e===t||e===Yh(t)}function Ga(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 oA(e,t){return t?Ga(e?.selected_model)===t||Ga(e?.effective_model)===t:!1}function dM(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=wu.has(t)||!r||rA(r,e.model_id)||r.toLowerCase()==="unknown";return{name:wu.has(t)&&tA.has(e.model_id)?nA():o?Yh(n):r,selector:n}}function uM(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function fM(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function pM(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function hM(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 mM(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 gM(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function sA(e){const t=e.trim();return t&&(Qh(t)??t)}const ku=new Map;function Qh(e){const t=mn();let n=ku.get(t);return n===void 0&&(n={auto:_("ui.chat.session_readout.effort.level.auto"),none:_("ui.chat.session_readout.effort.level.none"),minimal:_("ui.chat.session_readout.effort.level.minimal"),low:_("ui.chat.session_status.effort_level.low"),medium:_("ui.chat.session_status.effort_level.medium"),high:_("ui.chat.session_status.effort_level.high"),xhigh:_("ui.chat.session_readout.effort.level.xhigh"),max:_("ui.chat.session_readout.effort.level.max"),unknown:_("ui.chat.session_readout.effort.level.unknown"),reasoning:_("ui.chat.session_readout.effort.level.reasoning")},ku.set(t,n)),n[e.toLowerCase()]}const so=e=>sA(e).toLowerCase(),us=e=>{const t=Qh(e.trim());return t===void 0?e:t.toLowerCase()};function Xh(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 _M(e,t){const n=(e??t)?.effective_model;return Xh(n)?null:n?.model_id??null}function bM(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=Xh(e);return t?{label:t,adjustable:n===null||n.length>0,knownLadder:!!(n&&n.length>0),levelKnown:!0,detail:n&&n.length>0?_("ui.chat.session_readout.effort.detail.offers",{levels:ws(n.map(so))}):_("ui.chat.session_readout.effort.detail.session")}:n&&n.length>0?{label:"auto",adjustable:!0,knownLadder:!0,levelKnown:!0,detail:r?_("ui.chat.session_readout.effort.detail.auto_with_default",{default:so(r),levels:ws(n.map(so))}):_("ui.chat.session_readout.effort.detail.auto",{levels:ws(n.map(so))})}:o?{label:"unknown",adjustable:!0,knownLadder:!1,levelKnown:!1,detail:_("ui.chat.session_readout.effort.detail.not_reported",{command:"/effort <level>"})}:n&&e.reasoning?{label:"reasoning",adjustable:!1,knownLadder:!0,levelKnown:!0,detail:_("ui.chat.session_readout.effort.detail.no_levels")}:n===null&&r?{label:r,adjustable:!1,knownLadder:!1,levelKnown:!0,detail:_("ui.chat.session_readout.effort.detail.default_only")}:null}function vM(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:_("ui.chat.session_readout.effort.detail.offers",{levels:ws(n.map(so))})}}function iA(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=Yr(n.provider);if(!a)return null;const c=Yr(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:Yr(n.label)||a,effectiveState:d,owner:Yr(n.owner_label)||Yr(n.owner_device)||_("ui.chat.session_readout.access.owner_fallback"),observedAt:Qi(n.observed_at),lastGrantAt:Qi(n.last_grant_at),lastGrantExpiresAt:Qi(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 yM(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function wM(e){return e&&e.draft!==!0?iA(e.frontend,e.servingLocality):null}function Yr(e){return typeof e=="string"?e.trim():""}function Qi(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function Xi(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function kM(e){const{label:t,effectiveState:n}=e,r=e.owner||_("ui.chat.session_readout.access.owner_fallback"),o={local:[_("ui.chat.session_readout.access.local.title",{label:t}),_("ui.chat.session_readout.access.local.description")],pending:[_("ui.chat.session_readout.access.pending.title",{label:t}),_("ui.chat.session_readout.access.pending.description")],eligible_borrow_unverified:[_("ui.chat.session_readout.access.eligible_borrow_unverified.title",{owner:r}),_("ui.chat.session_readout.access.eligible_borrow_unverified.description",{label:t,owner:r})],effective_borrow:[_("ui.chat.session_readout.access.effective_borrow.title",{label:t,owner:r}),_("ui.chat.session_readout.access.effective_borrow.description")],expired:[_("ui.chat.session_readout.access.expired.title",{label:t}),_("ui.chat.session_readout.access.expired.description",{owner:r})],withdrawn:[_("ui.chat.session_readout.access.withdrawn.title",{label:t}),_("ui.chat.session_readout.access.withdrawn.description")],owner_unavailable:[_("ui.chat.session_readout.access.owner_unavailable.title",{owner:r}),_("ui.chat.session_readout.access.owner_unavailable.description",{label:t,owner:r})],device_bound:[_("ui.chat.session_readout.access.device_bound.title",{label:t}),_("ui.chat.session_readout.access.device_bound.description")],absent:[_("ui.chat.session_readout.access.absent.title",{label:t}),e.connectHere===!0?_("ui.chat.session_readout.access.absent.description_connect"):_("ui.chat.session_readout.access.absent.description_remote")]},s=e.state==="temporarily_unavailable",[a,c]=n?o[n]:[s?_("ui.chat.session_status.temporarily_unavailable",{label:t}):_("ui.chat.session_status.not_signed_in",{label:t}),s?_("ui.chat.session_status.temporarily_unavailable_description"):_("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];return n&&e.observedAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.last_checked",{time:Xi(e.observedAt)})),n&&e.lastGrantAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.last_resolved",{time:Xi(e.lastGrantAt)})),n&&e.lastGrantExpiresAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.grant_expiry",{time:Xi(e.lastGrantExpiresAt)})),n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push(_("ui.chat.session_readout.access.history.only")),{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 SM(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function EM(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function AM(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function aA(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function cA(e,t){return!!e.streams[t]}function Jh(e,t){return e.attached[t]?.turns.at(-1)}function RM(e,t){const n=Jh(e,t);return n?e.streams[n.asideId]:void 0}function xM(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 lA(){return{text:"",streaming:!0,settled:!1,error:null}}function dA(e){return{text:e,streaming:!1,settled:!0,error:null}}function uA(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const fA=Go(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]:lA()},attached:{...o.attached,[t]:{turns:[...o.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const o=aA(r.streams[t],n);return o?{streams:{...r.streams,[t]:o}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:dA(n)}}:r),failAside:(t,n)=>e(r=>cA(r,t)?{streams:{...r.streams,[t]:uA(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 IM(e,t){return Jh(e,t)?.asideId}const pA=4*1024*1024,Su=1024*1024,Yt=new Map;function Eu(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function hA(e){const t=e.slice(-200),n=Eu(t);if(n<=Su)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=Eu(t.slice(a));c>Su?r=a:(o=a,s=c)}return{records:t.slice(o),bytes:s}}function mA(e,t){const{records:n,bytes:r}=hA(UE(t.transcript).records);if(n.length===0){Yt.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:Au(n,t.owedLabels),markLabels:Au(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>o.index.has(a)))};Yt.delete(e),Yt.set(e,s),_A()}function Au(e,t){if(!t||t.size===0)return Ru;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:Ru}const Ru=new Set;function qh(e){const t=Yt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function gA(e){Yt.delete(e)}function _A(){let e=0;for(const t of Yt.values())e+=t.bytes;for(;e>pA&&Yt.size>0;){const t=Yt.keys().next().value;if(t===void 0)break;const n=Yt.get(t);Yt.delete(t),e-=n?.bytes??0}}const bA=8,vA=128,em=new Set,yA="",on=new Map,nl=e=>e??yA;function TM(e){return on.get(nl(e))??em}function CM(e,t,n){const r=nl(e),o=on.get(r)??new Set,s=new Set(o);if(n)for(s.delete(t),s.add(t);s.size>vA;){const a=s.values().next().value;if(a===void 0)break;s.delete(a)}else s.delete(t);for(on.delete(r),s.size>0&&on.set(r,s);on.size>bA;){const a=on.keys().next().value;if(a===void 0)break;on.delete(a)}return on.get(r)??em}function wA(e){on.delete(nl(e))}const kA=128,Ys=4096,Ji=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),xu=e=>e.startsWith("qg:")&&e.length>3;function OM(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 Ji("duplicate-prior-id");if(o.size===Ys)return Ji("prior-id-limit");o.set(u,{ordinal:c,order:d})}l.eligible!==!1&&xu(l.key)&&t.has(l.key)&&s.size<kA&&s.set(c,l.key)}for(const c of r)if(!o.has(c)){if(o.size===Ys)return Ji("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&&xu(c.key)&&s.set(a.ordinal,c.key)}return{complete:!0,owners:o,keys:s,reason:null}}function PM(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>Ys)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 y=a.get(f);y===void 0?a.set(f,{current:h,many:!1,lastOrder:m,reordered:!1,outside:!1}):(y.current!==h&&(y.many=!0),m<=y.lastOrder&&(y.reordered=!0),y.lastOrder=m)};for(let f=0;f<t.length;f+=1){const h=t[f];let m=null,y=!1;for(const v of h.segmentIds){if(s!==null){if(s.has(v))return r("duplicate-current-id");if(s.size===Ys)return r("current-uniqueness-unproved");s.add(v)}const p=e.owners.get(v);if(p!==void 0){if(o.has(v))return r("duplicate-current-id");o.add(v),l(p.ordinal,f,p.order),m===null?m=p.ordinal:m!==p.ordinal&&(y=!0)}}if(h.eligible===!1||y||m===null||m<0)continue;const b=e.keys.get(m);b!==void 0&&c.set(f,{owner:m,key:b})}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),y=h.key.slice(3);(m===void 0||m.many||m.reordered||m.outside||!o.has(y))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const 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 SA=8,EA="",Vn=new Map,rl=e=>e??EA;function MM(e){return Vn.get(rl(e))??null}function jM(e,t){const n=rl(e);for(Vn.delete(n),Vn.set(n,t);Vn.size>SA;){const r=Vn.keys().next().value;if(r===void 0)break;Vn.delete(r)}}function AA(e){Vn.delete(rl(e))}function RA(){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=_E(n.getTranscript()),f=u!==null&&u!==a?u:mE(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:po(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 xA={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"},IA={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function ol(e){return{kind:e,statement:_(xA[e]),action:IA[e]}}function Iu(e){return ol(Sy(e))}const TA=()=>ol("historyUnreadable"),CA=new Set(["subagent_start","subagent_progress","subagent_end"]),OA=(e,t)=>({...e,[t]:(e[t]??0)+1}),PA=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=tm(n);r&&(t[r]=(t[r]??0)+1)}return t},tm=e=>{if(!e||typeof e!="object")return null;const t=e;return CA.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},MA=(e,t)=>{const n=tm(t);return n?OA(e,n):e};function Tu(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 jA(e){for(const t of e)t.type==="aside_delta"&&fA.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function $A(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const Wn=new Set,io=new Set;function DA(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 NA=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),LA=15e3,za=[500,1e3,2e3,4e3,8e3,8e3],FA=za.length,UA=2e4,BA=1e4,HA=1e4;function Cu(e){const t=Math.max(1,Math.min(e,za.length));return za[t-1]??8e3}const WA=3,GA=250,zA=32*1024,Ou=512,Pu=new Set(["turn_end","agent_end"]),Mu=2,KA=500,ju=tl,VA=6,qi=fp("sessions.history"),ZA=2e3,$u={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},Xn=new Map,Es=new Map,YA=8,QA=2048,Du=1024,XA=1024,JA="",Un=new Map;function Nu(e){const t=e??JA,n=Un.get(t);if(n)return Un.delete(t),Un.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(Un.set(t,r);Un.size>YA;){const o=Un.keys().next().value;if(o===void 0||o===t)break;Un.delete(o)}return r}function ea(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function ta(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function qA(e,t){return Es.set(e,t),()=>{Es.get(e)===t&&Es.delete(e)}}function $M(e){const t=Es.get(e);return t?(t(),!0):!1}const Qe=new Map,eR=4,tR=16;function nm(e,t){e(n=>Vh(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function nR(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=di(n);return s[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:s}}function Ka(e,t){let n=Qe.get(e);if(!n){if(Qe.size>=tR){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>eR;){const s=n.keys().next();if(s.done)break;n.delete(s.value)}const o=Xn.get(e);o&&nm(o,r)}function DM(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 Va(e,t){const n=Qe.get(e);n&&(n.delete(t),n.size===0&&Qe.delete(e))}function Za(e,t){const n=Qe.get(e)?.get(t);n&&(n.settled=!0)}function Lu(e,t){return e?Qe.get(e)?.has(t)===!0:!1}function NM(e){return e?(Qe.get(e)?.size??0)>0:!1}function rR(e,t,n){const r=Qe.get(e)?.get(t);if(!r)return;r.text=n;const o=Xn.get(e);o&&o(s=>nR(s,t,n))}function oR(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 fs(e){Qe.delete(e)}function sR(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&&Va(e,r)}}function iR(e,t){Xn.set(e,t);const n=Qe.get(e);if(n)for(const r of n.values())nm(t,r);return()=>{Xn.get(e)===t&&Xn.delete(e)}}function aR(e,t){const n=Qe.get(e);if(!n)return t;let r=t;for(const o of n.values())r=Vh(r,o.id,o.text,o.images,void 0,o.documents);return r}function cR(e,t,n){return e===t?!0:!n}function lR(e,t){const n=Xn.get(e);if(!n)return Va(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",Zh(o,t)):(r="owner",o)}),Va(e,t),r}function rm(e,t){const n=Xn.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 dR(e){const t=qh(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:Lt,stale:!1,owedLabels:Wn,markLabels:io}}function uR(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function na(e,t){if(e.size!==0)for(const n of t)e.delete(Nt(n))}function ps(e,t){for(const n of t)e.add(Nt(n))}const Fu=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function LM(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),y=x.useRef(0),b=x.useRef(null),v=x.useRef(null),p=x.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const D=kt.getState();return ix(D.sessions,D.placementFacts,e)},[e]),E=x.useCallback(()=>{const D=f.current;return p()&&D!==null&&D.sessionId===e&&D.peer},[p,e]),k=x.useCallback(()=>{const D=f.current;return D!==null&&D.sessionId===e&&D.peer},[e]),[C,N]=x.useState(()=>{const D=t&&e?dR(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?aR(r,D?.transcript??Lt):Lt,stale:D?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:D?.owedLabels??Wn,labelMarked:D?.markLabels??io,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),O=x.useRef(C),R=x.useCallback(D=>{const q=D(O.current);return q===O.current||(O.current=q,N(q)),q},[]);x.useEffect(()=>Pg(()=>{R(D=>{const{failure:q}=D;if(!q?.kind)return D;const fe=ol(q.kind);return fe.statement===q.statement&&fe.action===q.action?D:{...D,failure:fe}})}),[R]);const g=x.useRef(e),w=x.useRef([]),S=x.useRef(Lt.index),I=x.useRef(new Set),F=x.useRef(new Set),$=x.useRef(Nu(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 D=++oe.current,q=new WeakMap;let fe=null;const Le=(te,re)=>{const ke=q.get(te);if(ke===void 0||xt(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)},Xo=te=>{for(const re of te)$.current.attempts.set(re,($.current.attempts.get(re)??0)+1)},Ei=te=>{R(re=>{const ke=new Set;for(const Fe of re.labelPending)re.labelPending.has(Fe)&&(ta($.current,re.transcript.argsByCall,Fe,ea(re))||ke.add(Fe));let we=null;for(const Fe of re.labelMarked)ta($.current,re.transcript.argsByCall,Fe,ea(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:Wn,labelMarked:we&&we.size===0?io:we??re.labelMarked}})},kg=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:Wn,labelMarked:we}})},Jo=async(te,re,ke=$u,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 Sg(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&&kg(ke.targets),Ei()}}},Sg=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 Eg(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 _n=R(vt=>{const $t=SE(vt.transcript,bt,ge.keys);return $t===vt.transcript?vt:{...vt,transcript:$t}});return S.current=_n.transcript.index,qe},Eg=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,_n=0,vt=0,$t=!1,bn=ke.size===0,cr=!1;const qo=O.current.cold,vn=T.current,Ln=vn?{epoch:vn.epoch,seq:vn.seq}:null,tn=new Set(pe.found),lr=()=>NE(pe.order,pe.targets,tn),M=()=>Kh(pe.order,pe.targets,tn),P=()=>{const Q=new Map;for(const yt of Re){if(tn.has(yt))continue;const Dt=pt.get(yt);Dt!==void 0&&Q.set(yt,Dt)}return Q},Ee=new Set(pe.every);for(const Q of tn)Ee.add(Q);const Re=new Set,pt=new Map;let Y=1;const yn=pe.targets.size>0;let he=Math.max(gu(lr()),yn?$.current.depth:0),Ze=0;for(;_n<ju&&vt<VA;){vt+=1;let Q;const yt=Pa(O.current.transcript),Dt=yt.revision;try{Q=await Ye({op:"sessions.history",sessionId:e,...bt?{beforeId:bt}:{},limit:Math.min(he,ju-_n),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Vt(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<WA?(Ie=window.setTimeout(()=>{if(Ie=0,oe.current!==te||qe()){Ei();return}Jo(te,re,pe,Fe+1,ge,ke,we)},Cu(Fe)),!0):(R(xe=>({...xe,status:"unavailable",failure:TA(),heldFrontend:null,...xe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{Ei()}if(oe.current!==te||qe())return!1;if(xt(O.current.transcript)!==Dt){if(!O.current.hydrated)continue;return!1}$.current.refused=!1;const Fn=Q.entries[0];_n+=Q.entries.length,ge?.(Q.entries.length),na(I.current,Q.entries),ps(F.current,Q.entries),R(xe=>{if(xt(xe.transcript)!==Dt)return xe;const zt=po(xe.transcript,Q,{authoritative:!0,orderRead:yt,peerSource:k(),readWitness:Ln}),dr=Yi(Q.entries,Ee),Ri=new Set(xe.labelPending);for(const Ig of dr)Ri.delete(Ig);return{...xe,hydrated:xe.hydrated||Q.entries.length>0||!qo,labelPending:Ri.size?Ri:Wn,labelMarked:DA(xe.labelMarked,dr),transcript:zt}}),e&&bt===void 0&&kt.getState().resolveHeldFromServer(e,Q.entries,!Q.cursor_missing);const xg=lr();for(const xe of Yi(Q.entries,Ee))tn.add(xe),Ee.add(xe);if(ME(Q.entries)&&(cr=!0),yn){const xe=jE(Q.entries,Ee);for(const zt of xe)Re.add(zt),Ee.add(zt);for(const[zt,dr]of CE(Q.entries,xe))pt.set(zt,dr);for(const zt of[...Re])tn.has(zt)&&Re.delete(zt);Re.size>0&&Y--<=0&&Re.clear()}$t=$t||re.size===0||Q.entries.some(xe=>re.has(Nt(xe))||_t.has(xe.id)),bn=bn||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));Fn&&(Ve.oldest=Fn),Ve.hasMore=Q.has_more,Ve.joined=$t,Ve.reachedHeld=bn;const Ai=lr()+Re.size;yn&&lr()<xg&&($.current.depth=Math.min(tl,Math.max($.current.depth,_n)));let Hl=!1;if(yn){const xe=M();Hl=OE(Q.entries,xe,pe.starts,P(),new Set(xe.filter(dr=>pe.waiting.has(dr))))||cr}if($E($t&&bn,Hl?0:Ai)||!Fn||!Q.has_more)return!1;bt=Fn.id,he=Ai>0?gu(Ai):Wa}return!1},Ll=()=>{if(ze&&cancelAnimationFrame(ze),Se&&clearTimeout(Se),ze=0,Se=0,oe.current!==D)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)Jc(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})}jA(te);const pe=M=>{const P=M.payload.history.entries,Ee=P.at(-1);if(!Ee)return!1;if(uR(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:r0(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||ps(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 _n=te.some(M=>M.type==="event"&&Pu.has(String(M.payload.type??""))),vt=mu($.current.attempts,hu(_t,qe),qe,Mu),$t=_n?mu($.current.attempts,[...$.current.attempts.keys(),...$.current.settled],qe,Mu):[],bn=[];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??"")&&bn.push(P)}const cr=[];for(const M of bn){const P=String(M.tool_call_id??"");qe.has(P)||$.current.settled.has(P)||cr.push(P)}for(const M of cr)$.current.settled.add(M);for(;$.current.settled.size>Ou;){const M=$.current.settled.values().next().value;if(M===void 0)break;$.current.settled.delete(M)}for(const[M,P]of pu(bn))$.current.starts.set(M,P);for(;$.current.starts.size>Du;){const M=$.current.starts.keys().next().value;if(M===void 0)break;$.current.starts.delete(M)}const qo=$.current.settleRows<KA?cr:[],vn=[...new Set([...vt,...$t,...qo])],Ln=vn.filter(M=>!$.current.painted.has(M));if(_t.length>0){$.current.order=hu(_t,new Set);for(const[M,P]of pu(_t))$.current.starts.set(M,P);for(;$.current.starts.size>Du;){const M=$.current.starts.keys().next().value;if(M===void 0)break;$.current.starts.delete(M)}for(const M of IE(_t))$.current.waiting.add(M);for(const M of DE(_t))$.current.waiting.delete(M);for(;$.current.waiting.size>XA;){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(Xo([...vt,...$t]);$.current.attempts.size>Ou;){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:_u(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=Fu(Y);if(!Ze&&!wy(fe,he,{allowEqual:Y.type==="snapshot"}))continue;Ze||(fe=he)}const yn=T.current;if((Y.type==="open"||"seq"in Y)&&!Fu(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:_u(P.transcript)},he&&P.status==="live"&&(P={...P,status:"reconnecting"}),Ee=!1}continue}if(!Ee){if(Y.type==="event"&&(Re=Ha(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 Dt=Re??P.transcript;yt&&(performance.mark("lop:open:history:start"),Dt=po(Dt,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"),na(I.current,Q.history.entries),ps(F.current,Q.history.entries)),e&&kt.getState().resolveHeldFromServer(e,Q.history.entries,yt),performance.mark("lop:open:seed:start"),Dt=xE(Dt,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 Fn=Tu(P.frontend??P.heldFrontend,Q.frontend.snapshot,Q.cold===!0||Q.attaching===!0);P={...P,contextCarried:Object.keys(Fn).length>0,subagentPulses:PA(Q.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...Q.frontend.snapshot,...Fn,attention:wr(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:Dt},Ee=!0,Re=null}continue}if(Y.type==="attention"){P.frontend&&(P={...P,frontend:{...P.frontend,attention:wr(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:Qy(P.frontend.jobs??[],he.job_deltas)}:{},attention:wr(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&&ky(yn,e,Y)){const he=Y.payload.frontend,Ze=Tu(P.frontend,he.snapshot,Y.payload.cold===!0);P={...P,contextCarried:Object.keys(Ze).length>0,frontend:{...he.snapshot,...Ze,attention:wr(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}NA.has(he)&&(P={...P,terminal:he}),Pu.has(he)&&(P={...P,turnsCompleted:P.turnsCompleted+1});const Ze=Ha(P.transcript,Y.payload,pt,{frame:{epoch:Y.epoch,seq:Y.seq},userStoppedAt:e?kt.getState().stoppedTurns[e]??null:null,queuedAskEngine:Uh(P.frontend)});Ze!==P.transcript&&(P={...P,transcript:Ze});const Q=MA(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,!$A(te))return M;if(Ln.length>0){const Y=new Set(P.labelPending);for(const yn of Ln)Y.add(yn);P={...P,labelPending:Y}}return P.frontend!==null&&P.frontend!==P.heldFrontend&&(P={...P,heldFrontend:P.frontend}),P}),Ln.length>0){for(const M of Ln)$.current.painted.add(M);for(;$.current.painted.size>QA;){const M=$.current.painted.values().next().value;if(M===void 0)break;$.current.painted.delete(M)}}const tn=ge||Ve,lr=qo.length>0&&vt.length===0&&$t.length===0&&!tn&&!Xe;if(tn||vn.length>0||Xe){const M=new Set(vn),P=$.current.order;Jo(D,bt,vn.length>0?{targets:M,order:P,starts:$.current.starts,waiting:$.current.waiting,every:new Set([...P,...M]),found:new Set(Yi(te.flatMap(Ee=>Ee.type==="snapshot"?Ee.payload.history.entries:[]),new Set(P))),pending:Ln}:$u,1,lr?Ee=>{$.current.settleRows+=Ee}:void 0,re,we)}if(Zy())for(const M of te)"epoch"in M&&"seq"in M&&Yy({carrier:"canonical-sse",sessionId:e,epoch:M.epoch,seq:M.seq,disposition:"processed"})},Ur=()=>{const te=ee;if(ee=null,f.current=null,h.current+=1,m.current&&(window.clearTimeout(m.current),m.current=0),y.current+=1,!!te){ft=!0;try{te()}finally{ft=!1}}},Br=()=>{const te=Pa(O.current.transcript),re=yu.currentToken(),ke=++Me.current;Be(),Oe=window.setTimeout(()=>{Oe=0,oe.current===D&&(Ur(),R(pe=>({...pe,subscriptionId:null,status:"unavailable",failure:Iu(lo.ended),...pe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ke&&(Ke=!0,Ce=window.setTimeout(()=>{Ce=0,oe.current===D&&Ul()},BA)))},UA);const we=p();ee=Ny({sessionId:e,epoch:V.current.epoch,afterSeq:V.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:Vt(O.current.transcript).slice(0,512),...we?{peerJournalSource:!0}:{}}:{}},pe=>{if(oe.current===D&&Me.current===ke){if(pe.kind==="error"||pe.kind==="end"){if(ft)return;if(Be(),Ur(),pe.kind==="error"&&pe.status===404){if(!n){e&&kt.getState().retireDraftWarm(e),R(ge=>({...ge,subscriptionId:null}));return}e&&(gA(e),wA(e),AA(e),kt.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??_("ui.common.errors.event_stream_failed"):_("ui.common.errors.event_stream_closed");if(R(ge=>({...ge,subscriptionId:null})),Je>=FA){R(ge=>({...ge,status:"unavailable",failure:Iu(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===D&&Br()},Cu(Je));return}if(pe.data!==void 0)try{const Fe=pe.data,Ve=Fe.length>=zA;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"&&(yu.note(e,"snapshot",re),Je=0,Be(),Ke=!1),w.current.push(ge),ze||(ze=requestAnimationFrame(Ll)),Se||(Se=window.setTimeout(Ll,GA))}catch{}}}),f.current={sessionId:e,peer:we},h.current+=1},Fl=()=>{H!==0&&(window.clearTimeout(H),H=0),V.current={},T.current=null,Ur(),Br()},Ul=()=>{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:ds(te.transcript,!1)})),O.current.hydrated||Jo(D,new Set(O.current.transcript.index.keys())),!ee&&Br()};Br(),Z.current=Ul,_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),Fl())},z.current=()=>{!O.current.hydrated&&me.current===0&&Jo(D,new Set(O.current.transcript.index.keys()))};const Ag=qA(e,Fl),Bl=()=>{if(!t||!e||b.current===e)return;const te=f.current;te===null||te.sessionId!==e||te.peer||p()&&(b.current=e,Ur(),Br())};v.current=Bl;const Rg=kt.subscribe(()=>{Bl()});return()=>{oe.current+=1,Z.current=null,z.current=null,_e.current=null,v.current=null,Rg(),m.current&&(window.clearTimeout(m.current),m.current=0),Ag(),Ur(),ze&&cancelAnimationFrame(ze),Se&&clearTimeout(Se),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||v.current?.()},[e,t,d]),x.useEffect(()=>{V.current={},T.current=null,S.current=Lt.index;const D=cR(g.current,e,n);g.current=e;const q=e?qh(e):null;S.current=D?O.current.transcript.index:(q?.transcript??Lt).index;const fe=new Set(D?I.current:[]);for(const ee of q?.replayBorn??[])fe.add(ee);const Le=D?O.current.transcript.index:(q?.transcript??Lt).index;for(const ee of fe)Le.has(ee)||fe.delete(ee);I.current=fe,D||(F.current=new Set),R(ee=>({...ee,frontend:null,heldFrontend:D?ee.heldFrontend:null,contextCarried:D?ee.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:D?ee.turnsCompleted:0,transcript:D?ee.transcript:q?.transcript??Lt,stale:D?ee.stale:q!==null,missing:D?ee.missing:!1,status:"connecting",subagentPulses:{},labelPending:q?.owedLabels??Wn,labelMarked:q?.markLabels??io,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),$.current=Nu(e)},[e,n]),x.useEffect(()=>{if(e)return()=>{const D=O.current.transcript;D.records.length>0&&mA(e,{transcript:D,owedLabels:new Set([...O.current.labelPending].filter(q=>ta($.current,O.current.transcript.argsByCall,q,ea(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 D=()=>{De.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)){De.current=window.setTimeout(D,qi);return}for(const ee of fe)if(Le.inFlight.has(ee)){De.current=window.setTimeout(D,qi);return}R(ee=>ee.labelPending.size===0&&ee.labelMarked.size===0?ee:{...ee,labelPending:Wn,labelMarked:io})};De.current=window.setTimeout(D,qi)},[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(D=>D.labelHoldLate?{...D,labelHoldLate:!1}:D);return}C.labelHoldLate||Ge.current||(Ge.current=window.setTimeout(()=>{Ge.current=0,R(D=>D.labelPending.size===0||D.labelHoldLate?D:{...D,labelHoldLate:!0})},ZA))},[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=RA());const Rt=x.useRef(!1),Ne=x.useRef(null),[Mt,ye]=x.useState(0);x.useEffect(()=>{const D=C.transcript,q=Vt(D);if(!e||!a||!D.orderNeedsReconcile&&(!D.journalGeneration||q.length===0)||Rt.current)return;const fe=H=>({fields:JSON.stringify([Mt,e,H.viewEpoch,xt(H),H.orderNeedsReconcile,H.orderWantedGeneration,Vt(H)]),demand:H.orderDemand}),Le=fe(D);if(Ne.current?.fields===Le.fields&&Ne.current.demand===Le.demand)return;Ne.current=Le;const ee=e,ft=D.viewEpoch;Rt.current=!0;let ze=null,Se=D;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=ds(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=ds(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=++y.current;m.current=window.setTimeout(()=>{m.current=0,y.current===Ce&&et.current===ee&&O.current.transcript.viewEpoch===ft&&h.current===H.streamEpoch&&R(Ke=>{const Be=ds(Ke.transcript,!0);return Be===Ke.transcript?Ke:{...Ke,transcript:Be}})},HA)};t0({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(Ip(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(jc(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,Ne.current=fe(Se);const Oe=E(),Ce=h.current;if(Ie==="lookup"||Ie==="payload"){const Be=O.current.transcript.journalGeneration,Xo=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:Xo,peer:Oe,streamEpoch:Ce}:{kind:"lookup",page:Xo,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||xt(Ce.transcript)!==Ie||Ce.transcript.viewEpoch!==ft?Ce:{...Ce,transcript:H.kind==="authority"?H.peer?fu(Ce.transcript,H.frame.payload.history,{authoritative:!0,orderRead:Oe}):yE(Ce.transcript,H.frame.payload.history,Oe):H.kind==="payload"?wE(Ce.transcript,H.page,Oe,Ie):fu(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(()=>{Rt.current=!1;const H=O.current.transcript,Ie=ze??Se;ze&&et.current===ee&&H.viewEpoch===ft&&!H.orderNeedsReconcile&&(Ne.current=fe(Ie)),(et.current!==ee||H.viewEpoch!==ft||xt(H)!==xt(Ie)||H.orderWantedGeneration!==Ie.orderWantedGeneration||H.orderNeedsReconcile!==Ie.orderNeedsReconcile||H.orderDemand!==Ie.orderDemand||JSON.stringify(Vt(H))!==JSON.stringify(Vt(Ie)))&&ye(Oe=>Oe+1)})},[R,e,a,E,C.transcript,Mt]);const Ae=x.useCallback(async()=>{const D=Te.current;if(!e||!D)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 D.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:Vt(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),jt=x.useCallback(async(D,q)=>{if(!e||gt.current)return!1;const fe=e;gt.current=!0;const Le=xt(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:Vt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}});return et.current!==fe||xt(O.current.transcript)!==Le||O.current.transcript.viewEpoch!==q?!1:(R(Se=>xt(Se.transcript)!==Le?Se:{...Se,transcript:po(Se.transcript,ze,{keepPaging:!0,peerSource:k(),readWitness:ft})}),na(I.current,ze.entries),ps(F.current,ze.entries),GE(ze.entries,D))}catch{return!1}finally{gt.current=!1}},[R,e,E,k]);x.useEffect(()=>r?iR(r,q=>{R(fe=>{const Le=q(fe.transcript);return Le===fe.transcript?fe:{...fe,transcript:Le}})}):void 0,[R,r]),x.useEffect(()=>{r&&sR(r,C.transcript)},[r,C.transcript]);const Fr=x.useCallback(()=>{R(D=>({...D,transcript:LE(D.transcript),olderFailed:!1,heldFrontend:null}))},[R]),ar=x.useCallback(()=>{Z.current?.()},[]),Ml=x.useCallback(()=>{_e.current?.()},[]),jl=x.useCallback(()=>{z.current?.()},[]),$l=x.useCallback((D,q="info")=>{R(fe=>({...fe,transcript:BE(fe.transcript,D,q)}))},[R]),Dl=x.useCallback(D=>{R(q=>({...q,pendingModel:D}))},[R]),Nl=x.useCallback(()=>{R(D=>D.pendingModel===null?D:{...D,pendingModel:null})},[R]);return x.useEffect(()=>{const D=C.pendingModel;if(!D)return;const q=Ga(D);if(!q)return;const fe=C.frontend;oA(fe,q)&&R(Le=>({...Le,pendingModel:null}))},[R,C.frontend,C.pendingModel]),x.useEffect(()=>{if(!C.pendingModel)return;const D=window.setTimeout(()=>R(q=>({...q,pendingModel:null})),LA);return()=>window.clearTimeout(D)},[R,C.pendingModel]),x.useMemo(()=>({...C,awaitingHydration:t&&!!e&&n&&!C.hydrated,loadOlder:ut,loadOlderDetailed:Ae,refreshTail:jt,clearView:Fr,addNote:$l,paintPendingModel:Dl,clearPendingModel:Nl,retry:ar,rehydrate:jl,reloadFromHistory:Ml}),[C,t,e,n,ut,Ae,jt,Fr,$l,Dl,Nl,ar,jl,Ml])}function pi(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
|
|
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.`,[rS="",oS=""]=nS.split("{goal}"),sS="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.",iS="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.",aS="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 kh(e){const t=e.trim();return t===sS||t===iS||t===aS||t.startsWith(eS)&&t.endsWith(tS)||t.startsWith(rS.trim())&&t.endsWith(oS.trim())}const cS=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function lS(e,t){const n=t?.match(cS)?.[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 br(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}const dS=32,uS=32*1024,fS=256*1024;function pS(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(y=>y.entry),...e]){if(m.type!=="prune"||!br(m.payload))continue;const{target:y,replacement:b}=m.payload;if(typeof y!="string"||!Number.isFinite(m.ts)||!br(b)||b.kind!=="message"||b.role!=="tool"||!Array.isArray(b.content)||!br(b.provider_payload)||Object.keys(b).some(O=>!["kind","role","content","tool_call_id","tool_name","provider_payload"].includes(O))||b.content.length===0||b.content.some(O=>!br(O)||typeof O.text!="string"||O.text.length>1e5||O.type!==void 0&&O.type!=="text"))continue;const v=b.tool_name;if(typeof v!="string"||typeof b.tool_call_id!="string"||b.tool_call_id.length===0)continue;const p=Jc(v,b.provider_payload.details),E=Tr(p),k=pk(E?.profile_action);if(!E||E.status!=="applied"||E.profile_kind!==v||!k||k.receipt_id!==E.receipt_id||k.profile_kind!==E.profile_kind||k.profile_name!==E.profile_name)continue;const C=a.get(y),N=c.has(y)||!!(C&&JSON.stringify(C.entry.payload.replacement)!==JSON.stringify(b));a.set(y,{entry:C?.entry??m,...N||C?.conflict?{conflict:!0}:{}})}const l=[];let d=2;const u=m=>{if(new TextEncoder().encode(JSON.stringify(m.entry)).length>uS)return;const y=new TextEncoder().encode(JSON.stringify(m)).length+(l.length?1:0);l.length<dS&&d+y<=fS&&(l.push(m),d+=y)};for(const m of a.values()){const{entry:y}=m,{target:b,replacement:v}=y.payload,p=v.tool_name,E=Tr(v.provider_payload.details);if(!E)continue;const k=r.get(b),C=k?void 0:t.find(F=>F.kind==="tool"&&F.sourceEntryId===b);if(m.conflict||!k&&(!C||C.kind!=="tool")){u(m);continue}const N=k?.payload,O=N&&br(N.provider_payload)?N.provider_payload.details:C?.kind==="tool"?C.details:null,R=Tr(O),g=N?.tool_call_id??(C?.kind==="tool"?C.toolCallId:null),w=N?.tool_name??(C?.kind==="tool"?C.toolName:null),S=k?.ts??(C?C.ts/1e3:0);if(k&&(N?.role!=="tool"||k.type!=="message")||!R||w!==p||g!==v.tool_call_id||y.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:v}:{id:b,type:"message",ts:S,payload:v,...C?.journalSeq!==void 0?{journal_seq:C.journalSeq}:{}};k?o.set(b,I):s.set(y.id,I)}const f=e.map(m=>o.get(m.id)??s.get(m.id)??m);for(const[m,y]of s)e.some(b=>b.id===m)||f.push(y);const h=n.length===l.length&&l.every((m,y)=>m.entry===n[y].entry&&m.conflict===n[y].conflict);return{entries:f,pending:h?n:l}}function hS(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||!br(e.payload.provider_payload))return!1;const n=Tr(e.payload.provider_payload.details),r=Tr(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 Sh(e){return e}const Ka="supplement_v1",mS="superseded",Vs=120,Xc=480,gS=20,tM=500,_S=10,bS=["outside","sensitive","missing","too-large"];function Eh(e,t){const n=[];let r=0;if(Array.isArray(e))for(const s of e.slice(0,_S)){if(!s||typeof s!="object")continue;const a=s,c=a.reason;if(!bS.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 Qc(e){return`supplement:${e}`}function vS(e){const t=e.payload??{};if(String(t.custom_type??"")!==Ka)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?Qc(r):null}function Zs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function yS(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:Zs(t.size_bytes)??0,mtime:Zs(t.mtime)??0,why:typeof t.why=="string"?t.why:"",...t.pinned===!0?{pinned:!0}:{}}}function Ah(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=yS(n);r&&t.push(r)}return t}function wS(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!Ih(n))return null;const r=Zs(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?Vs:Math.min(Xc,Math.max(Vs,Math.round(r)))}}function Rh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=wS(n);r&&t.push(r)}return t}function kS(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return Ih(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:Zs(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 xh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=kS(n);r&&t.push(r)}return t}const SS=/^[a-f0-9]{32}$/,ES=/\s+/,AS=/\.0$/;function Ih(e){return typeof e=="string"&&SS.test(e)}const RS={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function fu(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 nM(e,t){const n=e.state;if(e.error===mS||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?RS[r]??r:r}const rM="Preparing highlights…",oM="Highlights cancelled",sM="Couldn't prepare highlights",iM="Adjust…",aM="Cancel",cM="Retry",xS=64,IS={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 lM(e){return typeof e=="string"&&e?IS[e]??"":""}function Yi(e){return typeof e!="string"?"":e.replace(Yp,"").split(ES).filter(Boolean).join(" ")}function dM(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function TS(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(AS,"")} ${n}`;return""}function uM(e){const t=Yi(e.name)||Yi(e.path),n=Yi(e.path);return{name:t,path:n===t?"":n,size:TS(e.sizeBytes)}}function Ji(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function fM(e,t,n=e){return t?`Hide ${Ji(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${Ji(e,"graphic")}`:`Show ${Ji(e,"graphic")}`}function pM(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const CS="supplement",OS=1,PS=["ready","resize","error","pong"],MS=["resize","error","pong"],jS=64,qc=300,hM=5e3,mM=2e4;function gM(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==CS||n.v!==OS)return null;const r=n.t;if(typeof r!="string"||!PS.includes(r))return null;const o=r;if(MS.includes(o)&&(!t||t.length>jS||n.n!==t))return null;if(o==="error"){const s=n.msg;if(typeof s!="string"||s.length>qc)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 _M(){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 $S=["--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"],DS=120;function NS(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 $S){const s=t.getPropertyValue(o).trim();s&&(n[o]=s.slice(0,DS))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function bM(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(NS()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function vM(e){return`data:text/html;base64,${LS(e)}`}function LS(e){const t=FS(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 FS(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 yM(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function US(e){return Math.min(Xc,Math.max(Vs,e.heightHint))}function BS(e){return Math.min(Xc,Math.max(Vs,e))}function wM(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?BS(c):US(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 HS=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,Th=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,WS=/kind=(auth|quota)\b/,GS=/kind=(transient|timeout)\b/;function Ch(e){const t=a=>typeof a=="string"&&HS.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"&&(Th.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,s=typeof e.cause=="string"?e.cause.slice(0,xS):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...o?{detail:o}:{},...s?{cause:s}:{}}}function kM(e){if(!Th.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 SM(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return WS.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":GS.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 zS(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return Oh(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:Ah(e.files),..."withheld"in e||"withheld_more"in e?Eh(e.withheld,e.withheld_more):{}}:{},...n==="done"?{components:Rh(e.components),sounds:xh(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,qc)}:{},...Ch(e),live:!Ph(n)}:null}function KS(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!Oh(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,gS):[];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:Ah(e.files),filesMore:r,more:o,components:Rh(e.components),sounds:xh(e.sounds),...Eh(e.withheld,e.withheld_more),...Ch(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,qc)}:{}}}function pu(e,t,n){const r=KS(t);if(!r)return null;const o=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return Mh(o,r,e)}function Oh(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Ph(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function VS(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 ZS(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 YS(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 JS(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 Mh(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&fu(t.state)<fu(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),y=t.live!==void 0?t.live===!0?!0:Ph(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:Qc(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:VS(o,e?.files??[])?e?.files??[]:o,filesMore:d,more:XS(u,e?.more??[])?e?.more??[]:u,components:ZS(s,e?.components??[])?e?.components??[]:s,sounds:YS(a,e?.sounds??[])?e?.sounds??[]:a,withheld:JS(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:y}}function XS(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const EM=e=>e.kind===void 0||e.kind==="image",Lt={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function jh(e){return e==="skipped"||e==="aborted"}function hu(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function mu(e,t,n,r){return hu(n.args)??(r?.kind==="tool"?r.args:null)??hu(e.argsByCall.get(t)?.arguments)}function $h(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 fs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Yt(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!$h(n)&&Dh(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Jn(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:ho;const o=[];for(const s of r){const a=Dh(s);if(s.type==="document"||a===null&&!$h(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=fs(s.width),c.height=fs(s.height),c.sizeBytes=fs(s.size_bytes),c.durationS=fs(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?ho:n&&el(n,o)?n:o}const ho=[],Va=[];function Nh(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Va;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:Va:n&&QS(n,o)?n:o}function QS(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 gu(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 Lh(e,t,n){if(t.length===0)return e;if(e.length===0||el(e,t))return t;const r=gu(e),o=gu(t);return r!==o?r>o?e:t:n==="incoming"?e:t}function qS(e,t){return Lh(e,t,"incoming")}function el(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 At(e){const t=new Map;return e.forEach((n,r)=>t.set(n.id,r)),t}function eE(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const mn=new Set;function tl(e){return e.kind==="user"&&e.provisional===!0}function Fh(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{tl(n)&&r<t&&(t=r)}),t}function No(e,t=mn,n){if(n?.journalMode)return Dp(n,e).map(Sh);const r=e.map((a,c)=>({record:a,position:c})),o=Fh(e),s=a=>tl(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 tE(e,t,n){if(!n||t<=0)return mn;let r=null;for(const o of e){if(!tl(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&&sl(c)&&(a=!0),s&&a)break;s&&a&&(r??=new Set,r.add(o.id))}return r??mn}function nE(e){const{provisional:t,...n}=e;return n}function Za(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)&&el(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&&rE(a,c))continue}return!1}return!0}function rE(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(Za(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=No(a,mn,e);return{...e,records:c,index:At(c)}}const r=e.journalMode?No([...e.records,t],mn,e):[...e.records,t],o=At(r);return{...e,records:r,index:o}}function nl(e,t){if(!e.records.some(t))return e;const n=e.records.filter(r=>!t(r));return{...e,records:n,index:At(n)}}function Xi(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")?nl(e,s=>s.id===n):e}function oE(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:At(s)}}const sE=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function Uh(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 iE(e,t){const n=Ru(e),r=Ru(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const Bh="Context compacted",aE=12e4;function Hh(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>aE||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 cE(e){const t=Hh(e.records);return t===e.records?e:{...e,records:t,index:At(t)}}const lE="peer_message",dE="ask_response",uE="ask_timeout",Wh="Completed — runtime retired/disposed",Gh="Retired for an update — a turn was in flight and was cut; its earlier output is kept",fE="wake_prompt",pE="session_mcp_unavailable",hE=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),mE=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,_u=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,gE=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."]),zh=/^\[[^\]]{1,32}\]\s*/,Ys="Reason:",_E=/[\n;,(]| [—–] /,bE=/^\d+\.$/,vE=/[A-Z]/,yE=/\s/,mo=160;function Rs(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",...AE(t,n)};let r;return e===pE?r=wE(t):hE.has(e)?r=SE(t.trim().replace(zh,"")):r=RE(t),{level:"info",category:null,provider:null,...r}}function wE(e){const t=e.trim().replace(zh,"").split(`
|
|
33
|
+
`).map(c=>c.trim()),n=t[0]??"",r=t[1]?.startsWith(Ys)?t[1]:null,o=t.slice(r?2:1).filter(Boolean).join(`
|
|
34
|
+
`),s=(r?`${n} ${r}`:n).trim();if(s.length<=mo)return{headline:s,detail:o||null};const a=r===null?null:kE(r);if(a!==null){const c=(f,h)=>`${Ys} ${[f,h].filter(Boolean).join(" ")}`,l=f=>[f,o].filter(Boolean).join(`
|
|
35
|
+
`)||null,d=`${n} ${c(a.leading,a.clause)}`;if(d.length<=mo)return{headline:d,detail:l(a.rest)};const u=`${n} ${c("",a.clause)}`;if(u.length<=mo)return{headline:u,detail:l([a.leading,a.rest].filter(Boolean).join(" "))}}return{headline:Vh(s),detail:[r,o].filter(Boolean).join(`
|
|
36
|
+
`)||null}}function kE(e){const t=e.startsWith(Ys)?e.slice(Ys.length):e,n=t.indexOf("/mcp");if(n<0)return null;const r=t.slice(n),o=r.search(_E),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 SE(e){const t=e.trim(),n=EE(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 EE(e){for(let t=0;t<e.length-1;t++)if(".!?…".includes(e[t])&&yE.test(e[t+1])&&!bE.test(e.slice(0,t+1))&&vE.test(e.slice(t+1).trimStart()[0]??""))return t+1;return-1}function AE(e,t){const n=e.split(`
|
|
37
|
+
`),r=n[0].match(mE),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 Kh(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 RE(e){const t=xE(e),n=e.split(`
|
|
39
|
+
`).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function xE(e){const t=e.split(`
|
|
40
|
+
`).map(c=>c.trim()).filter(Boolean),n=c=>!_u.test(c)&&!IE(c),r=t.find(n),o=t.find(c=>_u.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 Vh(s)}function IE(e){return gE.has(e.replace(/\s+/g," ").trim().toLowerCase())}function Vh(e){const t=e.trim();if(t.length<=mo)return t;const n=t.slice(0,mo),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const TE="harness_injected",Zh=e=>!e||typeof e!="object"?!1:e[TE]===!0;function Yh(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function Jh(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const CE="ask";function bu(e,t){return t===!0&&String(e??"")===CE}function OE(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function Xh(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:Bh,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=Uh(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:Wh,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:Gh,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===Ka){const a=n.details??{};return pu(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(sE.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=Ba(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&Vi(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...Rs(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(h=>f[h]===u[h])?f:u,images:Jn(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===lE){const{body:u,sender:f}=Qp(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&Vi(t.sender,f)?t.sender:f}}if(a===fE){if(Ew(c)||Aw(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===dE){const u=c.answers,f={};if(u&&typeof u=="object")for(const[y,b]of Object.entries(u))f[String(y)]=Array.isArray(b)?b.map(v=>String(v)):[];const h=c.questions,m=Array.isArray(h)?h.flatMap(y=>{if(!y||typeof y!="object")return[];const b=y;return[{id:String(b.id??""),question:String(b.question??""),secret:b.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:r,askId:String(c.ask_id??""),status:String(c.status??"answered"),by:c.by&&typeof c.by=="object"?c.by:null,reason:typeof c.reason=="string"?c.reason:null,questions:m,answers:f,secretLost:c.secret_lost===!0}}if(a===uE){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===Ka)return pu(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?lS(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:Rw(c)}:{},attribution:n.attribution??"system",...Rs(a,d,c)}:null}const s=String(n.role??"");if(s==="user"){const a=Kh(n.provider_payload);if(a){const u=Ba({...a,text:Yt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&Vi(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",...Rs("hub_message",u.envelope||u.body,{...a,text:Yt(n)}),receipt:f&&Object.keys(u).every(m=>f[m]===u[m])?f:u,images:Jn(n,e.id,h)}}}if(Zh(n.provider_payload))return null;const c=Yt(n);if(kh(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=pi(c),d=Nh(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Jn(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=Yt(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(Jh(l))return null;const d=jh(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:Yt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Jn(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...yh(c.details,t?.kind==="tool"?t:null),diff:vh(bh(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:uh(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:ih(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:ah(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:wh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.details??null:null)}}return null}function PE(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 ME=/^(?:tool|compaction|local):/;function jE(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)&&!ME.test(t.id))return t.id}return null}function $E(e,t){const n=vS(t);if(n)return e.records[e.index.get(n)??-1]}function rl(e){const t=Dp(e,e.records);if(t===e.records)return e;const n=t.map(Sh);return{...e,records:n,index:At(n)}}const Lo=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Qh(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 DE(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&&Lo(r.journalSeq)&&n.add(o))}return{carried:t,admitted:n}}function ol(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function vu(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=ol(a);return l!==a&&(r=!0),l});let s=r?{...e,records:o}:e;return s=qh(s,n),s}function qh(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=DE(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 Js(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 Yo(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function em(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function NE(e,t,n){let r=Dr(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=Uc(r,{...s.payload,id:s.id});const o=Yo(r,!1);return rl(o.journalPeerSource===void 0&&!o.journalBodyOwed&&!o.journalSourceVoid&&o.journalSourceUnavailable===void 0?o:{...o,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function yu(e,t,n){let r=Dr(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=Yo(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=qh(r,s));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=Js(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=em(r,t),rl(r)}function LE(e,t,n,r){let o=Dr(e,t,[],!1,n,{peer:!0});o=Yo(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 y of l){if(typeof y.id!="string"||y.id===""||a(y.id))continue;const b=`tool:${String(y.payload?.tool_call_id??"")}`,v=f.get(y.id)??f.get(b),p=v===void 0?void 0:u[v];if(!p)continue;let E=Xh(y,p);E&&(E={...E,sourceEntryId:y.id,...p.sourcePrecedes?{sourcePrecedes:p.sourcePrecedes}:{}},Lo(y.journal_seq)?(E=Qh(E,y.id,t.journal_generation,y.journal_seq),d.push(y.id)):E=ol(E),m.set(p.id,E))}m.size>0&&(u=u.map(y=>m.get(y.id)??y),f=At(u))}let h=u===o.records?o:{...o,records:u,index:f};if(c){h=Js(h,d,!1);const m=(t.source_missing_ids??[]).filter(y=>typeof y=="string"&&y.length>0&&y.length<=128&&!a(y));if(m.length>0){h=Js(h,m,!1);const y=new Set(h.journalSourceVoid??[]);for(const b of m)y.add(b);h={...h,journalSourceVoid:y}}}return h=em(h,t),rl(h)}function ps(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function go(e,t,n={}){let r=e;const o=r,s=[];let a=e.profileHistoryPending;const c=T=>Yo(Js(T.profileHistoryPending===a?T:{...T,profileHistoryPending:a},s,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Dr(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=Uc(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=pS(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&&!nA(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]??$E(r,T);let Z=Xh(T,V);if(hS(T,V)&&V&&(Z=V),Z&&(r.journalMode||Z.kind==="tool"&&Jc(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&&Lo(T.journal_seq)?(Z=Qh(Z,T.id,t.journal_generation,T.journal_seq),s.push(T.id)):Z&&n.peerSource===!0&&(Z=ol(Z)),!(Z&&V&&OE(V,n.readWitness))&&Z&&h.push(Z)}let m=r.argsByCall,y=!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)||(y||(m=new Map(m),y=!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 b=y?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,v=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)&&!v.has(T.id)):[],E=n.replace?p.length>0?{...Lt,records:p,index:At(p)}:Lt:{...r,records:b},k=new Map(E.records.map(T=>[T.id,T]));let C=r!==o||n.replace||!n.replace&&b!==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:Lh(T.images,V.images,"current")};Za(V,Z)||(C=!0,k.set(T.id,Z));continue}Za(V,T)||(C=!0,k.set(T.id,T))}const N=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?mn:tE(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&&!N&&g.size===0)return c(r);const $=g.size===0?[...k.values()]:[...k.values()].map(T=>g.has(T.id)?nE(T):T),ne=Hh(No($,n.statedByOwner===!1?mn:new Set(h.map(T=>T.id)),r));return n.keepPaging?c({...r,records:ne,index:At(ne),argsByCall:m}):c({...r,records:ne,index:At(ne),oldestId:w,oldestTs:S,hasMore:I,argsByCall:m,compacting:N?!1:r.compacting,compactingSince:N?0:r.compactingSince})}const FE=/^(?:local|notice|retry|subagent|compaction):/;function sl(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!FE.test(e.id)}}function UE(e,t,n=mn){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(o=>!(o.ts<t.ts&&sl(o)&&!n.has(o.id)));return r.length===e.records.length?e:{...e,records:r,index:At(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const rn={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function Qi(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function Ya(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=Dr(o,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=No(d.records,mn,d);return d===o&&u===o.records?o:{...d,records:u,index:At(u)}}s&&(o=Uc(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=Qi(s);if(s===void 0||l===null)return rn.idlessFrameRefused+=1,o;const d=o.records[o.index.get(l)??-1];if(s.role==="user"){const u=Kh(s.provider_payload);if(u){const b=Yt(s),v=Ba({...u,text:b});if(v.body.trim()){const p=d?.kind==="user"&&d.provisional===!0;return $e(o,{kind:"custom",id:l,ts:p?Xs(o,n):n,customType:"hub_message",text:v.envelope,attribution:"user",...Rs("hub_message",v.envelope||v.body,{...u}),receipt:v,images:Jn(s,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(Zh(s.provider_payload))return o;const f=Yt(s);if(kh(f))return o;const h=d?.kind==="user"&&d.provisional===!0,m=Nh(s,l,d?.kind==="user"?d.documents:void 0),y=pi(f);return $e(o,{kind:"user",id:l,ts:h?Xs(o,n):n,text:f,images:Jn(s,l,d?.kind==="user"?d.images:void 0),...m.length?{documents:m}:{},...h?{provisional:!0}:{},...y?{skill:y}:{}})}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=Qi(s);if(s===void 0||l===null)return rn.idlessFrameRefused+=1,o;const d=o.index.get(l),u=String(t.delta??""),f=Yt(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 rn.settledAssistantUpdate+=1,o;if(r.seed!==!0&&a&&h.frame&&a.epoch===h.frame.epoch&&a.seq<=h.frame.seq)return rn.staleUpdateFrameDropped+=1,o;const m=eE(h.frame,a);if(r.seed===!0&&!f)return!h.text&&!u?o:(rn.seededDeltaWithheld+=h.text?1:0,$e(o,{...h,text:h.text||u,...m?{frame:m}:{},truncated:h.text?"interrupted":"prefix"}));let y;if(f){if(y=f+u,y.length<=h.text.length)return o}else{if(!u)return o;y=h.text+u}return $e(o,{...h,text:y,...m?{frame:m}:{},truncated:f?void 0:h.truncated})}case"message_end":{const l=Qi(s);if(s===void 0)return rn.idlessFrameRefused+=1,o;if(l===null){if(s.role!=="assistant")return rn.idlessFrameRefused+=1,o;let y;for(const p of o.records)if(!(p.kind!=="assistant"||!p.streaming)){if(y!==void 0)return rn.idlessFrameRefused+=1,o;y=p}if(y===void 0)return rn.idlessFrameRefused+=1,o;const b=Array.isArray(s.tool_calls)?s.tool_calls:[],v={...y,streaming:!1,settledAt:y.settledAt??n,callsTools:b.length>0,...y.text||b.length===0?{complete:!0}:{}};return $e(o,v)}if(s.role!=="assistant")return o;const d=o.index.get(l),u=Yt(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,y=o.journalPeerSource===!0||m,b=y&&u!==void 0&&u===o.journalGeneration,v=d.map(k=>String(k.id??"")).filter(k=>k.length>0&&k.length<=128),p={entries:d.map(k=>{const C=String(k.id??""),N=f?.[C],O=h?.[C];return{id:C,ts:b&&typeof O=="number"&&Number.isFinite(O)?O:n/1e3,type:"message",payload:{kind:k.custom_type?"custom":"message",...k},...b&&Lo(N)?{journal_seq:N}:{}}}),has_more:o.hasMore,...b?{journal_generation:u}:{}};let E=go(o,p,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:y});if(y&&v.length>0)if(b){const k=v.filter(C=>!Lo(f?.[C]));k.length>0&&(E=vu(E,k))}else E=vu(E,v),u!==void 0&&(E=Dr(E,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),E=Yo(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"?Xi(o,d):o;const b=String(t.not_run_reason??"").trim()||null,v=String(t.not_run_kind??"").trim()||null;if(bu(t.tool_name,c)&&!b&&!m)return d?Xi(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:b?"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:ho,added:0,removed:0,diff:null,stopped:!1,notRunReason:b,notRunKind:b?v:null,neverSent:b!==null};return d&&h?.kind==="tool"&&f?.kind!=="tool"?oE(o,d,E):$e(d&&f?.kind==="tool"?Xi(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=mu(o,l,t,u),h=f&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:f,anchoredAt:Or(t)??n}):o.argsByCall,m=h===o.argsByCall?o:{...o,argsByCall:h};return bu(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:Or(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:ho,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=fh(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(Jh(f.details))return rm(o,d);const h=mu(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:ho,added:0,removed:0,diff:null,stopped:!1},y=h&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:h,anchoredAt:Or(t)??n}):o.argsByCall,b=y===o.argsByCall?o:{...o,argsByCall:y},v=r.userStoppedAt??null,p=!!(t.is_error??f.is_error),E=jh(f.details?.__fault),k=v!==null&&(typeof m.startedAt=="number"?m.startedAt<=v:p);return $e(b,{...m,args:h,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:Yt(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:qS(Jn(f,d,m.images),m.images),...yh(f.details,m),diff:vh(bh(f.details),m.diff),stopped:m.stopped||k||E,delivery:uh(f.details,m.delivery,m.toolName),bridge:ih(m.toolName,f.details,m.bridge),bridgeLabel:ah(m.toolName,f.details,m.bridgeLabel),details:wh(m.toolName,f.details,m.details)})}case"supplement_progress":{const l=zS(t);if(!l)return o;const d=Qc(l.anchor),u=o.records[o.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,h=Mh(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:Uh(String(t.detail??"")),h=f?f.text:l&&d?iE(l,d):Bh,m=`compaction:${o.generation}:${l}:${d}`,y=o.compacting?{...o,compacting:!1,compactingSince:0}:o;return y.index.has(m)?y:f?$e(y,{kind:"notice",id:m,ts:n,text:h,level:f.level}):cE($e(y,{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 Or(e){return Ty(e.started_at_epoch)}function il(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function BE(e){const t=il(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function HE(e,t){const n=Or(e);if(n!==null)return n;const r=il(e);if(!r)return null;const o=t.argsByCall.get(r)?.anchoredAt;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}function WE(e,t){if(Or(e)!==null)return!1;const n=il(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<=Fh(t.records)}function al(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 mi(e){return e.type==="tool_execution_end"}function GE(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=Yh(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let h=n;const m=BE(f);if(m!==null&&!o.index.has(m)){const y=HE(f,o);if(y!==null)h=y,c=!0,WE(f,o)&&l.add(m);else if(mi(f)||al(f)||!s)continue}o=Ya(o,f,h,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return o;const d=No(o.records,l,o);return{...o,records:d,index:At(d)}}function wu(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!mi(r)&&!al(r))continue;const o=String(r.tool_call_id??"");if(!o)continue;const s=Or(r);s!==null&&t.set(o,s)}return t}function zE(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 KE=5e3;function VE(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 ZE(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-KE}function ku(e,t){const n=[];for(const r of e??[]){if(!r)continue;const o=r;if(!mi(o)&&!al(o))continue;const s=String(o.tool_call_id??"");!s||n.includes(s)||t.has(s)||n.push(s)}return n}function Su(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 YE=3.25,Ja=100,cl=500;function Eu(e){return e<=0?Ja:Math.min(cl,Ja+Math.ceil(YE*e))}function qi(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 JE(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function XE(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 QE(e,t){return e&&t===0}function qE(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"&&!mi(r)&&!s)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function tm(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 eA(e,t,n){return tm(e,t,n).length}function Au(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 tA(e,t=Date.now()){return e.records.length===0&&!e.profileHistoryPending?.length?e:{...Lt,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function nA(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 rA(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return nl(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function Xs(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function nm(e,t,n,r,o=Date.now(),s=Va){if(e.index.has(t))return e;const a=pi(n);return $e(e,{kind:"user",id:t,ts:Xs(e,o),text:n,images:r,...s.length?{documents:s}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function rm(e,t){return nl(e,n=>n.id===t)}let xu=0;function oA(e,t,n,r=Date.now()){return xu+=1,$e(e,{kind:"notice",id:`local:${r}:${xu}`,ts:Xs(e,r),text:t,level:n})}function AM(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"?Wh:s==="retired"?Gh:s==="error"?"Stopped with an error":"Interrupted",level:s==="closed"?"info":s==="retired"?"warning":s==="error"?"error":"warning"}))}const sA="compacting context…";function RM(e){return typeof e=="string"&&e.trim()===sA}const iA=[1500,5e3];async function xM(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of iA){await t(n);try{if(await e())return}catch{}}}function aA(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 cA=["store","routed","request","snapshot","content","painted","sendable"],lA=6e4,dA="[open-trace]",uA=/^[A-Za-z0-9_-]{1,80}$/,fA=["sidebar","open","native"];function pA(e,t,n){const r=uA.test(e.sessionId)?e.sessionId:"?",o=fA.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=[dA,`t=${e.token}`,`session=${r}`,`via=${o}`,`outcome=${t}`,...cA.map(u=>`${u}=${s(e.stages[u])}`),`settled=${s(l)}`];return n!==void 0&&d.push(`by=t${n}`),d.join(" ")}function hA(e){let t=0,n=null;const r=(s,a)=>{const c=n;if(c){n=null,e.clearTimer(c.timer);for(const l of Object.keys(c.fallbacks))c.stages[l]===void 0&&(c.stages[l]=c.fallbacks[l]);e.log(pA(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:{},fallbacks:{},timer:void 0,frameRequested:!1,endListeners:[]};return l.timer=e.setTimer(()=>{n===l&&r("timeout")},lA),n=l,c},note(s,a,c,l){const d=n;if(!(!d||!s||d.sessionId!==s)&&!(c!==void 0&&c!==d.token)){if(l?.fallback===!0){d.stages[a]===void 0&&d.fallbacks[a]===void 0&&(d.fallbacks[a]=e.now());return}if(a==="content"&&!d.frameRequested){d.frameRequested=!0,o(d,"content"),e.nextFrame(()=>{n===d&&o(d,"painted")});return}a==="painted"||a==="content"||o(d,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 mA=typeof window<"u";function gA(e,t,n){t(()=>n(e))}const _A=e=>{const t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)},ea=hA({now:()=>performance.now(),nextFrame:e=>{mA&&typeof requestAnimationFrame=="function"&&typeof MessageChannel=="function"?gA(e,t=>requestAnimationFrame(()=>t()),_A):setTimeout(e,0)},log:e=>console.warn(e),setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e)});function IM(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,e.note(c,"store"),l.validatingSessionId!==c&&e.note(c,"sendable")},a=r(s);e.onEnd(t,a),s()}const Iu=new Set(["openrouter","radient","radient-key"]),bA=new Set(["auto","openrouter/auto"]),vA=()=>_("ui.chat.session_readout.model.router_auto");function om(e){return e.slice(e.lastIndexOf("/")+1)||e}function yA(e,t){return e===t||e===om(t)}function Xa(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 wA(e,t){return t?Xa(e?.selected_model)===t||Xa(e?.effective_model)===t:!1}function TM(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||yA(r,e.model_id)||r.toLowerCase()==="unknown";return{name:Iu.has(t)&&bA.has(e.model_id)?vA():o?om(n):r,selector:n}}function CM(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function OM(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function PM(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function MM(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 jM(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 $M(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function kA(e){const t=e.trim();return t&&(sm(t)??t)}const Tu=new Map;function sm(e){const t=_n();let n=Tu.get(t);return n===void 0&&(n={auto:_("ui.chat.session_readout.effort.level.auto"),none:_("ui.chat.session_readout.effort.level.none"),minimal:_("ui.chat.session_readout.effort.level.minimal"),low:_("ui.chat.session_status.effort_level.low"),medium:_("ui.chat.session_status.effort_level.medium"),high:_("ui.chat.session_status.effort_level.high"),xhigh:_("ui.chat.session_readout.effort.level.xhigh"),max:_("ui.chat.session_readout.effort.level.max"),unknown:_("ui.chat.session_readout.effort.level.unknown"),reasoning:_("ui.chat.session_readout.effort.level.reasoning")},Tu.set(t,n)),n[e.toLowerCase()]}const co=e=>kA(e).toLowerCase(),hs=e=>{const t=sm(e.trim());return t===void 0?e:t.toLowerCase()};function im(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 DM(e,t){const n=(e??t)?.effective_model;return im(n)?null:n?.model_id??null}function NM(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=im(e);return t?{label:t,adjustable:n===null||n.length>0,knownLadder:!!(n&&n.length>0),levelKnown:!0,detail:n&&n.length>0?_("ui.chat.session_readout.effort.detail.offers",{levels:Es(n.map(co))}):_("ui.chat.session_readout.effort.detail.session")}:n&&n.length>0?{label:"auto",adjustable:!0,knownLadder:!0,levelKnown:!0,detail:r?_("ui.chat.session_readout.effort.detail.auto_with_default",{default:co(r),levels:Es(n.map(co))}):_("ui.chat.session_readout.effort.detail.auto",{levels:Es(n.map(co))})}:o?{label:"unknown",adjustable:!0,knownLadder:!1,levelKnown:!1,detail:_("ui.chat.session_readout.effort.detail.not_reported",{command:"/effort <level>"})}:n&&e.reasoning?{label:"reasoning",adjustable:!1,knownLadder:!0,levelKnown:!0,detail:_("ui.chat.session_readout.effort.detail.no_levels")}:n===null&&r?{label:r,adjustable:!1,knownLadder:!1,levelKnown:!0,detail:_("ui.chat.session_readout.effort.detail.default_only")}:null}function LM(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:_("ui.chat.session_readout.effort.detail.offers",{levels:Es(n.map(co))})}}function SA(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=Qr(n.provider);if(!a)return null;const c=Qr(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:Qr(n.label)||a,effectiveState:d,owner:Qr(n.owner_label)||Qr(n.owner_device)||_("ui.chat.session_readout.access.owner_fallback"),observedAt:ta(n.observed_at),lastGrantAt:ta(n.last_grant_at),lastGrantExpiresAt:ta(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 FM(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function UM(e){return e&&e.draft!==!0?SA(e.frontend,e.servingLocality):null}function Qr(e){return typeof e=="string"?e.trim():""}function ta(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function na(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function BM(e){const{label:t,effectiveState:n}=e,r=e.owner||_("ui.chat.session_readout.access.owner_fallback"),o={local:[_("ui.chat.session_readout.access.local.title",{label:t}),_("ui.chat.session_readout.access.local.description")],pending:[_("ui.chat.session_readout.access.pending.title",{label:t}),_("ui.chat.session_readout.access.pending.description")],eligible_borrow_unverified:[_("ui.chat.session_readout.access.eligible_borrow_unverified.title",{owner:r}),_("ui.chat.session_readout.access.eligible_borrow_unverified.description",{label:t,owner:r})],effective_borrow:[_("ui.chat.session_readout.access.effective_borrow.title",{label:t,owner:r}),_("ui.chat.session_readout.access.effective_borrow.description")],expired:[_("ui.chat.session_readout.access.expired.title",{label:t}),_("ui.chat.session_readout.access.expired.description",{owner:r})],withdrawn:[_("ui.chat.session_readout.access.withdrawn.title",{label:t}),_("ui.chat.session_readout.access.withdrawn.description")],owner_unavailable:[_("ui.chat.session_readout.access.owner_unavailable.title",{owner:r}),_("ui.chat.session_readout.access.owner_unavailable.description",{label:t,owner:r})],device_bound:[_("ui.chat.session_readout.access.device_bound.title",{label:t}),_("ui.chat.session_readout.access.device_bound.description")],absent:[_("ui.chat.session_readout.access.absent.title",{label:t}),e.connectHere===!0?_("ui.chat.session_readout.access.absent.description_connect"):_("ui.chat.session_readout.access.absent.description_remote")]},s=e.state==="temporarily_unavailable",[a,c]=n?o[n]:[s?_("ui.chat.session_status.temporarily_unavailable",{label:t}):_("ui.chat.session_status.not_signed_in",{label:t}),s?_("ui.chat.session_status.temporarily_unavailable_description"):_("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];return n&&e.observedAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.last_checked",{time:na(e.observedAt)})),n&&e.lastGrantAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.last_resolved",{time:na(e.lastGrantAt)})),n&&e.lastGrantExpiresAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.grant_expiry",{time:na(e.lastGrantExpiresAt)})),n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push(_("ui.chat.session_readout.access.history.only")),{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 HM(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function WM(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function GM(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function EA(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function AA(e,t){return!!e.streams[t]}function am(e,t){return e.attached[t]?.turns.at(-1)}function zM(e,t){const n=am(e,t);return n?e.streams[n.asideId]:void 0}function KM(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 RA(){return{text:"",streaming:!0,settled:!1,error:null}}function xA(e){return{text:e,streaming:!1,settled:!0,error:null}}function IA(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const TA=Vo(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]:RA()},attached:{...o.attached,[t]:{turns:[...o.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const o=EA(r.streams[t],n);return o?{streams:{...r.streams,[t]:o}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:xA(n)}}:r),failAside:(t,n)=>e(r=>AA(r,t)?{streams:{...r.streams,[t]:IA(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 VM(e,t){return am(e,t)?.asideId}const CA=4*1024*1024,Cu=1024*1024,Jt=new Map;function Ou(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function OA(e){const t=e.slice(-200),n=Ou(t);if(n<=Cu)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=Ou(t.slice(a));c>Cu?r=a:(o=a,s=c)}return{records:t.slice(o),bytes:s}}function PA(e,t){const{records:n,bytes:r}=OA(rA(t.transcript).records);if(n.length===0){Jt.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:Pu(n,t.owedLabels),markLabels:Pu(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>o.index.has(a)))};Jt.delete(e),Jt.set(e,s),jA()}function Pu(e,t){if(!t||t.size===0)return Mu;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:Mu}const Mu=new Set;function cm(e){const t=Jt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function MA(e){Jt.delete(e)}function jA(){let e=0;for(const t of Jt.values())e+=t.bytes;for(;e>CA&&Jt.size>0;){const t=Jt.keys().next().value;if(t===void 0)break;const n=Jt.get(t);Jt.delete(t),e-=n?.bytes??0}}const $A=8,DA=128,lm=new Set,NA="",sn=new Map,ll=e=>e??NA;function ZM(e){return sn.get(ll(e))??lm}function YM(e,t,n){const r=ll(e),o=sn.get(r)??new Set,s=new Set(o);if(n)for(s.delete(t),s.add(t);s.size>DA;){const a=s.values().next().value;if(a===void 0)break;s.delete(a)}else s.delete(t);for(sn.delete(r),s.size>0&&sn.set(r,s);sn.size>$A;){const a=sn.keys().next().value;if(a===void 0)break;sn.delete(a)}return sn.get(r)??lm}function LA(e){sn.delete(ll(e))}const FA=128,Qs=4096,ra=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),ju=e=>e.startsWith("qg:")&&e.length>3;function JM(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 ra("duplicate-prior-id");if(o.size===Qs)return ra("prior-id-limit");o.set(u,{ordinal:c,order:d})}l.eligible!==!1&&ju(l.key)&&t.has(l.key)&&s.size<FA&&s.set(c,l.key)}for(const c of r)if(!o.has(c)){if(o.size===Qs)return ra("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&&ju(c.key)&&s.set(a.ordinal,c.key)}return{complete:!0,owners:o,keys:s,reason:null}}function XM(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>Qs)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 y=a.get(f);y===void 0?a.set(f,{current:h,many:!1,lastOrder:m,reordered:!1,outside:!1}):(y.current!==h&&(y.many=!0),m<=y.lastOrder&&(y.reordered=!0),y.lastOrder=m)};for(let f=0;f<t.length;f+=1){const h=t[f];let m=null,y=!1;for(const v of h.segmentIds){if(s!==null){if(s.has(v))return r("duplicate-current-id");if(s.size===Qs)return r("current-uniqueness-unproved");s.add(v)}const p=e.owners.get(v);if(p!==void 0){if(o.has(v))return r("duplicate-current-id");o.add(v),l(p.ordinal,f,p.order),m===null?m=p.ordinal:m!==p.ordinal&&(y=!0)}}if(h.eligible===!1||y||m===null||m<0)continue;const b=e.keys.get(m);b!==void 0&&c.set(f,{owner:m,key:b})}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),y=h.key.slice(3);(m===void 0||m.many||m.reordered||m.outside||!o.has(y))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const 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 UA=8,BA="",Yn=new Map,dl=e=>e??BA;function QM(e){return Yn.get(dl(e))??null}function qM(e,t){const n=dl(e);for(Yn.delete(n),Yn.set(n,t);Yn.size>UA;){const r=Yn.keys().next().value;if(r===void 0)break;Yn.delete(r)}}function HA(e){Yn.delete(dl(e))}function WA(){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=jE(n.getTranscript()),f=u!==null&&u!==a?u:PE(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:go(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 GA={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"},zA={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function ul(e){return{kind:e,statement:_(GA[e]),action:zA[e]}}function $u(e){return ul(Py(e))}const KA=()=>ul("historyUnreadable"),VA=new Set(["subagent_start","subagent_progress","subagent_end"]),ZA=(e,t)=>({...e,[t]:(e[t]??0)+1}),YA=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=dm(n);r&&(t[r]=(t[r]??0)+1)}return t},dm=e=>{if(!e||typeof e!="object")return null;const t=e;return VA.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},JA=(e,t)=>{const n=dm(t);return n?ZA(e,n):e};function Du(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 XA(e){for(const t of e)t.type==="aside_delta"&&TA.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function QA(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const zn=new Set,lo=new Set;function qA(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 eR=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),tR=15e3,Qa=[500,1e3,2e3,4e3,8e3,8e3],nR=Qa.length,rR=2e4,oR=1e4,sR=1e4;function Nu(e){const t=Math.max(1,Math.min(e,Qa.length));return Qa[t-1]??8e3}const iR=3,aR=250,cR=32*1024,Lu=512,Fu=new Set(["turn_end","agent_end"]),Uu=2,lR=500,Bu=cl,dR=6,oa=vp("sessions.history"),uR=2e3,Hu={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},er=new Map,xs=new Map,fR=8,pR=2048,Wu=1024,hR=1024,mR="",Hn=new Map;function Gu(e){const t=e??mR,n=Hn.get(t);if(n)return Hn.delete(t),Hn.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(Hn.set(t,r);Hn.size>fR;){const o=Hn.keys().next().value;if(o===void 0||o===t)break;Hn.delete(o)}return r}function sa(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function ia(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function gR(e,t){return xs.set(e,t),()=>{xs.get(e)===t&&xs.delete(e)}}function ej(e){const t=xs.get(e);return t?(t(),!0):!1}const Je=new Map,_R=4,bR=16;function um(e,t){e(n=>nm(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function vR(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=pi(n);return s[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:s}}function qa(e,t){let n=Je.get(e);if(!n){if(Je.size>=bR){const s=Je.keys().next();s.done||Je.delete(s.value)}n=new Map,Je.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>_R;){const s=n.keys().next();if(s.done)break;n.delete(s.value)}const o=er.get(e);o&&um(o,r)}function tj(e){if(!e)return null;const t=Je.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function ec(e,t){const n=Je.get(e);n&&(n.delete(t),n.size===0&&Je.delete(e))}function tc(e,t){const n=Je.get(e)?.get(t);n&&(n.settled=!0)}function zu(e,t){return e?Je.get(e)?.has(t)===!0:!1}function nj(e){return e?(Je.get(e)?.size??0)>0:!1}function yR(e,t,n){const r=Je.get(e)?.get(t);if(!r)return;r.text=n;const o=er.get(e);o&&o(s=>vR(s,t,n))}function wR(e,t){if(e===t)return;const n=Je.get(e);if(!n)return;Je.delete(e);const r=Je.get(t)??new Map;for(const[o,s]of n)s.identity=t,r.set(o,s);Je.set(t,r)}function ms(e){Je.delete(e)}function kR(e,t){const n=Je.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&&ec(e,r)}}function SR(e,t){er.set(e,t);const n=Je.get(e);if(n)for(const r of n.values())um(t,r);return()=>{er.get(e)===t&&er.delete(e)}}function ER(e,t){const n=Je.get(e);if(!n)return t;let r=t;for(const o of n.values())r=nm(r,o.id,o.text,o.images,void 0,o.documents);return r}function AR(e,t,n){return e===t?!0:!n}function RR(e,t){const n=er.get(e);if(!n)return ec(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",rm(o,t)):(r="owner",o)}),ec(e,t),r}function fm(e,t){const n=er.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 xR(e){const t=cm(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:Lt,stale:!1,owedLabels:zn,markLabels:lo}}function IR(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function aa(e,t){if(e.size!==0)for(const n of t)e.delete(Nt(n))}function gs(e,t){for(const n of t)e.add(Nt(n))}const Ku=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function rj(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),y=x.useRef(0),b=x.useRef(null),v=x.useRef(null),p=x.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const D=kt.getState();return Sx(D.sessions,D.placementFacts,e)},[e]),E=x.useCallback(()=>{const D=f.current;return p()&&D!==null&&D.sessionId===e&&D.peer},[p,e]),k=x.useCallback(()=>{const D=f.current;return D!==null&&D.sessionId===e&&D.peer},[e]),[C,N]=x.useState(()=>{const D=t&&e?xR(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?ER(r,D?.transcript??Lt):Lt,stale:D?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:D?.owedLabels??zn,labelMarked:D?.markLabels??lo,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),O=x.useRef(C),R=x.useCallback(D=>{const q=D(O.current);return q===O.current||(O.current=q,N(q)),q},[]);x.useEffect(()=>Bg(()=>{R(D=>{const{failure:q}=D;if(!q?.kind)return D;const pe=ul(q.kind);return pe.statement===q.statement&&pe.action===q.action?D:{...D,failure:pe}})}),[R]);const g=x.useRef(e),w=x.useRef([]),S=x.useRef(Lt.index),I=x.useRef(new Set),F=x.useRef(new Set),$=x.useRef(Gu(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 D=++oe.current,q=new WeakMap;let pe=null;const Le=(te,re)=>{const ke=q.get(te);if(ke===void 0||xt(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,Qe=0,H=0,Ie=0,Oe=0,Ce=0,Ke=!1;const Be=()=>{Oe&&(window.clearTimeout(Oe),Oe=0)},es=te=>{for(const re of te)$.current.attempts.set(re,($.current.attempts.get(re)??0)+1)},xi=te=>{R(re=>{const ke=new Set;for(const Fe of re.labelPending)re.labelPending.has(Fe)&&(ia($.current,re.transcript.argsByCall,Fe,sa(re))||ke.add(Fe));let we=null;for(const Fe of re.labelMarked)ia($.current,re.transcript.argsByCall,Fe,sa(re))||(we=we??new Set(re.labelMarked),we.delete(Fe));if(ke.size===0&&!we)return re;const ue=new Set(re.labelPending);for(const Fe of ke)ue.delete(Fe);return{...re,labelPending:ue.size?ue:zn,labelMarked:we&&we.size===0?lo:we??re.labelMarked}})},Og=te=>{R(re=>{let ke=null,we=null;for(const ue of te)re.labelPending.has(ue)&&(ke=ke??new Set(re.labelPending),ke.delete(ue),we=we??new Set(re.labelMarked),we.add(ue));return!ke||!we?re:{...re,labelPending:ke.size?ke:zn,labelMarked:we}})},ts=async(te,re,ke=Hu,we=1,ue,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 Pg(te,re,Fe,Ve,ke,we,ue)}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&&Og(ke.targets),xi()}}},Pg=async(te,re,ke,we,ue,Fe,Ve)=>{const ge={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:ke.size===0},Xe=O.current.transcript.viewEpoch,qe=await Mg(te,re,ke,we,ue,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 vn=R(vt=>{const $t=UE(vt.transcript,bt,ge.keys);return $t===vt.transcript?vt:{...vt,transcript:$t}});return S.current=vn.transcript.index,qe},Mg=async(te,re,ke,we,ue,Fe,Ve,ge)=>{const Xe=O.current.transcript.viewEpoch,qe=()=>O.current.transcript.viewEpoch!==Xe,_t=new Set;let bt,vn=0,vt=0,$t=!1,yn=ke.size===0,ur=!1;const ns=O.current.cold,wn=T.current,Un=wn?{epoch:wn.epoch,seq:wn.seq}:null,nn=new Set(ue.found),fr=()=>eA(ue.order,ue.targets,nn),M=()=>tm(ue.order,ue.targets,nn),P=()=>{const J=new Map;for(const yt of Re){if(nn.has(yt))continue;const Dt=pt.get(yt);Dt!==void 0&&J.set(yt,Dt)}return J},Ee=new Set(ue.every);for(const J of nn)Ee.add(J);const Re=new Set,pt=new Map;let Y=1;const kn=ue.targets.size>0;let he=Math.max(Eu(fr()),kn?$.current.depth:0),Ze=0;for(;vn<Bu&&vt<dR;){vt+=1;let J;const yt=Fa(O.current.transcript),Dt=yt.revision;try{J=await Ye({op:"sessions.history",sessionId:e,...bt?{beforeId:bt}:{},limit:Math.min(he,Bu-vn),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(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<iR?(Ie=window.setTimeout(()=>{if(Ie=0,oe.current!==te||qe()){xi();return}ts(te,re,ue,Fe+1,ge,ke,we)},Nu(Fe)),!0):(R(xe=>({...xe,status:"unavailable",failure:KA(),heldFrontend:null,...xe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{xi()}if(oe.current!==te||qe())return!1;if(xt(O.current.transcript)!==Dt){if(!O.current.hydrated)continue;return!1}$.current.refused=!1;const Bn=J.entries[0];vn+=J.entries.length,ge?.(J.entries.length),aa(I.current,J.entries),gs(F.current,J.entries),R(xe=>{if(xt(xe.transcript)!==Dt)return xe;const Kt=go(xe.transcript,J,{authoritative:!0,orderRead:yt,peerSource:k(),readWitness:Un}),pr=qi(J.entries,Ee),Ti=new Set(xe.labelPending);for(const Ng of pr)Ti.delete(Ng);return{...xe,hydrated:xe.hydrated||J.entries.length>0||!ns,labelPending:Ti.size?Ti:zn,labelMarked:qA(xe.labelMarked,pr),transcript:Kt}}),e&&bt===void 0&&kt.getState().resolveHeldFromServer(e,J.entries,!J.cursor_missing);const Dg=fr();for(const xe of qi(J.entries,Ee))nn.add(xe),Ee.add(xe);if(JE(J.entries)&&(ur=!0),kn){const xe=XE(J.entries,Ee);for(const Kt of xe)Re.add(Kt),Ee.add(Kt);for(const[Kt,pr]of VE(J.entries,xe))pt.set(Kt,pr);for(const Kt of[...Re])nn.has(Kt)&&Re.delete(Kt);Re.size>0&&Y--<=0&&Re.clear()}$t=$t||re.size===0||J.entries.some(xe=>re.has(Nt(xe))||_t.has(xe.id)),yn=yn||J.entries.some(xe=>ke.has(Nt(xe)));for(const xe of J.entries)_t.add(xe.id);for(const xe of J.entries)Ve.keys.add(Nt(xe));Bn&&(Ve.oldest=Bn),Ve.hasMore=J.has_more,Ve.joined=$t,Ve.reachedHeld=yn;const Ii=fr()+Re.size;kn&&fr()<Dg&&($.current.depth=Math.min(cl,Math.max($.current.depth,vn)));let Yl=!1;if(kn){const xe=M();Yl=ZE(J.entries,xe,ue.starts,P(),new Set(xe.filter(pr=>ue.waiting.has(pr))))||ur}if(QE($t&&yn,Yl?0:Ii)||!Bn||!J.has_more)return!1;bt=Bn.id,he=Ii>0?Eu(Ii):Ja}return!1},zl=()=>{if(ze&&cancelAnimationFrame(ze),Se&&clearTimeout(Se),ze=0,Se=0,oe.current!==D)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)sl(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})}XA(te);const ue=M=>{const P=M.payload.history.entries,Ee=P.at(-1);if(!Ee)return!1;if(IR(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:y0(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"&&!ue(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||gs(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 vn=te.some(M=>M.type==="event"&&Fu.has(String(M.payload.type??""))),vt=Su($.current.attempts,ku(_t,qe),qe,Uu),$t=vn?Su($.current.attempts,[...$.current.attempts.keys(),...$.current.settled],qe,Uu):[],yn=[];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??"")&&yn.push(P)}const ur=[];for(const M of yn){const P=String(M.tool_call_id??"");qe.has(P)||$.current.settled.has(P)||ur.push(P)}for(const M of ur)$.current.settled.add(M);for(;$.current.settled.size>Lu;){const M=$.current.settled.values().next().value;if(M===void 0)break;$.current.settled.delete(M)}for(const[M,P]of wu(yn))$.current.starts.set(M,P);for(;$.current.starts.size>Wu;){const M=$.current.starts.keys().next().value;if(M===void 0)break;$.current.starts.delete(M)}const ns=$.current.settleRows<lR?ur:[],wn=[...new Set([...vt,...$t,...ns])],Un=wn.filter(M=>!$.current.painted.has(M));if(_t.length>0){$.current.order=ku(_t,new Set);for(const[M,P]of wu(_t))$.current.starts.set(M,P);for(;$.current.starts.size>Wu;){const M=$.current.starts.keys().next().value;if(M===void 0)break;$.current.starts.delete(M)}for(const M of zE(_t))$.current.waiting.add(M);for(const M of qE(_t))$.current.waiting.delete(M);for(;$.current.waiting.size>hR;){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(es([...vt,...$t]);$.current.attempts.size>Lu;){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"){pe=null,P={...P,frontend:null,heldFrontend:P.frontend??P.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:Au(P.transcript)},Ee=!1;continue}if(Y.type==="open")pe=null;else if("seq"in Y){const he={epoch:Y.epoch,seq:Y.seq},Ze=Ku(Y);if(!Ze&&!Cy(pe,he,{allowEqual:Y.type==="snapshot"}))continue;Ze||(pe=he)}const kn=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:Au(P.transcript)},he&&P.status==="live"&&(P={...P,status:"reconnecting"}),Ee=!1}continue}if(!Ee){if(Y.type==="event"&&(Re=Ya(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 J=Y.payload,yt=!J.history.cursor_missing&&!Ze;let Dt=Re??P.transcript;yt&&(performance.mark("lop:open:history:start"),Dt=go(Dt,J.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"),aa(I.current,J.history.entries),gs(F.current,J.history.entries)),e&&kt.getState().resolveHeldFromServer(e,J.history.entries,yt),performance.mark("lop:open:seed:start"),Dt=GE(Dt,J.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 Bn=Du(P.frontend??P.heldFrontend,J.frontend.snapshot,J.cold===!0||J.attaching===!0);P={...P,contextCarried:Object.keys(Bn).length>0,subagentPulses:YA(J.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...J.frontend.snapshot,...Bn,attention:Er(P.frontend?.attention,J.frontend.snapshot.attention,e)},history:Ze?P.history:J.history,cold:J.cold,ownerEpoch:J.frontend.epoch,failure:null,hydrated:P.hydrated||yt&&J.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:Dt},Ee=!0,Re=null}continue}if(Y.type==="attention"){P.frontend&&(P={...P,frontend:{...P.frontend,attention:Er(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 J=he.epoch!==P.ownerEpoch&&Ze.epoch===he.epoch,yt=he.changes!==void 0&&Ze.epoch===he.epoch;(J||he.epoch===P.ownerEpoch&&(P.frontend.sequence<he.sequence||P.frontend.sequence===he.sequence&&yt))&&(P={...P,contextCarried:!1,ownerEpoch:J?he.epoch:P.ownerEpoch,frontend:{...P.frontend,...Ze,...Ze.jobs==null&&he.job_deltas?{jobs:p0(P.frontend.jobs??[],he.job_deltas)}:{},attention:Er(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&&Oy(kn,e,Y)){const he=Y.payload.frontend,Ze=Du(P.frontend,he.snapshot,Y.payload.cold===!0);P={...P,contextCarried:Object.keys(Ze).length>0,frontend:{...he.snapshot,...Ze,attention:Er(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}eR.has(he)&&(P={...P,terminal:he}),Fu.has(he)&&(P={...P,turnsCompleted:P.turnsCompleted+1});const Ze=Ya(P.transcript,Y.payload,pt,{frame:{epoch:Y.epoch,seq:Y.seq},userStoppedAt:e?kt.getState().stoppedTurns[e]??null:null,queuedAskEngine:Yh(P.frontend)});Ze!==P.transcript&&(P={...P,transcript:Ze});const J=JA(P.subagentPulses,Y.payload);J!==P.subagentPulses&&(P={...P,subagentPulses:J})}}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,!QA(te))return M;if(Un.length>0){const Y=new Set(P.labelPending);for(const kn of Un)Y.add(kn);P={...P,labelPending:Y}}return P.frontend!==null&&P.frontend!==P.heldFrontend&&(P={...P,heldFrontend:P.frontend}),P}),Un.length>0){for(const M of Un)$.current.painted.add(M);for(;$.current.painted.size>pR;){const M=$.current.painted.values().next().value;if(M===void 0)break;$.current.painted.delete(M)}}const nn=ge||Ve,fr=ns.length>0&&vt.length===0&&$t.length===0&&!nn&&!Xe;if(nn||wn.length>0||Xe){const M=new Set(wn),P=$.current.order;ts(D,bt,wn.length>0?{targets:M,order:P,starts:$.current.starts,waiting:$.current.waiting,every:new Set([...P,...M]),found:new Set(qi(te.flatMap(Ee=>Ee.type==="snapshot"?Ee.payload.history.entries:[]),new Set(P))),pending:Un}:Hu,1,fr?Ee=>{$.current.settleRows+=Ee}:void 0,re,we)}if(u0())for(const M of te)"epoch"in M&&"seq"in M&&f0({carrier:"canonical-sse",sessionId:e,epoch:M.epoch,seq:M.seq,disposition:"processed"})},Wr=()=>{const te=ee;if(ee=null,f.current=null,h.current+=1,m.current&&(window.clearTimeout(m.current),m.current=0),y.current+=1,!!te){ft=!0;try{te()}finally{ft=!1}}},Gr=()=>{const te=Fa(O.current.transcript),re=ea.currentToken(),ke=++Me.current;Be(),Oe=window.setTimeout(()=>{Oe=0,oe.current===D&&(Wr(),R(ue=>({...ue,subscriptionId:null,status:"unavailable",failure:$u(po.ended),...ue.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ke&&(Ke=!0,Ce=window.setTimeout(()=>{Ce=0,oe.current===D&&Vl()},oR)))},rR);const we=p();ee=Vy({sessionId:e,epoch:V.current.epoch,afterSeq:V.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:Zt(O.current.transcript).slice(0,512),...we?{peerJournalSource:!0}:{}}:{}},ue=>{if(oe.current===D&&Me.current===ke){if(ue.kind==="error"||ue.kind==="end"){if(ft)return;if(Be(),Wr(),ue.kind==="error"&&ue.status===404){if(!n){e&&kt.getState().retireDraftWarm(e),R(ge=>({...ge,subscriptionId:null}));return}e&&(MA(e),LA(e),HA(e),kt.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=ue.kind==="error"?ue.detail??_("ui.common.errors.event_stream_failed"):_("ui.common.errors.event_stream_closed");if(R(ge=>({...ge,subscriptionId:null})),Qe>=nR){R(ge=>({...ge,status:"unavailable",failure:$u(Fe),...ge.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}Qe+=1;const Ve=T.current;Ve&&(V.current={epoch:Ve.epoch,afterSeq:Ve.seq}),R(ge=>ge.status==="unavailable"&&Qe>1?ge:{...ge,status:"reconnecting",failure:null}),H=window.setTimeout(()=>{H=0,oe.current===D&&Gr()},Nu(Qe));return}if(ue.data!==void 0)try{const Fe=ue.data,Ve=Fe.length>=cR;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"&&(ea.note(e,"snapshot",re),Qe=0,Be(),Ke=!1),w.current.push(ge),ze||(ze=requestAnimationFrame(zl)),Se||(Se=window.setTimeout(zl,aR))}catch{}}},ue=>{ue==="requested"&&ea.note(e,"request",re)}),f.current={sessionId:e,peer:we},h.current+=1},Kl=()=>{H!==0&&(window.clearTimeout(H),H=0),V.current={},T.current=null,Wr(),Gr()},Vl=()=>{Qe=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:ps(te.transcript,!1)})),O.current.hydrated||ts(D,new Set(O.current.transcript.index.keys())),!ee&&Gr()};Gr(),Z.current=Vl,_e.current=()=>{O.current.liveUpdatesReloading||(R(te=>({...te,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Qe=0,H&&(window.clearTimeout(H),H=0),Ce&&(window.clearTimeout(Ce),Ce=0),Kl())},z.current=()=>{!O.current.hydrated&&me.current===0&&ts(D,new Set(O.current.transcript.index.keys()))};const jg=gR(e,Kl),Zl=()=>{if(!t||!e||b.current===e)return;const te=f.current;te===null||te.sessionId!==e||te.peer||p()&&(b.current=e,Wr(),Gr())};v.current=Zl;const $g=kt.subscribe(()=>{Zl()});return()=>{oe.current+=1,Z.current=null,z.current=null,_e.current=null,v.current=null,$g(),m.current&&(window.clearTimeout(m.current),m.current=0),jg(),Wr(),ze&&cancelAnimationFrame(ze),Se&&clearTimeout(Se),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||v.current?.()},[e,t,d]),x.useEffect(()=>{V.current={},T.current=null,S.current=Lt.index;const D=AR(g.current,e,n);g.current=e;const q=e?cm(e):null;S.current=D?O.current.transcript.index:(q?.transcript??Lt).index;const pe=new Set(D?I.current:[]);for(const ee of q?.replayBorn??[])pe.add(ee);const Le=D?O.current.transcript.index:(q?.transcript??Lt).index;for(const ee of pe)Le.has(ee)||pe.delete(ee);I.current=pe,D||(F.current=new Set),R(ee=>({...ee,frontend:null,heldFrontend:D?ee.heldFrontend:null,contextCarried:D?ee.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:D?ee.turnsCompleted:0,transcript:D?ee.transcript:q?.transcript??Lt,stale:D?ee.stale:q!==null,missing:D?ee.missing:!1,status:"connecting",subagentPulses:{},labelPending:q?.owedLabels??zn,labelMarked:q?.markLabels??lo,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),$.current=Gu(e)},[e,n]),x.useEffect(()=>{if(e)return()=>{const D=O.current.transcript;D.records.length>0&&PA(e,{transcript:D,owedLabels:new Set([...O.current.labelPending].filter(q=>ia($.current,O.current.transcript.argsByCall,q,sa(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 D=()=>{De.current=0;const q=O.current.labelPending,pe=O.current.labelMarked;if(q.size===0&&pe.size===0)return;const Le=$.current;for(const ee of q)if(Le.inFlight.has(ee)){De.current=window.setTimeout(D,oa);return}for(const ee of pe)if(Le.inFlight.has(ee)){De.current=window.setTimeout(D,oa);return}R(ee=>ee.labelPending.size===0&&ee.labelMarked.size===0?ee:{...ee,labelPending:zn,labelMarked:lo})};De.current=window.setTimeout(D,oa)},[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(D=>D.labelHoldLate?{...D,labelHoldLate:!1}:D);return}C.labelHoldLate||Ge.current||(Ge.current=window.setTimeout(()=>{Ge.current=0,R(D=>D.labelPending.size===0||D.labelHoldLate?D:{...D,labelHoldLate:!0})},uR))},[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=WA());const Rt=x.useRef(!1),Ne=x.useRef(null),[Mt,ye]=x.useState(0);x.useEffect(()=>{const D=C.transcript,q=Zt(D);if(!e||!a||!D.orderNeedsReconcile&&(!D.journalGeneration||q.length===0)||Rt.current)return;const pe=H=>({fields:JSON.stringify([Mt,e,H.viewEpoch,xt(H),H.orderNeedsReconcile,H.orderWantedGeneration,Zt(H)]),demand:H.orderDemand}),Le=pe(D);if(Ne.current?.fields===Le.fields&&Ne.current.demand===Le.demand)return;Ne.current=Le;const ee=e,ft=D.viewEpoch;Rt.current=!0;let ze=null,Se=D;const Qe=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=ps(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=ps(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=++y.current;m.current=window.setTimeout(()=>{m.current=0,y.current===Ce&&et.current===ee&&O.current.transcript.viewEpoch===ft&&h.current===H.streamEpoch&&R(Ke=>{const Be=ps(Ke.transcript,!0);return Be===Ke.transcript?Ke:{...Ke,transcript:Be}})},sR)};b0({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(Np(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(Bc(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,Ne.current=pe(Se);const Oe=E(),Ce=h.current;if(Ie==="lookup"||Ie==="payload"){const Be=O.current.transcript.journalGeneration,es=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:es,peer:Oe,streamEpoch:Ce}:{kind:"lookup",page:es,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||xt(Ce.transcript)!==Ie||Ce.transcript.viewEpoch!==ft?Ce:{...Ce,transcript:H.kind==="authority"?H.peer?yu(Ce.transcript,H.frame.payload.history,{authoritative:!0,orderRead:Oe}):NE(Ce.transcript,H.frame.payload.history,Oe):H.kind==="payload"?LE(Ce.transcript,H.page,Oe,Ie):yu(Ce.transcript,H.page,{authoritative:!1})}),Qe(H))}}).then(H=>{ze=H.kind==="complete"?H.transcript:null}).catch(H=>{console.warn("[canonical] source-order reconcile refused",H)}).finally(()=>{Rt.current=!1;const H=O.current.transcript,Ie=ze??Se;ze&&et.current===ee&&H.viewEpoch===ft&&!H.orderNeedsReconcile&&(Ne.current=pe(Ie)),(et.current!==ee||H.viewEpoch!==ft||xt(H)!==xt(Ie)||H.orderWantedGeneration!==Ie.orderWantedGeneration||H.orderNeedsReconcile!==Ie.orderNeedsReconcile||H.orderDemand!==Ie.orderDemand||JSON.stringify(Zt(H))!==JSON.stringify(Zt(Ie)))&&ye(Oe=>Oe+1)})},[R,e,a,E,C.transcript,Mt]);const Ae=x.useCallback(async()=>{const D=Te.current;if(!e||!D)return{kind:"nothing-to-load"};const q=e,pe=be.current.epoch,Le=()=>be.current.epoch===pe,ee=O.current.transcript.viewEpoch,ft=()=>O.current.transcript.viewEpoch===ee,ze=await D.load(`${q}#${pe}`,{getTranscript:()=>O.current.transcript,readPage:Se=>Ye({op:"sessions.history",sessionId:q,beforeId:Se,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>Le()&&ft(),commit:Se=>R(Qe=>{const H=Se(Qe.transcript);return H===Qe.transcript?Qe:{...Qe,transcript:H}}).transcript,setLoading:Se=>{Le()&&R(Qe=>Qe.loadingOlder===Se?Qe:{...Qe,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),jt=x.useCallback(async(D,q)=>{if(!e||gt.current)return!1;const pe=e;gt.current=!0;const Le=xt(O.current.transcript),ee=T.current,ft=ee?{epoch:ee.epoch,seq:ee.seq}:null;try{const ze=await Ye({op:"sessions.history",sessionId:pe,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}});return et.current!==pe||xt(O.current.transcript)!==Le||O.current.transcript.viewEpoch!==q?!1:(R(Se=>xt(Se.transcript)!==Le?Se:{...Se,transcript:go(Se.transcript,ze,{keepPaging:!0,peerSource:k(),readWitness:ft})}),aa(I.current,ze.entries),gs(F.current,ze.entries),aA(ze.entries,D))}catch{return!1}finally{gt.current=!1}},[R,e,E,k]);x.useEffect(()=>r?SR(r,q=>{R(pe=>{const Le=q(pe.transcript);return Le===pe.transcript?pe:{...pe,transcript:Le}})}):void 0,[R,r]),x.useEffect(()=>{r&&kR(r,C.transcript)},[r,C.transcript]);const Hr=x.useCallback(()=>{R(D=>({...D,transcript:tA(D.transcript),olderFailed:!1,heldFrontend:null}))},[R]),dr=x.useCallback(()=>{Z.current?.()},[]),Ul=x.useCallback(()=>{_e.current?.()},[]),Bl=x.useCallback(()=>{z.current?.()},[]),Hl=x.useCallback((D,q="info")=>{R(pe=>({...pe,transcript:oA(pe.transcript,D,q)}))},[R]),Wl=x.useCallback(D=>{R(q=>({...q,pendingModel:D}))},[R]),Gl=x.useCallback(()=>{R(D=>D.pendingModel===null?D:{...D,pendingModel:null})},[R]);return x.useEffect(()=>{const D=C.pendingModel;if(!D)return;const q=Xa(D);if(!q)return;const pe=C.frontend;wA(pe,q)&&R(Le=>({...Le,pendingModel:null}))},[R,C.frontend,C.pendingModel]),x.useEffect(()=>{if(!C.pendingModel)return;const D=window.setTimeout(()=>R(q=>({...q,pendingModel:null})),tR);return()=>window.clearTimeout(D)},[R,C.pendingModel]),x.useMemo(()=>({...C,awaitingHydration:t&&!!e&&n&&!C.hydrated,loadOlder:ut,loadOlderDetailed:Ae,refreshTail:jt,clearView:Hr,addNote:Hl,paintPendingModel:Wl,clearPendingModel:Gl,retry:dr,rehydrate:Bl,reloadFromHistory:Ul}),[C,t,e,n,ut,Ae,jt,Hr,Hl,Wl,Gl,dr,Bl,Ul])}function gi(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
|
|
41
41
|
|
|
42
42
|
`)?e:`${t}
|
|
43
43
|
|
|
44
|
-
${e}`}const ra={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function As(e,t,n){const r=[...e.attachments??[]],o=[],s=[],a=new Set;for(const h of t.attachments){const m=r.find(b=>b.path===h&&!a.has(b.id));if(m){a.add(m.id),s.push(m.id);continue}const y={id:n(),path:h};o.push(y),s.push(y.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:pi(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 fR(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 pR(e){return{text:pi(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function hR(e,t){if(!e||!t)return!1;const n=pR(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 mR(e,t=()=>crypto.randomUUID()){const n={};for(const[r,o]of Object.entries(e??{}))n[r]=o.inFlight?As(o,o.inFlight,t):o;return n}function gR(e,t){const n=t.text,r=pi(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 _R=300,om="conversation-input-store";let Do=null,sm=om,wt=null,oa=!1;const Ya=()=>{try{return globalThis.localStorage??null}catch{return null}},ho=()=>{wt!==null&&(clearTimeout(wt),wt=null);const e=Do;if(!e)return;const t=sm,n=Ya();if(n){try{n.setItem(t,JSON.stringify(e))}catch(r){oa||(oa=!0,console.warn("[composer] the draft could not be persisted; it stays in memory for this session",r));return}Do=null,oa=!1}},FM=()=>{ho()},UM=()=>{Do=null,wt!==null&&(clearTimeout(wt),wt=null)},bR={getItem:e=>{const t=Ya();if(!t)return null;const n=t.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}},setItem:(e,t)=>{Do=t,sm=e,wt!==null&&clearTimeout(wt),wt=setTimeout(()=>{wt=null,ho()},_R)},removeItem:e=>{Do=null,wt!==null&&(clearTimeout(wt),wt=null),Ya()?.removeItem(e)}};typeof window<"u"&&typeof window.addEventListener=="function"&&(window.addEventListener("pagehide",ho),window.addEventListener("beforeunload",ho),window.document?.addEventListener("visibilitychange",()=>{window.document.visibilityState==="hidden"&&ho()}));const at=Go()(ci((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"&&!fR(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&&(r.currentHistoryIndex??null)!==null&&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]??ra,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]??ra;n!==r&&s&&(c=As(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=As(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=pi(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]??ra;o.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:As(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?hR(r,r.returned):o(r),c=r.returned?gR(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:om,storage:bR,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:mR(e?.inputByConversation)})}));function im(e){if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null}function BM(e,t){return t?e.filter(n=>n.session_id===t&&am(n)).length:0}function am(e){if(im(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function vR(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function HM(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 WM={cwd:""};function yR(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,vR(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function wR(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 GM(e,t){const n=e.trim();if(!n)return{checked:!0,rung:null,confirmation:o=>_("ui.chat.session_readout.draft.confirm_model",{selector:o})};if(!t.ladderKnown)return{checked:!1,rung:null,refusal:_("ui.chat.session_readout.draft.refusal_ladder_unread")};const r=t.ladder.find(o=>o.trim().toLowerCase()===n.toLowerCase());return r?{checked:!0,rung:r,confirmation:o=>_("ui.chat.session_readout.draft.confirm_model_effort",{selector:o,effort:us(r)})}:{checked:!0,rung:null,confirmation:o=>t.level?_("ui.chat.session_readout.draft.confirm_effort_changed",{selector:o,level:us(t.level),wanted:us(n)}):_("ui.chat.session_readout.draft.confirm_effort_unset",{selector:o,wanted:us(n)})}}function zM(e,t){return e!==!0?null:t==="on"?_("ui.chat.fast_mode.stays_on"):t==="off"?_("ui.chat.fast_mode.turned_off"):_("ui.chat.fast_mode.unsupported_stays_off")}const KM=()=>_("ui.chat.fast_mode.service_cannot_carry"),VM="fast_unavailable";function sl(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function ZM(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function YM(e){const t=e instanceof Pe?e:null;return t?.code==="fast_mode_unsupported"?_("ui.chat.fast_mode.pick_unsupported"):t?.status===422?_("ui.chat.fast_mode.service_unavailable"):_("ui.chat.fast_mode.not_changed")}function QM(e,t){const n={...e,model:sl(e.model,t)};return{queryKey:yR(n),queryFn:()=>wR(n),placeholderData:Lg,staleTime:3e4,retry:!1}}function ae(e){return typeof e=="string"?e.trim():""}function gr(e){const t=ae(e);return t||null}function Dn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ao(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function cm(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function Jn(e,t){return typeof e=="boolean"?e:t}function Qa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Dr(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 Dr(t)}return[]}function kR(e){if(!In(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:cm(e.attempts),last_frame_at:Dn(e.last_frame_at),next_retry_at:Dn(e.next_retry_at),last_error:ae(e.last_error)}}function In(e){return typeof e=="object"&&e!==null}const SR=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function ER(e,t){const n=ae(e);return SR.includes(n)?n:t?"reachable":"unreachable_legacy"}const AR=["running","not_listening","unknown"];function RR(e){const t=ae(e);return AR.includes(t)?t:void 0}function xR(e){if(Array.isArray(e))return e.filter(In).map(t=>({endpoint:ae(t.endpoint),connected:t.connected===!0,detail:ae(t.detail),latency_ms:Dn(t.latency_ms)})).filter(t=>t.endpoint!=="")}function XM(e){const t=new Set,n=[];for(const a of Dr(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=xR(a.attempts),u=a.reachable?void 0:kR(a.redial);n.push({device_id:c,name:ae(a.name),reachable:a.reachable,link_state:ER(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:gr(a.unreachable_reason??a.reason),last_seen_at:Dn(a.last_seen_at),session_count:ao(a.session_count),rtt_ms:Dn(a.rtt_ms)})}const r=In(e)?e:{},o=ae(r.self_device_id),s=Qa(r.degraded);return{peers:n,...o?{self_device_id:o}:{},...s.length?{degraded:s}:{}}}function IR(e){const t=ae(e.device_id);return t?{device_id:t,name:ae(e.name),role:ae(e.role),capabilities:Qa(e.capabilities),active:Jn(e.active,!0),suspect:Jn(e.suspect,!1),endpoints:Qa(e.endpoints),last_seen_at:Dn(e.last_seen_at),reachable:Jn(e.reachable,!0),reason:ae(e.reason??e.unreachable_reason),scope:ae(e.scope)}:null}function TR(e){const t=ae(e.network_id);return t?{network_id:t,name:ae(e.name),epoch:cm(e.epoch),trust:ae(e.trust),members:Dr(e.members).map(IR).filter(n=>n!==null)}:null}function JM(e){const t=In(e)?e:{},n=ae(t.self_device_id);return{networks:Dr(t.networks).map(TR).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function CR(e){return e.live_state.trim().toLowerCase()==="busy"}function qM(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const o of Dr(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=In(o.status)?{code:ae(o.status.code),label:ae(o.status.label)}:null,l=In(o.binding)?{agent:gr(o.binding.agent),team:gr(o.binding.team)}:null,d=In(o.opened_by)?{agent:gr(o.opened_by.agent),label:gr(o.opened_by.label),session:gr(o.opened_by.session)}:null;t.push({id:s,name:ae(o.name),mtime:Dn(o.mtime)??0,locality:a,owner_device:ae(o.owner_device),owner_device_name:ae(o.owner_device_name),reachable:Jn(o.reachable,!0),unreachable_reason:ae(o.unreachable_reason),live_state:ae(o.live_state),archived:Jn(o.archived,!1),created_at:Dn(o.created_at),pinned:Jn(o.pinned,!1),...typeof o.active=="boolean"?{active:o.active}:{},waiting_on:ao(o.waiting_on),jobs_running:ao(o.jobs_running),subagents_running:ao(o.subagents_running),subagents_queued:ao(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 ej(e){const{id:t,name:n,mtime:r,...o}=e;return{...o,session_id:t,title:n,updated_at:r}}function tj(e){if(!In(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:Jn(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:Dr(e.phases).map(o=>({phase:ae(o.phase),peer:ae(o.peer),progress:typeof o.progress=="number"?o.progress:0}))}:null}const OR=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function nj(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)||_("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||OR.has(n)}}function rj(e){const t=ae(e.name);return t||_("ui.mesh.mesh_types.device_suffix",{suffix:ae(e.device_id).slice(-6)})}function PR(e){const t=ae(e.name);return t?JSON.stringify(t):_("ui.mesh.mesh_types.unnamed_device")}function MR(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 oj(e,t,n=!1){const r=n?MR(e.id,t):ae(e.id);return`${PR(e)} ${r}`}function sj(e){const t=ae(e.name);return t||_("ui.mesh.mesh_types.network_suffix",{suffix:ae(e.network_id).slice(-6)})}const jR=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function $R(e){const t=e.trim();return t!==""&&jR.includes(t)}function lm(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"||$R(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const ij=()=>_("ui.mesh.mesh_graph.identity_suspect");function dm(e){switch(e){case"self":return _("ui.mesh.mesh_drop.this_device");case"reached":return _("ui.mesh.mesh_reach.reached");case"relay-down":return _("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return _("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return _("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return _("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return _("ui.mesh.mesh_reach.not_a_member");case"unanswered":return _("ui.mesh.mesh_reach.no_answer");case"not-attempted":return _("ui.mesh.mesh_reach.not_asked");default:return _("ui.mesh.mesh_reach.unknown")}}function aj(e){const t=lm(e),n=dm(t);return e.reason?`${n} — ${e.reason}`:n}const cj={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"},lj={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function dj(e){const t=e.trim();switch(t){case"ok":return _("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return _("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return _("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return _("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return _("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?_("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function uj(e){return e.reachable?"":e.remoteRelay==="not_listening"?_("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?_("ui.mesh.mesh_reach.peer_closed_handshake"):""}function fj(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>CR(r))?"working":"idle",source:"derived"}}function DR(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 NR(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=lm({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 pj(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${_("ui.chat.canonical.transcript.reconnecting")} · ${Xa(n,t)}`:_("ui.presence.link_down_last_seen",{age:Xa(n,t)})}function Xa(e,t){if(e===null)return _("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?_("ui.presence.just_now"):n<3600?_("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?_("ui.presence.hours_ago",{count:Math.floor(n/3600)}):_("ui.presence.days_ago",{count:Math.floor(n/86400)})}function hj(e,t){if(e.link_reconnecting===!0)return _("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return _("ui.presence.link_down_compact",{age:Xa(n,t)})}function LR(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 mj(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?dm(e.peer_reach):null}function gj(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?_("ui.chat.canonical.untitled"):n==="this chat"?_("ui.chat.canonical.this_chat"):n:t==="this_chat"?_("ui.chat.canonical.this_chat"):_("ui.chat.canonical.untitled")}function Ja(e,t){return e.map((n,r)=>({id:`${t}:doc:${r}`,attachment:n.digest,filename:n.name??"Attached file",mimeType:n.mime_type??"application/octet-stream",path:n.path??null,storedPath:null,bytes:n.bytes??0}))}const hs=(e,t)=>e instanceof Pe?Pc(e,t):e instanceof Error?e.message:t,hi="session_unvalidated",FR=()=>_("ui.common.errors.session_unvalidated"),Qs="leading_slash_message",um=()=>_("ui.common.errors.leading_slash_message");function UR(e,t){return e instanceof Pe&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const fm="attachment_read_failed",pm="store_out_of_space",hm="store_unavailable";function Uu(e){return e===pm||e===hm}const BR="answer_not_sent",mm="aside_not_answered",gm="aside_still_answering";function co(e){return e===Qs||e===fm||e===pm||e===hm||e===BR||e===mm||e===gm||e===hi||e===ii}function HR(e){return e instanceof Pe&&e.status===409&&il(e)===void 0}function _m(e,t=!1){return zR(e)||HR(e)&&!t?"not_sent":e instanceof Pe&&e.status===404?"gone":"unknown"}function il(e){if(e instanceof Pe||e instanceof jn)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 _("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return _("ui.chat.canonical.send_failure.unreachable")},get busy(){return _("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return _("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return _("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return _("ui.chat.canonical.send_failure.retiring")},get notReady(){return _("ui.chat.canonical.send_failure.not_ready")},get generic(){return _("ui.chat.canonical.send_failure.generic")},get gone(){return _("ui.chat.canonical.send_failure.gone")},get sendLock(){return _("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return _("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return _("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return _("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return _("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return _("ui.chat.canonical.send_failure.late_delivery_overlap")}};function _j(e){return e?ht.gateLock:ht.sendLock}const bj=()=>_("ui.common.actions.retry"),vj=()=>_("ui.common.actions.clear");function WR(e,t,n=!1){const r=_m(e,n),o=t??il(e),s=Pc(e,ht.generic);return r==="gone"?{message:ht.gone,retry:!1,code:o}:r==="not_sent"?o===ii?{message:ht.busy,retry:!0,code:o}:o===cp?{message:ht.retiring,retry:!0,code:o}:o===hi?{message:ht.notReady,retry:!co(o),code:o}:o===mm?{message:ht.asideNotAnswered,retry:!1,code:o}:o===gm?{message:ht.asideStillAnswering,retry:!1,code:o}:o===Qs?{message:um(),retry:!1,code:o}:{message:s,retry:!1,code:o}:o===Ct.transportFailed?{message:ht.unreachable,retry:!0,code:o}:ai(o)?{message:Oc(o),retry:!1,code:o}:o===Cc?{message:ht.unconfirmed,retry:!co(o),code:o}:o===jv.runtimeUnreachable?{message:ht.unconfirmed,retry:!0,code:o}:o?{message:s,retry:!co(o),code:o}:{message:ht.unconfirmed,retry:!co(o),code:o}}function qa(e){return e.trim()}function yj(e,t){if(t.length===0)return qa(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
|
|
45
|
-
`);return
|
|
46
|
-
${e}`)}function ec(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function GR(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 wj(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,s])=>ec(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 al(e,t){return t??e??void 0}function bm(e,t,n){return e?t??void 0:n??void 0}function kj(e,t,n){return al(e,bm(e,t,n))}function zR(e){return e instanceof Pe?e.status===413||e.status===422?!0:e.code===ii||e.code===cp||e.code===Ct.noCredential||Uu(e.code):e instanceof jn&&(e.code===hi||e.code===fm||Uu(e.code))}function Vo(e,t){const n=e.startsWith("send:")?e.slice(5):null;return al(e.startsWith("draft:")?e:null,t??n)??e}function KR(e,t){const n=at.getState(),r=Vo(e,t),o=r===""||r===e?[e]:[e,r];n.settleInFlight(o),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function Sj(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=Vo(e,t.sessionId);return at.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),kt.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:ht.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!co(t.heldClaimCode),heldClaimCode:void 0}),!0}function Ej(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=Vo(e,t.sessionId);if(n){if(Lu(s,n.recordId))return!1;const c=rm(s,n.recordId);return c!=="unseen"?(c==="owner"&&kt.getState().retractUndelivered(e,n.recordId),!1):(Ka(s,{id:n.recordId,text:n.text,images:[],documents:Ja(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const a=t.admissionRequestId;return Lu(s,a)?!1:(Ka(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:Ja(t.submittedFiles??[],a)}),!0)}function Bu(e,t,n){lR(Vo(e,t),n)}function VR(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 ZR(e,t){return!!t&&e===t}const YR=3,QR=5e3,XR=2e3;async function JR(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=YR||!(n instanceof Pe)||n.code!==ii)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??XR),QR);await new Promise(o=>setTimeout(o,r))}}async function qR(e){await JR(async()=>{await Ye(e)})}async function Aj(e,t,n,r,o){const s=kt.getState();if(ZR(s.validatingSessionId,n))throw new jn(FR(),hi);const a=s.drafts[e];if(a?.pending)return null;const c=qa(t.text),l=a?.submittedText!==void 0&&VR(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,y=l&&a?a.submittedInputPath:t.inputPath,b=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),v=Date.now();s.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:b,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:h,submittedInputMode:m,submittedInputPath:y,error:void 0,errorCode:void 0,submittedAt:v});const p=al(e.startsWith("draft:")?e:null,n??d.sessionId)??null;p&&Ka(p,{id:b,submittedAt:v,text:c,images:u.map((N,O)=>({id:`${b}:${O}`,data:N.data_b64,attachment:null,mimeType:N.mime_type})),documents:Ja(f??[],b),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,sl(d.model??null,s.draftFastCarries),d.warmId,d.peer)??void 0,!k)throw new jn(kt.getState().error??_("ui.common.errors.chat_start_simple"));s.updateDraft(e,{sessionId:k}),p&&oR(p,k),s.fetchSessions()}const N=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:N}),k&&rR(k,b,N),C="sessions.message",await qR({op:"sessions.message",sessionId:k,requestId:b,text:N,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:h,inputMode:m,inputPath:y}),s.finishDraft(e,k),kt.setState({error:null}),k}catch(N){kt.setState({error:null});const O=l&&a?.admissionAttempted===!0,R=_m(N,O),g=C==="sessions.message"&&UR(N,c),w=g?Qs:il(N),S=WR(N,w,O);let I=!1;const F=k??p??void 0;if(F&&R==="unknown"&&(I=E&&rm(F,b)==="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 $=Vo(e,k??d.sessionId),ne=p&&p!==$?[p,$]:[$];throw at.getState().settleInFlight(ne),p&&p!==$&&at.getState().returnInFlight(p,$),F&&Za(F,b),e!==F&&Za(e,b),g?new Pe(422,um(),N,Qs):N}}const vm=50,Hu="activity",ex=25,tx=500;function nx(e){return e?vm:tx}function Wu(e,t){return`${e}:${t}`}function rx(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function ox(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function sx(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 ix(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 ax(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 cx(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 Gn(e,t){return{...e,...t,...ux(e,t),...fx(t,e),attention:wr(e?.attention,t.attention,t.session_id)}}const Rj=im,lx=e=>e.filter(am),Gu=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const o=e[r],s=wr(o.attention,n,t);if(s===o.attention)return e;const a=e.slice();return a[r]={...o,attention:s},a},dx=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function ux(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 fx(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 px(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 sa(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 ym(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 wm(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 km(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 hx(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 mx(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]=ym(s),r.push({key:o,sessionId:s.sessionId,payload:wm(s)}));return{drafts:n??e,restored:r}}function Sm(e){return e.map(({id:t,name:n,mtime:r,...o})=>({...o,session_id:t,title:n,updated_at:r}))}function zu(e,t){return Sm(e).filter(n=>t[n.session_id]===void 0)}function ia(e){return typeof e=="string"&&e.length>0?e:null}function gx(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 _x(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Gn(n.get(r.session_id),r)])).values()]}let aa=0,fr=null;function bx(e,t,n){const r=fr;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 fr=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 fr===o&&(fr=null),s}}finally{fr===o&&(fr=null)}})(),o.promise}function Em(){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 vx(){const e=Em();return e.kind==="session"?e.sessionId:null}function yx(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 wx(e,t){const n={...t,...e},{drafts:r,restored:o}=mx(n.drafts,n.forgotten),s=r===n.drafts?n:{...n,drafts:r};for(const l of o)km(l.key,l.sessionId,l.payload);const a=Em();if(a.kind==="session")return{...s,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...s,activeSessionId:null};const c=yx(s);return c?{...s,...c}:s}const kt=Go()(ci((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:vx(),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=nx(t().cataloguePageable),r=!1)=>{const o=++aa,s=t().answerSeq+1;e({answerSeq:s}),e({loading:!0,error:null});try{const a=await bx(n,r,(l,d)=>Ye({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:Hu}:{}}));if(o!==aa)return;const c=Sm(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,y=c.filter(g=>m[g.session_id]===void 0);let b=null;for(const g of y){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&&(b??={...l.placementFacts},b[g.session_id]={locality:S,owner_device:typeof g.owner_device=="string"?g.owner_device:"",at:l.answerSeq+1})}const v=ia(a.next_cursor),p=v===null&&a.truncated!==!0,E=y.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=ax({sessions:l.sessions,scopeIds:rx(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...ox(l.placementFacts)],tailIds:p?[]:l.head.tailIds,page:y,merge:_x});let N=C.rows;for(const g of k){const w=l.pinFacts[g.session_id],S=N.findIndex(I=>I.session_id===g.session_id);S===-1?N=[...N,{...g,pinned:w.pinned}]:N[S]={...N[S],pinned:w.pinned}}const O=px(l.archiveFacts,s),R=gx(a.counts);return{sessions:N,pinFacts:d,archiveFacts:O,...b===null?{}:{placementFacts:b,answerSeq:l.answerSeq+1},forgotten:m,loading:!1,truncated:a.truncated===!0,head:{pageIds:E,tailIds:C.tailIds,nextCursor:v,tailCursor:p?null:l.head.tailStarted?l.head.tailCursor:v,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===aa&&e({loading:!1,error:hs(a,_("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:vm,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:Hu}:{}}),s=zu(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]=Gn(l[h],f)}const u=ia(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:hs(o,_("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,o=null,s=ex)=>{const a=Wu(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=zu(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=cx({sessions:u.sessions,previousIds:h?f.ids:[],page:d,merge:Gn}),y=ia(l.next_cursor);return{sessions:m.rows,scopes:{...u.scopes,[a]:{ids:m.ids,nextCursor:y,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[a];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[a]:{...u,loading:!1,error:hs(l,_("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const o=Wu(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=>sa(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=>sa(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:s==="session_delete_refused",detail:r instanceof Pe&&r.message?r.message:_("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:hs(l,_("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,...sa(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:dx(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=Gu(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=Gu(o,a.slice(8),s))}return o===r.sessions?r:{...r,sessions:o}})},markAllRead:async()=>{const n=lx(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=sx(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(y=>y.session_id===n);let d=!1;const u=c.sessions.map(y=>{if(y.status_epoch===void 0&&y.status_revision===void 0||y.status_epoch===s)return y;d=!0;const{status_revision:b,status_epoch:v,...p}=y;return p});if(l<0)return d?{...c,sessions:u}:c;const f=u[l],m=!(a!==void 0&&Object.keys(a).some(y=>f[y]!==a[y]))&&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=bm(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 hx(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=sl(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=>{KR(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=wm(r);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:ym(c)}}}),km(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];fs(n),s&&s!==n&&fs(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);fs(u),h&&h!==u&&fs(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])=>ec(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&&Bu(S,I.sessionId,F)}}const d=Object.entries(l).find(([,S])=>ec(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&&!GR(r,f,s.placementFacts[n],s.sessions.find(S=>S.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:y,submittedText:b,submittedAttachments:v,submittedImages:p,submittedMode:E,submittedInputMode:k,submittedInputPath:C,heldClaimCode:N,error:O,errorCode:R,errorRetry:g,...w}=f;return m||Za(n,h),{drafts:{...l,[u]:{...w,...m?{}:{undelivered:{recordId:h,text:b??"",attachments:v??[]}},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}}}),Bu(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(y=>{const b=y.pinFacts[n];return b===void 0||b.at!==d?{}:(m=!0,{sessions:y.sessions.map(v=>v.session_id===n?{...v,pinned:h.pinned===!0}:v),pinFacts:{...y.pinFacts,[n]:{...b,pinned:h.pinned===!0}}})}),m}catch(h){return e(m=>{const y=m.pinFacts[n];if(y!==void 0&&y.at!==d)return{};const b={...m.pinFacts};return a===null&&s===void 0?delete b[n]:b[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:m.sessions.map(v=>v.session_id===n?{...v,pinned:c}:v),pinFacts:b,pinFailure:{sessionId:n,pinned:r,title:s?.title||"",detail:Pc(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?Gn(s,n):s):[...r.sessions,n]})),settlePlacement:(n,r)=>{const o=t().beginAnswer();e(s=>({sessions:s.sessions.map(a=>a.session_id===n?Gn(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:LR(a.peerDeviceFacts,o,a.peerDeviceSnapshotAt,s),y=m?.facts??DR(a.peerDeviceFacts,Object.fromEntries(Object.entries(o).filter(([,g])=>g.at>a.peerDeviceSnapshotAt))),b=l.filter(g=>g.locality==="remote");let v=a.sessions,p=!1;const E=[],k=new Map;for(let g=0;g<v.length;g+=1)k.set(v[g].session_id,g);for(const g of b){const w=k.get(g.session_id);if(w===void 0){E.push(g);continue}v[w]!==g&&(p||(v=v.slice(),p=!0),v[w]=Gn(v[w],g))}E.length>0&&(v=[...v,...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||v[w]===g||(p||(v=v.slice(),p=!0),v[w]=Gn(v[w],g))}const C=new Set(l.map(g=>g.session_id)),N=new Set;for(const g of l)g.locality==="remote"&&typeof g.owner_device=="string"&&g.owner_device!==""&&g.reachable!==!1&&N.add(g.owner_device);const O=new Set;for(const g of v){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||y[w.owner_device]?.reachable!==!1&&(w.owner_device===""||!N.has(w.owner_device)||(O.add(g),delete d[g])));O.size>0&&(v=v.filter(g=>!O.has(g.session_id)));const R=v.map(g=>NR(g,y));return R.some((g,w)=>g!==v[w])&&(v=R,p=!0),!f&&E.length===0&&!p&&O.size===0&&Object.keys(o).length===0&&s===void 0?{}:{sessions:v,placementFacts:d,peerDeviceFacts:y,peerDeviceSnapshotAt:m?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:wx,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 xj(e,t){return t?e.filter(n=>n.archived!==!0):e}function Ij(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 Tj(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function Cj(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const Oj="This backend cannot archive conversations. Update the backend and try again.",Pj="This conversation is already archived. Use /unarchive to restore it.",Mj="This conversation is not archived, so there is nothing to restore.",jj="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 $j(e,t,n){return n&&e&&t.trim().length>0}function Dj(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],[y,b]=[Math.hypot(h,o),Math.hypot(m,c)],v=(T,V)=>{if(T===0&&V===0)return 0;const Z=Math.atan2(T,V)*d;return Z<0?Z+360:Z},[p,E]=[v(o,h),v(c,m)],k=s-n,C=b-y;let N=0;y*b!==0&&(N=E-p,N>180?N-=360:N<-180&&(N+=360));const O=2*Math.sqrt(y*b)*Math.sin(N*l/2),R=(n+s)/2,g=(y+b)/2;let w;y*b===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/$))},Xs=([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,Ku=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]=[Ku(e),Ku(t)].sort((o,s)=>s-o);return(n+.05)/(r+.05)},kx=/^#[0-9a-fA-F]{3,8}$/,W=e=>typeof e=="string"&&kx.test(e),Vu=(e,t,n)=>{const r=f=>{const h=f.replace("#","").trim(),m=h.length===3?h.split("").map(y=>y+y).join(""):h;return[0,2,4].map(y=>Number.parseInt(m.slice(y,y+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("")}`},hn={"under-window":{dark:81,light:199},menu:{dark:102,light:171},popover:{dark:122,light:143}},cl=["canvas","surface","elevated"],mi=["ink","inkMuted","inkDim"],Zo=4.5,Sx=3,Ex=1.5,Am=["danger","success","warning","info"],Rm={hover:.05,selected:.08,field:.05,work:.08},xm=4,Ax=1.5,ll=.96,Rx=["sunken","surface"],Im=3.5,tc=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},Nr=(e,t)=>{const[n,r]=[tc(e),tc(t)].sort((o,s)=>s-o);return(n+.05)/(r+.05)},Zu=(e,t)=>Number.parseInt(e.slice(1+t*2,3+t*2),16),Nn=e=>`#${e.toString(16).padStart(2,"0").repeat(3)}`,st=(e,t,n)=>`#${[0,1,2].map(r=>Math.round(Zu(e,r)*t+Zu(n,r)*(1-t)).toString(16).padStart(2,"0")).join("")}`,Pt=e=>tc(e.canvas)<.18?"dark":"light",Tm=(e,t,n,r,o=Zo)=>{for(let s=.2;s<=1.0001;s+=.01)if(Nr(e[n],st(e[t],s,r))>=o)return Math.round(s*100)/100;return 1},dl=(e,t,n,r,o)=>{for(let s=.2;s<=1.0001;s+=.01){const a=st(e[t],s,r);if(Nr(e[n],st(e.ink,o,a))>=(n==="inkDim"?Im:Zo))return Math.round(s*100)/100}return 1},xx=(e,t)=>st(e.ink,t,e.borderControl);function Ix(e,t){const n={};for(const r of["dark","light"]){let o=0;for(const s of Object.keys(hn))for(const{palette:a}of t){if(Pt(a)!==r)continue;const c=st(a.canvas,e[s][r].canvas,Nn(hn[s][r]));let l=.01;for(;l<1&&de(st(a.ink,l,c),c)<xm;)l=Math.round((l+.01)*100)/100;o=Math.max(o,l)}n[r]=Math.round(o*100)/100}return n}function Tx(e,t=Rm){const n={};for(const[r,o]of Object.entries(hn)){n[r]={};for(const s of["dark","light"]){n[r][s]={};for(const a of cl){let c=0;for(const{palette:l}of e)if(Pt(l)===s)for(const d of mi)c=Math.max(c,Tm(l,a,d,Nn(o[s])),...Object.values(t).map(u=>dl(l,a,d,Nn(o[s]),u)));n[r][s][a]=Math.min(1,Math.round((c+.02)*100)/100)}}}return n}function Cx(e){const t={};for(const n of["dark","light"]){let r=0;for(const{palette:o}of e){if(Pt(o)!==n)continue;const s=n==="dark"?"#ffffff":"#000000";for(const a of mi)r=Math.max(r,Tm(o,"elevated",a,s,a==="inkDim"?Im:Zo))}t[n]=Math.round(r*100)/100}return t}function Cm(e,t){let n=1;for(const r of Object.keys(e))n=Math.min(n,e[r][t]?.canvas??1);return n}function Om(e,t,n,r){const o=r==="dark"?"#ffffff":"#000000";return st(e.elevated,t,st(e.canvas,Cm(n,r),o))}function Ox(e,t){const n={};for(const r of["dark","light"]){const o=Cm(t,r),s=r==="dark"?"#ffffff":"#000000";let a=0;for(const{palette:c}of e){if(Pt(c)!==r)continue;const l=st(c.canvas,o,s);for(const d of["inkMuted","ink"]){let u=.2;for(;u<=1.0001&&!(Nr(c[d],st(c.elevated,u,l))>=Zo);u+=.01);a=Math.max(a,Math.round(Math.min(u,1)*100)/100)}}n[r]=Math.round(a*100)/100}return n}function Px(e,t,n){const r={};for(const o of["dark","light"]){let s=0;for(const{palette:a}of e){if(Pt(a)!==o)continue;const c=Om(a,n[o],t,o);for(const l of Am){let d=0;for(;d<=1.0001&&!(Nr(st(a.ink,d,a[l]),c)>=Zo);d+=.05);s=Math.max(s,Math.round(Math.min(d,1)*100)/100)}}r[o]=Math.round(s*100)/100}return r}function Mx(e,t,n){const r={};for(const o of["dark","light"]){const s=n[o],a=Math.max(ll,s),c=[Math.round((a-.8*(a-s))*100)/100,s];let l=0;for(const{palette:d}of e)if(Pt(d)===o)for(const u of c){const f=Om(d,u,t,o);let h=0;for(;h<=1.0001&&!(Nr(st(d.ink,h,d.hairline),f)>=Ex);h+=.05);l=Math.max(l,Math.round(Math.min(h,1)*100)/100)}r[o]=Math.round(l*100)/100}return r}function jx(e,t){const n={};for(const[r,o]of Object.entries(hn)){n[r]={};for(const s of["dark","light"]){let a=0;for(const{palette:c}of t)if(Pt(c)===s)for(const l of cl){const d=st(c[l],e[r][s][l],Nn(o[s]));let u=0;for(;u<1&&Nr(xx(c,u),d)<Sx;)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 Qr=new Map;function $x(e){const t=Pt(e),n=r=>Object.values(hn).every(o=>cl.every(s=>mi.every(a=>dl(e,s,a,Nn(o[t]),r)<=.95)));return Object.fromEntries(Object.entries(Rm).map(([r,o])=>{let s=o;for(;s>.01&&!n(s);)s=Math.round((s-.01)*100)/100;return[r,s]}))}function Dx(e,t){const n=Pt(e);let r=Ix(t,[{palette:e}])[n];const o=()=>Object.entries(hn).every(([s,a])=>Array.from({length:101},(c,l)=>{const d=t[s][n].canvas,u=Math.max(ll,d),f=Math.round((u-l/100*(u-d))*100)/100,h=st(e.canvas,f,Nn(a[n]));return de(st(e.ink,r,h),h)>=xm}).every(Boolean));for(;r<1&&!o();)r=Math.round((r+.01)*100)/100;return{dark:0,light:0,[n]:r}}function Nx(e,t){const n=Pt(e);for(const r of Rx)for(let o=5;o<=104;o++){const s=o/100;if(Object.entries(hn).every(([c,l])=>Array.from({length:101},(d,u)=>{const f=t[c][n].canvas,h=Math.max(ll,f),m=Math.round((h-u/100*(h-f))*100)/100,y=Math.round(m*s*100)/100;if(y>1)return!1;const b=st(e.canvas,m,Nn(l[n]));return de(st(e[r],y,b),b)>=Ax}).every(Boolean)))return{dark:{role:r,scale:s},light:{role:r,scale:s}}}return null}function Lx(e,t){const n=Pt(e);for(;;){const r=Dx(e,t);let o=!1;for(const[s,a]of Object.entries(hn)){const c=Math.min(1,Math.round((Math.max(...mi.map(l=>dl(e,"canvas",l,Nn(a[n]),r[n])))+.02)*100)/100);c>t[s][n].canvas&&(t[s][n].canvas=c,o=!0)}if(!o)return r}}const Fx=["canvas","surface","elevated","sunken","ink","inkMuted","inkDim","borderControl","hairline",...Am];function Ux(e){for(const t of Fx){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 Nj(e){Ux(e);const t=JSON.stringify(e),n=Qr.get(t);if(n)return n;const r=[{palette:e}],o=$x(e),s=Tx(r,o);let a,c;for(let u=0;u<=99;u++){let f=!1;for(const h of Object.keys(hn)){const m=Pt(e),y=s[h][m].canvas,b=Math.max(y,u/100);f||=b!==y,s[h][m].canvas=b}if(!(u>0&&!f)&&(a=Lx(e,s),c=Nx(e,s),c))break}if(!c)throw new Error("palette roles cannot form a readable transparent lane");const l=Ox(r,s),d={alphaFloor:s,blockVeil:a,laneWash:c,controlMix:jx(s,r),bandFloor:Cx(r),overlayFloor:l,overlayInkMix:Px(r,s,l),overlayEdgeMix:Mx(r,s,l),stateAlpha:o};return Qr.set(t,d),Qr.size>8&&Qr.delete(Qr.keys().next().value),d}const nc=new WeakMap,Bx=(e,t)=>{t?nc.set(e,t):nc.delete(e)},Lj=e=>nc.get(e);/**
|
|
44
|
+
${e}`}const ca={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function Is(e,t,n){const r=[...e.attachments??[]],o=[],s=[],a=new Set;for(const h of t.attachments){const m=r.find(b=>b.path===h&&!a.has(b.id));if(m){a.add(m.id),s.push(m.id);continue}const y={id:n(),path:h};o.push(y),s.push(y.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:gi(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 TR(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 CR(e){return{text:gi(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function OR(e,t){if(!e||!t)return!1;const n=CR(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 PR(e,t=()=>crypto.randomUUID()){const n={};for(const[r,o]of Object.entries(e??{}))n[r]=o.inFlight?Is(o,o.inFlight,t):o;return n}function MR(e,t){const n=t.text,r=gi(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 jR=300,pm="conversation-input-store";let Fo=null,hm=pm,wt=null,la=!1;const nc=()=>{try{return globalThis.localStorage??null}catch{return null}},_o=()=>{wt!==null&&(clearTimeout(wt),wt=null);const e=Fo;if(!e)return;const t=hm,n=nc();if(n){try{n.setItem(t,JSON.stringify(e))}catch(r){la||(la=!0,console.warn("[composer] the draft could not be persisted; it stays in memory for this session",r));return}Fo=null,la=!1}},oj=()=>{_o()},sj=()=>{Fo=null,wt!==null&&(clearTimeout(wt),wt=null)},$R={getItem:e=>{const t=nc();if(!t)return null;const n=t.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}},setItem:(e,t)=>{Fo=t,hm=e,wt!==null&&clearTimeout(wt),wt=setTimeout(()=>{wt=null,_o()},jR)},removeItem:e=>{Fo=null,wt!==null&&(clearTimeout(wt),wt=null),nc()?.removeItem(e)}};typeof window<"u"&&typeof window.addEventListener=="function"&&(window.addEventListener("pagehide",_o),window.addEventListener("beforeunload",_o),window.document?.addEventListener("visibilitychange",()=>{window.document.visibilityState==="hidden"&&_o()}));const at=Vo()(ui((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"&&!TR(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&&(r.currentHistoryIndex??null)!==null&&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]??ca,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]??ca;n!==r&&s&&(c=Is(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=Is(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=gi(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]??ca;o.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:Is(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?OR(r,r.returned):o(r),c=r.returned?MR(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:pm,storage:$R,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:PR(e?.inputByConversation)})}));function mm(e){if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null}function ij(e,t){return t?e.filter(n=>n.session_id===t&&gm(n)).length:0}function gm(e){if(mm(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function DR(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function aj(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 cj={cwd:""};function NR(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,DR(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function LR(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 lj(e,t){const n=e.trim();if(!n)return{checked:!0,rung:null,confirmation:o=>_("ui.chat.session_readout.draft.confirm_model",{selector:o})};if(!t.ladderKnown)return{checked:!1,rung:null,refusal:_("ui.chat.session_readout.draft.refusal_ladder_unread")};const r=t.ladder.find(o=>o.trim().toLowerCase()===n.toLowerCase());return r?{checked:!0,rung:r,confirmation:o=>_("ui.chat.session_readout.draft.confirm_model_effort",{selector:o,effort:hs(r)})}:{checked:!0,rung:null,confirmation:o=>t.level?_("ui.chat.session_readout.draft.confirm_effort_changed",{selector:o,level:hs(t.level),wanted:hs(n)}):_("ui.chat.session_readout.draft.confirm_effort_unset",{selector:o,wanted:hs(n)})}}function dj(e,t){return e!==!0?null:t==="on"?_("ui.chat.fast_mode.stays_on"):t==="off"?_("ui.chat.fast_mode.turned_off"):_("ui.chat.fast_mode.unsupported_stays_off")}const uj=()=>_("ui.chat.fast_mode.service_cannot_carry"),fj="fast_unavailable";function fl(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function pj(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function hj(e){const t=e instanceof Pe?e:null;return t?.code==="fast_mode_unsupported"?_("ui.chat.fast_mode.pick_unsupported"):t?.status===422?_("ui.chat.fast_mode.service_unavailable"):_("ui.chat.fast_mode.not_changed")}function mj(e,t){const n={...e,model:fl(e.model,t)};return{queryKey:NR(n),queryFn:()=>LR(n),placeholderData:Vg,staleTime:3e4,retry:!1}}function ae(e){return typeof e=="string"?e.trim():""}function vr(e){const t=ae(e);return t||null}function Ln(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function uo(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function _m(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function tr(e,t){return typeof e=="boolean"?e:t}function rc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Fr(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 Fr(t)}return[]}function FR(e){if(!Cn(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:_m(e.attempts),last_frame_at:Ln(e.last_frame_at),next_retry_at:Ln(e.next_retry_at),last_error:ae(e.last_error)}}function Cn(e){return typeof e=="object"&&e!==null}const UR=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function BR(e,t){const n=ae(e);return UR.includes(n)?n:t?"reachable":"unreachable_legacy"}const HR=["running","not_listening","unknown"];function WR(e){const t=ae(e);return HR.includes(t)?t:void 0}function GR(e){if(Array.isArray(e))return e.filter(Cn).map(t=>({endpoint:ae(t.endpoint),connected:t.connected===!0,detail:ae(t.detail),latency_ms:Ln(t.latency_ms)})).filter(t=>t.endpoint!=="")}function gj(e){const t=new Set,n=[];for(const a of Fr(e)){const c=ae(a.device_id);if(!c||t.has(c)||typeof a.reachable!="boolean")continue;t.add(c);const l=WR(a.remote_relay),d=GR(a.attempts),u=a.reachable?void 0:FR(a.redial);n.push({device_id:c,name:ae(a.name),reachable:a.reachable,link_state:BR(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:vr(a.unreachable_reason??a.reason),last_seen_at:Ln(a.last_seen_at),session_count:uo(a.session_count),rtt_ms:Ln(a.rtt_ms)})}const r=Cn(e)?e:{},o=ae(r.self_device_id),s=rc(r.degraded);return{peers:n,...o?{self_device_id:o}:{},...s.length?{degraded:s}:{}}}function zR(e){const t=ae(e.device_id);return t?{device_id:t,name:ae(e.name),role:ae(e.role),capabilities:rc(e.capabilities),active:tr(e.active,!0),suspect:tr(e.suspect,!1),endpoints:rc(e.endpoints),last_seen_at:Ln(e.last_seen_at),reachable:tr(e.reachable,!0),reason:ae(e.reason??e.unreachable_reason),scope:ae(e.scope)}:null}function KR(e){const t=ae(e.network_id);return t?{network_id:t,name:ae(e.name),epoch:_m(e.epoch),trust:ae(e.trust),members:Fr(e.members).map(zR).filter(n=>n!==null)}:null}function _j(e){const t=Cn(e)?e:{},n=ae(t.self_device_id);return{networks:Fr(t.networks).map(KR).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function VR(e){return e.live_state.trim().toLowerCase()==="busy"}function bj(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const o of Fr(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=Cn(o.status)?{code:ae(o.status.code),label:ae(o.status.label)}:null,l=Cn(o.binding)?{agent:vr(o.binding.agent),team:vr(o.binding.team)}:null,d=Cn(o.opened_by)?{agent:vr(o.opened_by.agent),label:vr(o.opened_by.label),session:vr(o.opened_by.session)}:null;t.push({id:s,name:ae(o.name),mtime:Ln(o.mtime)??0,locality:a,owner_device:ae(o.owner_device),owner_device_name:ae(o.owner_device_name),reachable:tr(o.reachable,!0),unreachable_reason:ae(o.unreachable_reason),live_state:ae(o.live_state),archived:tr(o.archived,!1),created_at:Ln(o.created_at),pinned:tr(o.pinned,!1),...typeof o.active=="boolean"?{active:o.active}:{},waiting_on:uo(o.waiting_on),jobs_running:uo(o.jobs_running),subagents_running:uo(o.subagents_running),subagents_queued:uo(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 vj(e){const{id:t,name:n,mtime:r,...o}=e;return{...o,session_id:t,title:n,updated_at:r}}function yj(e){if(!Cn(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:tr(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:Fr(e.phases).map(o=>({phase:ae(o.phase),peer:ae(o.peer),progress:typeof o.progress=="number"?o.progress:0}))}:null}const ZR=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function wj(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)||_("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||ZR.has(n)}}function kj(e){const t=ae(e.name);return t||_("ui.mesh.mesh_types.device_suffix",{suffix:ae(e.device_id).slice(-6)})}function YR(e){const t=ae(e.name);return t?JSON.stringify(t):_("ui.mesh.mesh_types.unnamed_device")}function JR(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 Sj(e,t,n=!1){const r=n?JR(e.id,t):ae(e.id);return`${YR(e)} ${r}`}function Ej(e){const t=ae(e.name);return t||_("ui.mesh.mesh_types.network_suffix",{suffix:ae(e.network_id).slice(-6)})}const XR=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function QR(e){const t=e.trim();return t!==""&&XR.includes(t)}function bm(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"||QR(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const Aj=()=>_("ui.mesh.mesh_graph.identity_suspect");function vm(e){switch(e){case"self":return _("ui.mesh.mesh_drop.this_device");case"reached":return _("ui.mesh.mesh_reach.reached");case"relay-down":return _("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return _("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return _("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return _("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return _("ui.mesh.mesh_reach.not_a_member");case"unanswered":return _("ui.mesh.mesh_reach.no_answer");case"not-attempted":return _("ui.mesh.mesh_reach.not_asked");default:return _("ui.mesh.mesh_reach.unknown")}}function Rj(e){const t=bm(e),n=vm(t);return e.reason?`${n} — ${e.reason}`:n}const xj={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"},Ij={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function Tj(e){const t=e.trim();switch(t){case"ok":return _("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return _("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return _("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return _("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return _("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?_("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function Cj(e){return e.reachable?"":e.remoteRelay==="not_listening"?_("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?_("ui.mesh.mesh_reach.peer_closed_handshake"):""}function Oj(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>VR(r))?"working":"idle",source:"derived"}}function qR(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 ex(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=bm({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 Pj(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${_("ui.chat.canonical.transcript.reconnecting")} · ${oc(n,t)}`:_("ui.presence.link_down_last_seen",{age:oc(n,t)})}function oc(e,t){if(e===null)return _("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?_("ui.presence.just_now"):n<3600?_("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?_("ui.presence.hours_ago",{count:Math.floor(n/3600)}):_("ui.presence.days_ago",{count:Math.floor(n/86400)})}function Mj(e,t){if(e.link_reconnecting===!0)return _("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return _("ui.presence.link_down_compact",{age:oc(n,t)})}function tx(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 jj(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?vm(e.peer_reach):null}function $j(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?_("ui.chat.canonical.untitled"):n==="this chat"?_("ui.chat.canonical.this_chat"):n:t==="this_chat"?_("ui.chat.canonical.this_chat"):_("ui.chat.canonical.untitled")}function sc(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 _s=(e,t)=>e instanceof Pe?Fc(e,t):e instanceof Error?e.message:t,_i="session_unvalidated",nx=()=>_("ui.common.errors.session_unvalidated"),qs="leading_slash_message",ym=()=>_("ui.common.errors.leading_slash_message");function rx(e,t){return e instanceof Pe&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const wm="attachment_read_failed",km="store_out_of_space",Sm="store_unavailable";function Vu(e){return e===km||e===Sm}const ox="answer_not_sent",Em="aside_not_answered",Am="aside_still_answering";function fo(e){return e===qs||e===wm||e===km||e===Sm||e===ox||e===Em||e===Am||e===_i||e===li}function sx(e){return e instanceof Pe&&e.status===409&&pl(e)===void 0}function Rm(e,t=!1){return cx(e)||sx(e)&&!t?"not_sent":e instanceof Pe&&e.status===404?"gone":"unknown"}function pl(e){if(e instanceof Pe||e instanceof Dn)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 _("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return _("ui.chat.canonical.send_failure.unreachable")},get busy(){return _("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return _("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return _("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return _("ui.chat.canonical.send_failure.retiring")},get notReady(){return _("ui.chat.canonical.send_failure.not_ready")},get generic(){return _("ui.chat.canonical.send_failure.generic")},get gone(){return _("ui.chat.canonical.send_failure.gone")},get sendLock(){return _("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return _("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return _("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return _("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return _("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return _("ui.chat.canonical.send_failure.late_delivery_overlap")}};function Dj(e){return e?ht.gateLock:ht.sendLock}const Nj=()=>_("ui.common.actions.retry"),Lj=()=>_("ui.common.actions.clear");function ix(e,t,n=!1){const r=Rm(e,n),o=t??pl(e),s=Fc(e,ht.generic);return r==="gone"?{message:ht.gone,retry:!1,code:o}:r==="not_sent"?o===li?{message:ht.busy,retry:!0,code:o}:o===mp?{message:ht.retiring,retry:!0,code:o}:o===_i?{message:ht.notReady,retry:!fo(o),code:o}:o===Em?{message:ht.asideNotAnswered,retry:!1,code:o}:o===Am?{message:ht.asideStillAnswering,retry:!1,code:o}:o===qs?{message:ym(),retry:!1,code:o}:{message:s,retry:!1,code:o}:o===Ct.transportFailed?{message:ht.unreachable,retry:!0,code:o}:di(o)?{message:Lc(o),retry:!1,code:o}:o===Nc?{message:ht.unconfirmed,retry:!fo(o),code:o}:o===Wv.runtimeUnreachable?{message:ht.unconfirmed,retry:!0,code:o}:o?{message:s,retry:!fo(o),code:o}:{message:ht.unconfirmed,retry:!fo(o),code:o}}function ic(e){return e.trim()}function Fj(e,t){if(t.length===0)return ic(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
|
|
45
|
+
`);return ic(`${n}
|
|
46
|
+
${e}`)}function ac(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function ax(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 Uj(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,s])=>ac(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 hl(e,t){return t??e??void 0}function xm(e,t,n){return e?t??void 0:n??void 0}function Bj(e,t,n){return hl(e,xm(e,t,n))}function cx(e){return e instanceof Pe?e.status===413||e.status===422?!0:e.code===li||e.code===mp||e.code===Ct.noCredential||Vu(e.code):e instanceof Dn&&(e.code===_i||e.code===wm||Vu(e.code))}function Jo(e,t){const n=e.startsWith("send:")?e.slice(5):null;return hl(e.startsWith("draft:")?e:null,t??n)??e}function lx(e,t){const n=at.getState(),r=Jo(e,t),o=r===""||r===e?[e]:[e,r];n.settleInFlight(o),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function Hj(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=Jo(e,t.sessionId);return at.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),kt.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:ht.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!fo(t.heldClaimCode),heldClaimCode:void 0}),!0}function Wj(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=Jo(e,t.sessionId);if(n){if(zu(s,n.recordId))return!1;const c=fm(s,n.recordId);return c!=="unseen"?(c==="owner"&&kt.getState().retractUndelivered(e,n.recordId),!1):(qa(s,{id:n.recordId,text:n.text,images:[],documents:sc(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const a=t.admissionRequestId;return zu(s,a)?!1:(qa(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:sc(t.submittedFiles??[],a)}),!0)}function Zu(e,t,n){RR(Jo(e,t),n)}function dx(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 ux(e,t){return!!t&&e===t}const fx=3,px=5e3,hx=2e3;async function mx(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=fx||!(n instanceof Pe)||n.code!==li)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??hx),px);await new Promise(o=>setTimeout(o,r))}}async function gx(e){await mx(async()=>{await Ye(e)})}async function Gj(e,t,n,r,o){const s=kt.getState();if(ux(s.validatingSessionId,n))throw new Dn(nx(),_i);const a=s.drafts[e];if(a?.pending)return null;const c=ic(t.text),l=a?.submittedText!==void 0&&dx(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,y=l&&a?a.submittedInputPath:t.inputPath,b=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),v=Date.now();s.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:b,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:h,submittedInputMode:m,submittedInputPath:y,error:void 0,errorCode:void 0,submittedAt:v});const p=hl(e.startsWith("draft:")?e:null,n??d.sessionId)??null;p&&qa(p,{id:b,submittedAt:v,text:c,images:u.map((N,O)=>({id:`${b}:${O}`,data:N.data_b64,attachment:null,mimeType:N.mime_type})),documents:sc(f??[],b),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,fl(d.model??null,s.draftFastCarries),d.warmId,d.peer)??void 0,!k)throw new Dn(kt.getState().error??_("ui.common.errors.chat_start_simple"));s.updateDraft(e,{sessionId:k}),p&&wR(p,k),s.fetchSessions()}const N=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:N}),k&&yR(k,b,N),C="sessions.message",await gx({op:"sessions.message",sessionId:k,requestId:b,text:N,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:h,inputMode:m,inputPath:y}),s.finishDraft(e,k),kt.setState({error:null}),k}catch(N){kt.setState({error:null});const O=l&&a?.admissionAttempted===!0,R=Rm(N,O),g=C==="sessions.message"&&rx(N,c),w=g?qs:pl(N),S=ix(N,w,O);let I=!1;const F=k??p??void 0;if(F&&R==="unknown"&&(I=E&&fm(F,b)==="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 $=Jo(e,k??d.sessionId),ne=p&&p!==$?[p,$]:[$];throw at.getState().settleInFlight(ne),p&&p!==$&&at.getState().returnInFlight(p,$),F&&tc(F,b),e!==F&&tc(e,b),g?new Pe(422,ym(),N,qs):N}}const Im=50,Yu="activity",_x=25,bx=500;function vx(e){return e?Im:bx}function Ju(e,t){return`${e}:${t}`}function yx(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function wx(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function kx(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 Sx(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 Ex(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 Ax(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 Kn(e,t){return{...e,...t,...Ix(e,t),...Tx(t,e),attention:Er(e?.attention,t.attention,t.session_id)}}const zj=mm,Rx=e=>e.filter(gm),Xu=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const o=e[r],s=Er(o.attention,n,t);if(s===o.attention)return e;const a=e.slice();return a[r]={...o,attention:s},a},xx=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function Ix(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 Tx(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 Cx(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 da(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 Cm(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 Om(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 Ox(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 Px(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:Cm(s)}));return{drafts:n??e,restored:r}}function Pm(e){return e.map(({id:t,name:n,mtime:r,...o})=>({...o,session_id:t,title:n,updated_at:r}))}function Qu(e,t){return Pm(e).filter(n=>t[n.session_id]===void 0)}function ua(e){return typeof e=="string"&&e.length>0?e:null}function Mx(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 jx(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Kn(n.get(r.session_id),r)])).values()]}let fa=0,mr=null;function $x(e,t,n){const r=mr;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 mr=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 mr===o&&(mr=null),s}}finally{mr===o&&(mr=null)}})(),o.promise}function Mm(){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 Dx(){const e=Mm();return e.kind==="session"?e.sessionId:null}function Nx(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 Lx(e,t){const n={...t,...e},{drafts:r,restored:o}=Px(n.drafts,n.forgotten),s=r===n.drafts?n:{...n,drafts:r};for(const l of o)Om(l.key,l.sessionId,l.payload);const a=Mm();if(a.kind==="session")return{...s,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...s,activeSessionId:null};const c=Nx(s);return c?{...s,...c}:s}const kt=Vo()(ui((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:Dx(),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=vx(t().cataloguePageable),r=!1)=>{const o=++fa,s=t().answerSeq+1;e({answerSeq:s}),e({loading:!0,error:null});try{const a=await $x(n,r,(l,d)=>Ye({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:Yu}:{}}));if(o!==fa)return;const c=Pm(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,y=c.filter(g=>m[g.session_id]===void 0);let b=null;for(const g of y){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&&(b??={...l.placementFacts},b[g.session_id]={locality:S,owner_device:typeof g.owner_device=="string"?g.owner_device:"",at:l.answerSeq+1})}const v=ua(a.next_cursor),p=v===null&&a.truncated!==!0,E=y.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=Ex({sessions:l.sessions,scopeIds:yx(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...wx(l.placementFacts)],tailIds:p?[]:l.head.tailIds,page:y,merge:jx});let N=C.rows;for(const g of k){const w=l.pinFacts[g.session_id],S=N.findIndex(I=>I.session_id===g.session_id);S===-1?N=[...N,{...g,pinned:w.pinned}]:N[S]={...N[S],pinned:w.pinned}}const O=Cx(l.archiveFacts,s),R=Mx(a.counts);return{sessions:N,pinFacts:d,archiveFacts:O,...b===null?{}:{placementFacts:b,answerSeq:l.answerSeq+1},forgotten:m,loading:!1,truncated:a.truncated===!0,head:{pageIds:E,tailIds:C.tailIds,nextCursor:v,tailCursor:p?null:l.head.tailStarted?l.head.tailCursor:v,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===fa&&e({loading:!1,error:_s(a,_("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:Im,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:Yu}:{}}),s=Qu(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]=Kn(l[h],f)}const u=ua(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:_s(o,_("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,o=null,s=_x)=>{const a=Ju(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=Qu(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=Ax({sessions:u.sessions,previousIds:h?f.ids:[],page:d,merge:Kn}),y=ua(l.next_cursor);return{sessions:m.rows,scopes:{...u.scopes,[a]:{ids:m.ids,nextCursor:y,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[a];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[a]:{...u,loading:!1,error:_s(l,_("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const o=Ju(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=>da(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=>da(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:s==="session_delete_refused",detail:r instanceof Pe&&r.message?r.message:_("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:_s(l,_("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,...da(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:xx(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=Rx(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=kx(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(y=>y.session_id===n);let d=!1;const u=c.sessions.map(y=>{if(y.status_epoch===void 0&&y.status_revision===void 0||y.status_epoch===s)return y;d=!0;const{status_revision:b,status_epoch:v,...p}=y;return p});if(l<0)return d?{...c,sessions:u}:c;const f=u[l],m=!(a!==void 0&&Object.keys(a).some(y=>f[y]!==a[y]))&&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=xm(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 Ox(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=fl(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=>{lx(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=Cm(r);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:Tm(c)}}}),Om(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];ms(n),s&&s!==n&&ms(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);ms(u),h&&h!==u&&ms(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])=>ac(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&&Zu(S,I.sessionId,F)}}const d=Object.entries(l).find(([,S])=>ac(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&&!ax(r,f,s.placementFacts[n],s.sessions.find(S=>S.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:y,submittedText:b,submittedAttachments:v,submittedImages:p,submittedMode:E,submittedInputMode:k,submittedInputPath:C,heldClaimCode:N,error:O,errorCode:R,errorRetry:g,...w}=f;return m||tc(n,h),{drafts:{...l,[u]:{...w,...m?{}:{undelivered:{recordId:h,text:b??"",attachments:v??[]}},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}}}),Zu(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(y=>{const b=y.pinFacts[n];return b===void 0||b.at!==d?{}:(m=!0,{sessions:y.sessions.map(v=>v.session_id===n?{...v,pinned:h.pinned===!0}:v),pinFacts:{...y.pinFacts,[n]:{...b,pinned:h.pinned===!0}}})}),m}catch(h){return e(m=>{const y=m.pinFacts[n];if(y!==void 0&&y.at!==d)return{};const b={...m.pinFacts};return a===null&&s===void 0?delete b[n]:b[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:m.sessions.map(v=>v.session_id===n?{...v,pinned:c}:v),pinFacts:b,pinFailure:{sessionId:n,pinned:r,title:s?.title||"",detail:Fc(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?Kn(s,n):s):[...r.sessions,n]})),settlePlacement:(n,r)=>{const o=t().beginAnswer();e(s=>({sessions:s.sessions.map(a=>a.session_id===n?Kn(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:tx(a.peerDeviceFacts,o,a.peerDeviceSnapshotAt,s),y=m?.facts??qR(a.peerDeviceFacts,Object.fromEntries(Object.entries(o).filter(([,g])=>g.at>a.peerDeviceSnapshotAt))),b=l.filter(g=>g.locality==="remote");let v=a.sessions,p=!1;const E=[],k=new Map;for(let g=0;g<v.length;g+=1)k.set(v[g].session_id,g);for(const g of b){const w=k.get(g.session_id);if(w===void 0){E.push(g);continue}v[w]!==g&&(p||(v=v.slice(),p=!0),v[w]=Kn(v[w],g))}E.length>0&&(v=[...v,...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||v[w]===g||(p||(v=v.slice(),p=!0),v[w]=Kn(v[w],g))}const C=new Set(l.map(g=>g.session_id)),N=new Set;for(const g of l)g.locality==="remote"&&typeof g.owner_device=="string"&&g.owner_device!==""&&g.reachable!==!1&&N.add(g.owner_device);const O=new Set;for(const g of v){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||y[w.owner_device]?.reachable!==!1&&(w.owner_device===""||!N.has(w.owner_device)||(O.add(g),delete d[g])));O.size>0&&(v=v.filter(g=>!O.has(g.session_id)));const R=v.map(g=>ex(g,y));return R.some((g,w)=>g!==v[w])&&(v=R,p=!0),!f&&E.length===0&&!p&&O.size===0&&Object.keys(o).length===0&&s===void 0?{}:{sessions:v,placementFacts:d,peerDeviceFacts:y,peerDeviceSnapshotAt:m?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:Lx,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 Kj(e,t){return t?e.filter(n=>n.archived!==!0):e}function Vj(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 Zj(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function Yj(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const Jj="This backend cannot archive conversations. Update the backend and try again.",Xj="This conversation is already archived. Use /unarchive to restore it.",Qj="This conversation is not archived, so there is nothing to restore.",qj="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 e$(e,t,n){return n&&e&&t.trim().length>0}function t$(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],[y,b]=[Math.hypot(h,o),Math.hypot(m,c)],v=(T,V)=>{if(T===0&&V===0)return 0;const Z=Math.atan2(T,V)*d;return Z<0?Z+360:Z},[p,E]=[v(o,h),v(c,m)],k=s-n,C=b-y;let N=0;y*b!==0&&(N=E-p,N>180?N-=360:N<-180&&(N+=360));const O=2*Math.sqrt(y*b)*Math.sin(N*l/2),R=(n+s)/2,g=(y+b)/2;let w;y*b===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/$))},ei=([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,qu=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]=[qu(e),qu(t)].sort((o,s)=>s-o);return(n+.05)/(r+.05)},Fx=/^#[0-9a-fA-F]{3,8}$/,W=e=>typeof e=="string"&&Fx.test(e),ef=(e,t,n)=>{const r=f=>{const h=f.replace("#","").trim(),m=h.length===3?h.split("").map(y=>y+y).join(""):h;return[0,2,4].map(y=>Number.parseInt(m.slice(y,y+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("")}`},gn={"under-window":{dark:81,light:199},menu:{dark:102,light:171},popover:{dark:122,light:143}},ml=["canvas","surface","elevated"],bi=["ink","inkMuted","inkDim"],Xo=4.5,Ux=3,Bx=1.5,jm=["danger","success","warning","info"],$m={hover:.05,selected:.08,field:.05,work:.08},Dm=4,Hx=1.5,gl=.96,Wx=["sunken","surface"],Nm=3.5,cc=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},Ur=(e,t)=>{const[n,r]=[cc(e),cc(t)].sort((o,s)=>s-o);return(n+.05)/(r+.05)},tf=(e,t)=>Number.parseInt(e.slice(1+t*2,3+t*2),16),Fn=e=>`#${e.toString(16).padStart(2,"0").repeat(3)}`,st=(e,t,n)=>`#${[0,1,2].map(r=>Math.round(tf(e,r)*t+tf(n,r)*(1-t)).toString(16).padStart(2,"0")).join("")}`,Pt=e=>cc(e.canvas)<.18?"dark":"light",Lm=(e,t,n,r,o=Xo)=>{for(let s=.2;s<=1.0001;s+=.01)if(Ur(e[n],st(e[t],s,r))>=o)return Math.round(s*100)/100;return 1},_l=(e,t,n,r,o)=>{for(let s=.2;s<=1.0001;s+=.01){const a=st(e[t],s,r);if(Ur(e[n],st(e.ink,o,a))>=(n==="inkDim"?Nm:Xo))return Math.round(s*100)/100}return 1},Gx=(e,t)=>st(e.ink,t,e.borderControl);function zx(e,t){const n={};for(const r of["dark","light"]){let o=0;for(const s of Object.keys(gn))for(const{palette:a}of t){if(Pt(a)!==r)continue;const c=st(a.canvas,e[s][r].canvas,Fn(gn[s][r]));let l=.01;for(;l<1&&de(st(a.ink,l,c),c)<Dm;)l=Math.round((l+.01)*100)/100;o=Math.max(o,l)}n[r]=Math.round(o*100)/100}return n}function Kx(e,t=$m){const n={};for(const[r,o]of Object.entries(gn)){n[r]={};for(const s of["dark","light"]){n[r][s]={};for(const a of ml){let c=0;for(const{palette:l}of e)if(Pt(l)===s)for(const d of bi)c=Math.max(c,Lm(l,a,d,Fn(o[s])),...Object.values(t).map(u=>_l(l,a,d,Fn(o[s]),u)));n[r][s][a]=Math.min(1,Math.round((c+.02)*100)/100)}}}return n}function Vx(e){const t={};for(const n of["dark","light"]){let r=0;for(const{palette:o}of e){if(Pt(o)!==n)continue;const s=n==="dark"?"#ffffff":"#000000";for(const a of bi)r=Math.max(r,Lm(o,"elevated",a,s,a==="inkDim"?Nm:Xo))}t[n]=Math.round(r*100)/100}return t}function Fm(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 st(e.elevated,t,st(e.canvas,Fm(n,r),o))}function Zx(e,t){const n={};for(const r of["dark","light"]){const o=Fm(t,r),s=r==="dark"?"#ffffff":"#000000";let a=0;for(const{palette:c}of e){if(Pt(c)!==r)continue;const l=st(c.canvas,o,s);for(const d of["inkMuted","ink"]){let u=.2;for(;u<=1.0001&&!(Ur(c[d],st(c.elevated,u,l))>=Xo);u+=.01);a=Math.max(a,Math.round(Math.min(u,1)*100)/100)}}n[r]=Math.round(a*100)/100}return n}function Yx(e,t,n){const r={};for(const o of["dark","light"]){let s=0;for(const{palette:a}of e){if(Pt(a)!==o)continue;const c=Um(a,n[o],t,o);for(const l of jm){let d=0;for(;d<=1.0001&&!(Ur(st(a.ink,d,a[l]),c)>=Xo);d+=.05);s=Math.max(s,Math.round(Math.min(d,1)*100)/100)}}r[o]=Math.round(s*100)/100}return r}function Jx(e,t,n){const r={};for(const o of["dark","light"]){const s=n[o],a=Math.max(gl,s),c=[Math.round((a-.8*(a-s))*100)/100,s];let l=0;for(const{palette:d}of e)if(Pt(d)===o)for(const u of c){const f=Um(d,u,t,o);let h=0;for(;h<=1.0001&&!(Ur(st(d.ink,h,d.hairline),f)>=Bx);h+=.05);l=Math.max(l,Math.round(Math.min(h,1)*100)/100)}r[o]=Math.round(l*100)/100}return r}function Xx(e,t){const n={};for(const[r,o]of Object.entries(gn)){n[r]={};for(const s of["dark","light"]){let a=0;for(const{palette:c}of t)if(Pt(c)===s)for(const l of ml){const d=st(c[l],e[r][s][l],Fn(o[s]));let u=0;for(;u<1&&Ur(Gx(c,u),d)<Ux;)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 qr=new Map;function Qx(e){const t=Pt(e),n=r=>Object.values(gn).every(o=>ml.every(s=>bi.every(a=>_l(e,s,a,Fn(o[t]),r)<=.95)));return Object.fromEntries(Object.entries($m).map(([r,o])=>{let s=o;for(;s>.01&&!n(s);)s=Math.round((s-.01)*100)/100;return[r,s]}))}function qx(e,t){const n=Pt(e);let r=zx(t,[{palette:e}])[n];const o=()=>Object.entries(gn).every(([s,a])=>Array.from({length:101},(c,l)=>{const d=t[s][n].canvas,u=Math.max(gl,d),f=Math.round((u-l/100*(u-d))*100)/100,h=st(e.canvas,f,Fn(a[n]));return de(st(e.ink,r,h),h)>=Dm}).every(Boolean));for(;r<1&&!o();)r=Math.round((r+.01)*100)/100;return{dark:0,light:0,[n]:r}}function e1(e,t){const n=Pt(e);for(const r of Wx)for(let o=5;o<=104;o++){const s=o/100;if(Object.entries(gn).every(([c,l])=>Array.from({length:101},(d,u)=>{const f=t[c][n].canvas,h=Math.max(gl,f),m=Math.round((h-u/100*(h-f))*100)/100,y=Math.round(m*s*100)/100;if(y>1)return!1;const b=st(e.canvas,m,Fn(l[n]));return de(st(e[r],y,b),b)>=Hx}).every(Boolean)))return{dark:{role:r,scale:s},light:{role:r,scale:s}}}return null}function t1(e,t){const n=Pt(e);for(;;){const r=qx(e,t);let o=!1;for(const[s,a]of Object.entries(gn)){const c=Math.min(1,Math.round((Math.max(...bi.map(l=>_l(e,"canvas",l,Fn(a[n]),r[n])))+.02)*100)/100);c>t[s][n].canvas&&(t[s][n].canvas=c,o=!0)}if(!o)return r}}const n1=["canvas","surface","elevated","sunken","ink","inkMuted","inkDim","borderControl","hairline",...jm];function r1(e){for(const t of n1){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 n$(e){r1(e);const t=JSON.stringify(e),n=qr.get(t);if(n)return n;const r=[{palette:e}],o=Qx(e),s=Kx(r,o);let a,c;for(let u=0;u<=99;u++){let f=!1;for(const h of Object.keys(gn)){const m=Pt(e),y=s[h][m].canvas,b=Math.max(y,u/100);f||=b!==y,s[h][m].canvas=b}if(!(u>0&&!f)&&(a=t1(e,s),c=e1(e,s),c))break}if(!c)throw new Error("palette roles cannot form a readable transparent lane");const l=Zx(r,s),d={alphaFloor:s,blockVeil:a,laneWash:c,controlMix:Xx(s,r),bandFloor:Vx(r),overlayFloor:l,overlayInkMix:Yx(r,s,l),overlayEdgeMix:Jx(r,s,l),stateAlpha:o};return qr.set(t,d),qr.size>8&&qr.delete(qr.keys().next().value),d}const lc=new WeakMap,o1=(e,t)=>{t?lc.set(e,t):lc.delete(e)},r$=e=>lc.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 ec(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
|
|
55
|
+
*/function Uo(){return Uo=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},Uo.apply(this,arguments)}var Tn;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Tn||(Tn={}));const nf="popstate";function o$(e){e===void 0&&(e={});function t(o,s){let{pathname:a="/",search:c="",hash:l=""}=cr(o.location.hash.substr(1));return!a.startsWith("/")&&!a.startsWith(".")&&(a="/"+a),dc("",{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:Bm(s))}function r(o,s){bl(o.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(s)+")")}return i1(t,n,r,e)}function We(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function bl(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function s1(){return Math.random().toString(36).substr(2,8)}function rf(e,t){return{usr:e.state,key:e.key,idx:t}}function dc(e,t,n,r){return n===void 0&&(n=null),Uo({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?cr(t):t,{state:n,key:t&&t.key||r||s1()})}function Bm(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 cr(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 i1(e,t,n,r){r===void 0&&(r={});let{window:o=document.defaultView,v5Compat:s=!1}=r,a=o.history,c=Tn.Pop,l=null,d=u();d==null&&(d=0,a.replaceState(Uo({},a.state,{idx:d}),""));function u(){return(a.state||{idx:null}).idx}function f(){c=Tn.Pop;let v=u(),p=v==null?null:v-d;d=v,l&&l({action:c,location:b.location,delta:p})}function h(v,p){c=Tn.Push;let E=dc(b.location,v,p);n&&n(E,v),d=u()+1;let k=rf(E,d),C=b.createHref(E);try{a.pushState(k,"",C)}catch(N){if(N instanceof DOMException&&N.name==="DataCloneError")throw N;o.location.assign(C)}s&&l&&l({action:c,location:b.location,delta:1})}function m(v,p){c=Tn.Replace;let E=dc(b.location,v,p);n&&n(E,v),d=u();let k=rf(E,d),C=b.createHref(E);a.replaceState(k,"",C),s&&l&&l({action:c,location:b.location,delta:0})}function y(v){let p=o.location.origin!=="null"?o.location.origin:o.location.href,E=typeof v=="string"?v:Bm(v);return E=E.replace(/ $/,"%20"),We(p,"No window.location.(origin|href) available to create URL for href: "+E),new URL(E,p)}let b={get action(){return c},get location(){return e(o,a)},listen(v){if(l)throw new Error("A history only accepts one active listener");return o.addEventListener(nf,f),l=v,()=>{o.removeEventListener(nf,f),l=null}},createHref(v){return t(o,v)},createURL:y,encodeLocation(v){let p=y(v);return{pathname:p.pathname,search:p.search,hash:p.hash}},push:h,replace:m,go(v){return a.go(v)}};return b}var of;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(of||(of={}));function a1(e,t,n){return n===void 0&&(n="/"),c1(e,t,n)}function c1(e,t,n,r){let o=typeof t=="string"?cr(t):t,s=Gm(o.pathname||"/",n);if(s==null)return null;let a=Hm(e);l1(a);let c=null;for(let l=0;c==null&&l<a.length;++l){let d=w1(s);c=b1(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=On([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:g1(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 Wm(s.path))o(s,a,l)}),t}function Wm(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=Wm(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 l1(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:_1(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const d1=/^:[\w-]+$/,u1=3,f1=2,p1=1,h1=10,m1=-2,sf=e=>e==="*";function g1(e,t){let n=e.split("/"),r=n.length;return n.some(sf)&&(r+=m1),t&&(r+=f1),n.filter(o=>!sf(o)).reduce((o,s)=>o+(d1.test(s)?u1:s===""?p1:h1),r)}function _1(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 b1(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=v1({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:On([s,f.pathname]),pathnameBase:A1(On([s,f.pathnameBase])),route:h}),f.pathnameBase!=="/"&&(s=On([s,f.pathnameBase]))}return a}function v1(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=y1(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 b=c[f]||"";a=s.slice(0,s.length-b.length).replace(/(.)\/+$/,"$1")}const y=c[f];return m&&!y?d[h]=void 0:d[h]=(y||"").replace(/%2F/g,"/"),d},{}),pathname:s,pathnameBase:a,pattern:e}}function y1(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),bl(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 w1(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return bl(!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 k1(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:o=""}=typeof e=="string"?cr(e):e;return{pathname:n?n.startsWith("/")?n:S1(n,t):t,search:R1(r),hash:x1(o)}}function S1(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 pa(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 E1(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function vl(e,t){let n=E1(e);return t?n.map((r,o)=>o===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function yl(e,t,n,r){r===void 0&&(r=!1);let o;typeof e=="string"?o=cr(e):(o=Uo({},e),We(!o.pathname||!o.pathname.includes("?"),pa("?","pathname","search",o)),We(!o.pathname||!o.pathname.includes("#"),pa("#","pathname","hash",o)),We(!o.search||!o.search.includes("#"),pa("#","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=k1(o,c),d=a&&a!=="/"&&a.endsWith("/"),u=(s||a===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(d||u)&&(l.pathname+="/"),l}const On=e=>e.join("/").replace(/\/\/+/g,"/"),A1=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),R1=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,x1=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function I1(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const zm=["post","put","patch","delete"];new Set(zm);const T1=["get",...zm];new Set(T1);/**
|
|
56
56
|
* React Router v6.30.0
|
|
57
57
|
*
|
|
58
58
|
* Copyright (c) Remix Software Inc.
|
|
@@ -61,5 +61,5 @@ ${e}`)}function ec(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 Lo(){return Lo=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},Lo.apply(this,arguments)}const hl=x.createContext(null),p1=x.createContext(null),ir=x.createContext(null),gi=x.createContext(null),gn=x.createContext({outlet:null,matches:[],isDataRoute:!1}),Nm=x.createContext(null);function Uj(e,t){let{relative:n}=t===void 0?{}:t;Lr()||We(!1);let{basename:r,navigator:o}=x.useContext(ir),{hash:s,pathname:a,search:c}=g1(e,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:Tn([r,a])),o.createHref({pathname:l,search:c,hash:s})}function Lr(){return x.useContext(gi)!=null}function _i(){return Lr()||We(!1),x.useContext(gi).location}function Lm(e){x.useContext(ir).static||x.useLayoutEffect(e)}function h1(){let{isDataRoute:e}=x.useContext(gn);return e?I1():m1()}function m1(){Lr()||We(!1);let e=x.useContext(hl),{basename:t,future:n,navigator:r}=x.useContext(ir),{matches:o}=x.useContext(gn),{pathname:s}=_i(),a=JSON.stringify(fl(o,n.v7_relativeSplatPath)),c=x.useRef(!1);return Lm(()=>{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=pl(d,JSON.parse(a),s,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:Tn([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,a,s,e])}function Bj(){let{matches:e}=x.useContext(gn),t=e[e.length-1];return t?t.params:{}}function g1(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=x.useContext(ir),{matches:o}=x.useContext(gn),{pathname:s}=_i(),a=JSON.stringify(fl(o,r.v7_relativeSplatPath));return x.useMemo(()=>pl(e,JSON.parse(a),s,n==="path"),[e,a,s,n])}function _1(e,t){return b1(e,t)}function b1(e,t,n,r){Lr()||We(!1);let{navigator:o,static:s}=x.useContext(ir),{matches:a}=x.useContext(gn),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=_i(),f;if(t){var h;let p=typeof t=="string"?sr(t):t;d==="/"||(h=p.pathname)!=null&&h.startsWith(d)||We(!1),f=p}else f=u;let m=f.pathname||"/",y=m;if(d!=="/"){let p=d.replace(/^\//,"").split("/");y="/"+m.replace(/^\//,"").split("/").slice(p.length).join("/")}let b=Gx(e,{pathname:y}),v=S1(b&&b.map(p=>Object.assign({},p,{params:Object.assign({},l,p.params),pathname:Tn([d,o.encodeLocation?o.encodeLocation(p.pathname).pathname:p.pathname]),pathnameBase:p.pathnameBase==="/"?d:Tn([d,o.encodeLocation?o.encodeLocation(p.pathnameBase).pathname:p.pathnameBase])})),a,n,r);return t&&v?x.createElement(gi.Provider,{value:{location:Lo({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:xn.Pop}},v):v}function v1(){let e=x1(),t=u1(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 y1=x.createElement(v1,null);class w1 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(gn.Provider,{value:this.props.routeContext},x.createElement(Nm.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function k1(e){let{routeContext:t,match:n,children:r}=e,o=x.useContext(hl);return o&&o.static&&o.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(o.staticContext._deepestRenderedBoundaryId=n.route.id),x.createElement(gn.Provider,{value:t},r)}function S1(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,y=f.route.loader&&h[f.route.id]===void 0&&(!m||m[f.route.id]===void 0);if(f.route.lazy||y){l=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}return a.reduceRight((u,f,h)=>{let m,y=!1,b=null,v=null;n&&(m=c&&f.route.id?c[f.route.id]:void 0,b=f.route.errorElement||y1,l&&(d<0&&h===0?(T1("route-fallback"),y=!0,v=null):d===h&&(y=!0,v=f.route.hydrateFallbackElement||null)));let p=t.concat(a.slice(0,h+1)),E=()=>{let k;return m?k=b:y?k=v:f.route.Component?k=x.createElement(f.route.Component,null):f.route.element?k=f.route.element:k=u,x.createElement(k1,{match:f,routeContext:{outlet:u,matches:p,isDataRoute:n!=null},children:k})};return n&&(f.route.ErrorBoundary||f.route.errorElement||h===0)?x.createElement(w1,{location:n.location,revalidation:n.revalidation,component:b,error:m,children:E(),routeContext:{outlet:null,matches:p,isDataRoute:!0}}):E()},null)}var Fm=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Fm||{}),Um=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}(Um||{});function E1(e){let t=x.useContext(hl);return t||We(!1),t}function A1(e){let t=x.useContext(p1);return t||We(!1),t}function R1(e){let t=x.useContext(gn);return t||We(!1),t}function Bm(e){let t=R1(),n=t.matches[t.matches.length-1];return n.route.id||We(!1),n.route.id}function x1(){var e;let t=x.useContext(Nm),n=A1(),r=Bm();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function I1(){let{router:e}=E1(Fm.UseNavigateStable),t=Bm(Um.UseNavigateStable),n=x.useRef(!1);return Lm(()=>{n.current=!0}),x.useCallback(function(o,s){s===void 0&&(s={}),n.current&&(typeof o=="number"?e.navigate(o):e.navigate(o,Lo({fromRouteId:t},s)))},[e,t])}const qu={};function T1(e,t,n){qu[e]||(qu[e]=!0)}function Hj(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function Wj(e){let{to:t,replace:n,state:r,relative:o}=e;Lr()||We(!1);let{future:s,static:a}=x.useContext(ir),{matches:c}=x.useContext(gn),{pathname:l}=_i(),d=h1(),u=pl(t,fl(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 C1(e){We(!1)}function Gj(e){let{basename:t="/",children:n=null,location:r,navigationType:o=xn.Pop,navigator:s,static:a=!1,future:c}=e;Lr()&&We(!1);let l=t.replace(/^\/*/,"/"),d=x.useMemo(()=>({basename:l,navigator:s,static:a,future:Lo({v7_relativeSplatPath:!1},c)}),[l,c,s,a]);typeof r=="string"&&(r=sr(r));let{pathname:u="/",search:f="",hash:h="",state:m=null,key:y="default"}=r,b=x.useMemo(()=>{let v=$m(u,l);return v==null?null:{location:{pathname:v,search:f,hash:h,state:m,key:y},navigationType:o}},[l,u,f,h,m,y,o]);return b==null?null:x.createElement(ir.Provider,{value:d},x.createElement(gi.Provider,{children:n,value:b}))}function zj(e){let{children:t,location:n}=e;return _1(oc(t),n)}new Promise(()=>{});function oc(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,oc(r.props.children,s));return}r.type!==C1&&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=oc(r.props.children,s)),n.push(a)}),n}const bi=260,ml=220,gl=320,Hm=56,_l=480,Kj=8,bl=44,vl=400,Wm=1200;function yl(e){return Math.max(0,Math.min(Wm,e-_l))}function sc(e){return yl(e)>=vl?"docked":"overlay"}const O1=48,P1=16;function Vj(e,t){if(sc(e)==="docked")return{mode:"docked",width:Math.min(t,yl(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,vl),e-O1));return e-n>=P1?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function Zj({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 M1(e,t=bi,n=bl){return sc(e-Gm(t)-n)==="overlay"&&sc(e-Hm-n)==="docked"}function Gm(e){return Number.isNaN(e)?bi:Math.min(gl,Math.max(ml,e))}function j1(e,t=bl){return Math.max(0,Math.min(gl,e-_l-t))}function Yj(e,t,n=bi,r=!1,o=bl){const s=!t&&r&&M1(e,n,o),a=t||s,c=j1(e,o);return{mode:a?"strip":"docked",width:a?Hm:Math.min(Gm(n),c),collapsed:a,resizable:!a&&c>=ml}}function Qj(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const Xj=e=>e?"⌘B":"Ctrl+B",$1="data-canvas-shortcuts",D1=`[${$1}]`,N1=e=>zm(e,D1),L1='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',Jj=e=>zm(e,L1);function zm(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const qj=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&N1(e.target)?"new-file":null},Km="small",F1=["small","medium","large"],Vm="before:absolute before:-inset-0.5 before:content-['']",U1={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:Vm},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"}},e$={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:Vm,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 t$(e){for(const t of F1)if(e===t)return t;return Km}function n$(e){return U1[e].px+B1[e].px}const Zm="delegating",ms=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,la=e=>Math.max(1,Math.floor(e)),H1=e=>e===Zm,Ym=e=>e.locality==="remote"&&e.link_down===!0||e.peer_reach==="not-attempted"||e.peer_reach==="unknown";function wl(e){return Ym(e)?!1:typeof e.background_work=="boolean"?e.background_work:e.status?.code===Zm}const W1=Intl.ListFormat;let da=null;const G1=e=>{const t=mn();return da?.tag!==t&&(da={tag:t,format:new W1(t,{type:"conjunction",style:"narrow"})}),da.format.format(e)};function r$(e){if(Ym(e))return"";const t=wl(e);if(!t&&typeof e.background_work=="boolean")return"";const n=!H1(e.status?.code),r=[];n&&ms(e.subagents_running)&&r.push(_("ui.chat.sidebar.row.bg.subagents",{count:la(e.subagents_running)})),t&&ms(e.jobs_running)&&r.push(_("ui.chat.sidebar.row.bg.jobs",{count:la(e.jobs_running)}));const o=[];if(r.length>0&&o.push(_("ui.chat.sidebar.row.bg.running",{items:G1(r)})),n&&ms(e.subagents_queued)){const s=la(e.subagents_queued);o.push(r.length>0?_("ui.chat.sidebar.row.bg.queued",{count:s}):_("ui.chat.sidebar.row.bg.subagents_queued",{count:s}))}return t&&o.length===0&&e.status?.code!=="waiting"&&ms(e.waiting_on)&&o.push(_("ui.chat.sidebar.row.bg.waiting")),o.join(" · ")}const z1=new Set(["idle","recent"]);function o$(e,t){return t!==""&&z1.has(e.status?.code??"recent")&&wl(e)}const K1=["active","created"],s$={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"},V1=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function vi(e){return V1.has(e.status?.code??"")||wl(e)}const Z1=new Set(["approval","answer"]);function Qm(e){return Z1.has(e.status?.code??"")}const Y1=24*60*60*1e3,Q1=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function kl(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 X1="last_user_at";function J1(e){const t=e[X1],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 q1(e,t,n){if(vi(e))return"running";const r=kl(e,n);if(r===null)return"older";const o=Q1(t);return r>=o?"today":r>=o-6*Y1?"week":"older"}function i$(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const o of e)r[q1(o,t,n)].push(o);return r}function Xm(e,t,n){const r=kl(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 a$(e,t,n){const r=Xm(e,t,n);return r?_("ui.chat.sidebar_view.relative_short",r):""}function c$(e,t,n){const r=Xm(e,t,n);return r?n==="created"?_("ui.chat.sidebar_view.relative_created",r):_("ui.chat.sidebar_view.relative_active",r):""}const ic=["pinned","running","today","week","older","agents","teams"],l$={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 d$(e){return e==="agents"||e==="teams"}const Fo=8;function eI(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function u$(e,t){return{...e,[t]:(e[t]??Fo)+Fo}}function f$(e,t,n,r,o){const s=!(e[n]??r);return{expanded:{...e,[n]:s},caps:!s&&!o?eI(t,n):t}}function Jm(e){return`tag:${e}`}function qm(e,t){return e[Jm(t)]===!1}function p$(e,t){const n=Jm(t);if(qm(e,t)){const{[n]:r,...o}=e;return o}return{...e,[n]:!1}}function h$(e,t,n){return qm(t,n)?[]:e}function m$(e,t,n,r){return(e||t!=="")&&(r>Fo||n.trim()!=="")}const g$="Collapse, then reopen, to restore the compact list";function _$(e){return(e??Fo)>Fo}const b$=e=>`section-grown-hint-${e}`,v$=e=>_("ui.chat.sidebar.catalogue.show_more",{hidden:e});function y$(e,t){return t==="agents"?_("ui.chat.sidebar.catalogue.show_more_agents",{count:e}):_("ui.chat.sidebar.catalogue.show_more_teams",{count:e})}function w$(e,t){return e.groupBy==="tag"&&!t?"section":e.groupBy}function k$(e){return e.tagsEnabled||e.groupBy==="tag"}const _r={hidden:[],order:[...ic],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},tI=10,Xr=[25,50],nI=50,rI=500,oI=64,sI=2;function S$(e){return e.groupBy==="tag"?Math.max(e.loads,sI):e.loads}function Tr(e){const t=Math.max(0,Math.floor(e));return t===0?tI:t<=Xr.length?Xr[t-1]:Xr[Xr.length-1]+(t-Xr.length)*nI}function E$(e,t){const n=Tr(e+1)-Tr(e),r=Math.max(0,Math.min(n,t));return _("ui.chat.sidebar.catalogue.show_more_chats",{add:r})}function A$(e,t,n){const r=Tr(t+1)-Tr(t),o=Tr(t),s=Math.min(o+r,e.length);let a=0;for(let l=o;l<s;l+=1)yi(e[l])&&(a+=1);const c=Math.max(0,s-o-a);return c>0?c:Math.max(0,Math.min(r,n))}function R$(e,t){if(!t)return null;const n=e.filter(r=>yi(r));return n.length===0?null:{row:n.find(r=>Qm(r))??n[0],count:n.length}}function yi(e){return vi(e)}function iI(e){return Qm(e)?0:vi(e)?1:2}function aI(e,t){return vi(e)?J1(e):kl(e,t)}function cI(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function x$(e,t,n){const r=e.map((o,s)=>({row:o,index:s,lane:t==="active-first"?iI(o):0,at:aI(o,n)}));return r.sort((o,s)=>o.lane-s.lane||cI(o.at,s.at)||o.index-s.index),r.map(o=>o.row)}function I$(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}yi(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 T$(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=Tr(t.loads),r=[];let o=n;for(const l of e){if(yi(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 C$(e){if(e.add<=0)return null;const t=_("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 lI="mt-4",dI="mt-2";function O$(e){return e?lI:dI}function P$(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function M$(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 uI(e,t){return!e.hidden.includes(t)}function eg(e){return e.order.filter(t=>uI(e,t))}function j$(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function $$(e,t,n){const r=eg(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 fI=["running","today","week","older"];function ef(e){return fI.includes(e)}function D$(e,t,n,r){if(!ef(t)||r&&!r(t))return!1;const o=eg(e),s=o.indexOf(t);if(s<0)return!1;const a=o[s+n];return a===void 0||!ef(a)?!1:r?r(a):!0}const pI=["section","tag","agent","flat"],hI=["active-first","recent"];function N$(e){if(typeof e!="object"||e===null)return _r;const t=e,n=new Set(ic),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 ic)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=pI.includes(t.groupBy)?t.groupBy:_r.groupBy,a=K1.includes(t.basis)?t.basis:_r.basis,c=hI.includes(t.orderBy)?t.orderBy:_r.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(rI,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>=oI)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:_r.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const tg={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},mI=["recent","name","kind","modified","created","size"],gI=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function Sl(e){const t=e&&typeof e=="object"?e:{};return{sort:mI.includes(t.sort??"")?t.sort:tg.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=>[Uo,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>gI.includes(n)))]:[]}}const Uo="Attachments";function L$(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 _I=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 F$(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:Uo,label:_("ui.canvas.files.attachments"),items:o,open:n||!r.has(Uo),highlights:!1}),s.length&&c.push({id:"Highlights",label:_("ui.canvas.finder_layout.highlights"),items:s,open:n||!r.has("Highlights"),highlights:!0}),s.length&&a.length&&(c.push({id:"Working files",label:_("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:_("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=>_I(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const bI=32,U$=4,ng=32,rg=18;function B$(e){return e.height-ng-(e.kind==="tiles"&&e.section.id===Uo?rg:0)}function H$(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((y,b)=>o.set(y.row.document.id,{band:r.length,column:b})),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",bI,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(d.id===Uo){const u=d.items.filter(y=>y.row.media!=="image"),f=d.items.filter(y=>y.row.media==="image");for(const y of u)l(d,"compact",36,[y]);const h=(s-4*(a-1))/a,m=Math.round((h-8)*3/4)+ng+rg;for(let y=0;y<f.length;y+=a)l(d,"tiles",m,f.slice(y,y+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 W$(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 G$(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 vI="both",og="by-turn",ac=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function z$(e){for(const t of ac)if(e===t.value)return t.value;return og}function K$(e){return ac.find(t=>t.value===e)?.label??ac[0].label}const V$="primary+alt+shift+space",yI=/^f([1-9]|1[0-9]|2[0-4])$/;function wI(e){return yI.test(e)}function kI(e,t){const n=SI(e,t);return t==="mac"?n.join(""):n.join("+")}function SI(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]:wI(s)||s.length===1?s.toUpperCase():s)}const wi=[{id:"panel.console",get label(){return _("ui.settings.shortcuts.action.open_console")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return _("ui.settings.shortcuts.action.open_canvas")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return _("ui.settings.shortcuts.action.open_run_details")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return _("ui.settings.shortcuts.action.open_asks")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return _("ui.settings.shortcuts.action.open_browser")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return _("ui.settings.shortcuts.action.open_code_review")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],EI=new Map(wi.map(e=>[e.id,e])),AI=e=>EI.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 xI 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 El=new xI([["primary+p",()=>_("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>_("ui.settings.shortcuts.reserved.palette_commands")],["primary+k",()=>_("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>_("ui.settings.shortcuts.reserved.new_chat")],["primary+b",()=>_("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>_("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>_("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>_("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>_("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>_("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>_("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>_("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>_("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>_("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>_("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>_("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>_("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>_("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>_("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>_("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>_("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>_("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>_("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>_("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>_("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>_("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>_("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>_("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>_("ui.settings.shortcuts.reserved.browser_last_tab"):()=>_("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>_("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>_("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>_("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>_("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>_("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>_("ui.settings.shortcuts.reserved.close")],["primary+m",()=>_("ui.settings.shortcuts.reserved.minimise")]]),II=["primary","alt","shift"],TI={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},CI=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),OI=e=>CI.has(e)||/^[a-z0-9]$/.test(e);function Al(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(!OI(n))return null;const r=new Set;for(const s of t.slice(0,-1)){const a=TI[s];if(a===void 0)return null;r.add(a)}return[...II.filter(s=>r.has(s)),n].join("+")}const sg=e=>e.split("+").includes("primary");function ki(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!El.has(n)?n:AI(e)?.defaultChord??null}function Z$(e){const t=new Map;for(const n of wi){const r=ki(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const PI=e=>e==="mac"?_("ui.settings.shortcuts.capture.needs_modifier_mac"):_("ui.settings.shortcuts.capture.needs_modifier");function MI(e,t,n,r="linux",o=new Map){const s=e===null?null:Al(e);if(s===null)return _("ui.settings.shortcuts.capture.unbindable");if(!sg(s))return PI(r);const a=El.get(s);if(a!==void 0)return a;const c=o.get(s);if(c!==void 0)return _("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of wi)if(l.id!==t&&ki(l.id,n)===s)return _("ui.settings.shortcuts.capture.already_assigned",{label:l.label});return null}function jI(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const o of wi){const s=t[o.id];if(s===null){r[o.id]=null;continue}const a=typeof s=="string"?Al(s):null,c=a!==null&&RI.has(a),l=a!==null&&sg(a)&&(c||!El.has(a)&&!n.has(a))?a:null;l!==null&&(r[o.id]=l);const d=ki(o.id,r);d!==null&&n.add(d)}return r}function Y$(e,t,n){const r=ki(e,t);return r===null?null:ig(r,n)}function ig(e,t){return kI(e,t)}function Q$(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:ig(e,t),aria:[...o,r.length===1?r.toUpperCase():r].join("+")}}const tf=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)})},ag=Object.freeze([tf({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"}),tf({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"})]),X$=e=>ag.some(t=>t.role===e||t.variants.includes(e)),je={strongText:7,text:4.5,nonText:3},nf=new Set(["inkDisabled"]),He=["canvas","surface","elevated","sunken"],cg=[["ink",je.strongText],["inkMuted",5.5],["inkDim",5]],ln=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Kt={dark:{canvasMin:9,canvasMax:15,elevatedMax:22},light:{canvasMax:94,sunkenMin:80}},En={canvasSurface:[2.5,5],surfaceElevated:[2,6],canvasSunken:[1.5,6]},$I=2,DI=1.03,Rl=8,Js=2,rf=.8,of=3,sf=2,af=4,cc=2.5,cf=4,lf=2.5,df=2,uf=2,NI=[{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}],LI=[{name:"context wheel arc against its track",a:["info","warning","danger"],b:"sunken",floor:je.nonText}],FI=[{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"}],UI=[{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"],HI=["accent","success","warning","danger","info"],WI=[{fg:"surface",on:"accent",floor:je.text,name:"the console terminal's cursor ink on its own cursor (9.1)"}],GI=[],zI=[{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"}],br=15,vr=8,KI=[{theme:"catppuccinMocha",a:"accentAlt",b:"info",floor:br,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:br,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:br,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:br,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:br,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:vr,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:vr,got:0,why:"`info` IS `accent` (`#00EFFF`), the palette's single cyan"},{theme:"obsidian",a:"info",b:"accent",floor:vr,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:vr,got:0,why:"`info` IS `accent` (`#91B7E9`), the palette's single steel blue"},{theme:"githubLight",a:"info",b:"accent",floor:vr,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"}],VI=[],ZI=[],YI=["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"],gs=["success","warning","danger","info"],QI=["success","warning","danger","info","ink"],Sr=8,Jr="tokenCommand",_s=Sr,XI=["surface","elevated","messageSurface"],JI=[{theme:"obsidian",against:["ink","accent"],got:0,why:"monochrome: accent = ink = #FAFAFA. The run is separated by the semibold step, exactly as `functionName`/`className` are in code-mirror-theme.ts. Re-measure if ink or accent move."}],sn=15,Bo=15,mo=Sr,it=2,ff=4,qI=.75,pf=.12,eT=[["surface","canvas"],["surface","elevated"],["elevated","canvas"]],tT=4,nT=2,rT=2,ua=1,qs=2,fa=2,hf=.5,oT=1.5,sT=1.5,lg=5,ei=2.5,dg=.5,ti=5,lc=4,dc=24,mf=12,iT=.45,gf=.75,aT=.25,dn=2,ug=2,cT=[{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"}],lT=[{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"}],uc=10,bs="surface",_f=2,bf=1.15,dT=({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=zI.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=KI.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}`,y=[],b=R=>{n.failures++,y.push(`FAIL ${R}`)},v=new Set,p=(R,g,w,S)=>{const I=GI.find(F=>F.theme===R&&F.fg===g&&F.bg===w&&o(F.got,S));return I&&v.add(I),I};return Object.assign(n,{readings:r,pinMatches:o,ledgerHolds:s,log:y,fail:b,exceptionSeen:v,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)||b(`${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&&b(`${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}b(`${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)=>cT.find(S=>S.id===R&&S.role===g)??null,shortfallPin:(R,g,w)=>lT.find(I=>I.id===R&&I.role===g&&I.bound===w)??null}),n},uT=(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:y,ledgerHolds:b}=e;for(const{id:v,palette:p}of[t]){for(const g of YI)e.assertions++,g in p||n(`${v}: missing required role \`${g}\``);for(const[g,w]of cg)if(!nf.has(g))for(const S of ln)r(v,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(`${v}: 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(ei,dg*g),castCeiling:g=>Math.max(g,ei),stepFloor:oT,stepCeiling:null},{role:"rowSelected",castFloor:g=>Math.max(ti,g),castCeiling:g=>Math.min(Math.max(g+lc,ti),dc),stepFloor:sT,stepCeiling:lg}];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),De=g.castCeiling(me),Ge=me<dn;e.assertions++;const et=me>=dn?{name:"the panel's",hue:Math.atan2(V,T)}:z>=ug?{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>=dn&&Te>mf&&n(`${v}: \`${w}\` ${S} sits ${L(Te)} degrees off ${et.name} hue (the limit is ${mf}) — 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>De+1e-9?(d.add(`${v}:${w}:floor`),e.assertions++,c(v,w)||n(`${v}: \`${w}\` ${S} carries C* ${L(oe)}, and its cast floor ${L(Me)} 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 \`${v}\`'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-gf&&n(`${v}: \`${w}\` ${S} carries C* ${L(oe)} where its cast floor ${L(Me)} 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<Me-iT&&n(`${v}: \`${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>De+gf&&n(`${v}: \`${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 ${lc} above it, and no more`}, and the flat cap is ${dc}. 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 Rt=I-ne,Ne=p.mode==="dark"?Rt:-Rt;if(Ne<g.stepFloor-1e-9&&n(`${v}: \`${w}\` ${S} sits ${L(Math.abs(Rt))} \`L*\` ${p.mode==="dark"?"above":"below"} \`surface\` ${p.surface}, so the step is ${p.mode==="dark"?"LIGHTER":"DARKER"}-by-${L(Ne)} 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++,Ne>g.stepCeiling+aT+1e-9&&n(`${v}: \`${w}\` ${S} sits ${L(Ne)} \`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),jt=p.mode==="dark"?Ae-ne:ne-Ae,Fr=Math.hypot(ut,gt);if(e.assertions++,Ne<jt+ua-1e-9){const ar=l(v,"rowSelected","rank");d.add(`${v}:rowSelected:rank`),e.assertions++,ar?b(ar.measured,Ne-jt,.05)||n(`${v}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${ar.measured} and the pair now ranks ${L(Ne-jt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${v}: \`rowSelected\` ${S} is ${L(Ne)} \`L*\` from \`surface\` where \`rowHover\` ${p.rowHover} is ${L(jt)} — the selection has to be at least ${ua} \`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(v,"rowSelected","rank")&&n(`${v}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — the pair ranks ${L(Ne-jt)} \`L*\`, clear of the ${ua} the row claims it misses. Remove the row`);e.assertions++,oe<Fr+qs-1e-9&&n(`${v}: \`rowSelected\` ${S} carries C* ${L(oe)} where \`rowHover\` ${p.rowHover} carries ${L(Fr)} — the selection has to carry at least ${qs} 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++,jt<hf*Ne-1e-9&&n(`${v}: \`rowHover\` ${p.rowHover} takes ${L(jt)} \`L*\` of the ${L(Ne)} the selection takes (${Math.round(jt/Ne*100)}%), under the ${Math.round(hf*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 Mt=de(S,p.surface);if(Mt<it-1e-9){const Ae=l(v,w,"band");d.add(`${v}:${w}:band`),e.assertions++,Ae?b(Ae.measured,Mt,.05)||n(`${v}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Ae.measured} and the palette now measures ${L(Mt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${v}: \`${w}\` ${S} is ΔE00 ${L(Mt)} 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(v,w,"band")&&n(`${v}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${L(Mt)} 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<fa){const Ae=l(v,w,"wash");d.add(`${v}:${w}:wash`),e.assertions++,Ae?b(Ae.measured,ye,.05)||n(`${v}: 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(`${v}: \`${w}\` ${S} is ΔE00 ${L(ye)} from \`accentWash\` ${p.accentWash} (need ${fa}) — 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(v,w,"wash")&&n(`${v}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${L(ye)} from \`accentWash\`, clear of the ${fa} 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=rT;g<w-1e-9&&n(`${v}: \`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(`${v}: 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 ln){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(`${v}: 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(v,p,g,w,je.nonText,"structural edge");const k=[...He,"accentWash","messageSurface"];for(const g of HI)for(const w of k)r(v,p,g,w,je.text,"colour as text");r(v,p,"warning","elevated",je.text,"the picker's partial-listing note"),r(v,p,"danger","elevated",je.text,"danger as text on a dialog's ground"),r(v,p,"warning","rowSelected",je.text,"integration status text on a deep-linked row"),r(v,p,"accent","warningWash",je.text,"model-access band links on the warning wash"),r(v,p,"warning","rowHover",je.text,"the partial delivery word on the hovered row's ground"),r(v,p,"dangerBorder","elevated",je.nonText,"the danger control's only edge on a dialog's ground");for(const g of NI)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&&!nf.has(g.ink)&&!s(v,g.ink,g.fill??w,ne)&&n(`${v}: ${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=ZI.find(z=>z.control===g.name&&z.ground===w&&z.theme===v&&y(z.got,L(Z)));_e?h.add(m(_e.control,_e.ground,_e.theme)):n(`${v}: ${g.name} on ${w} has no perceivable edge — fill ${T}:1, border ${V}:1, need one at ${je.nonText}:1`)}}}for(const g of WI)r(v,p,g.fg,g.on,g.floor,g.name);for(const g of FI)for(const w of g.on)r(v,p,g.fg,w,g.floor??je.nonText,g.name);for(const g of LI){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(v,S,g.b,F)&&n(`${v}: ${g.name} — ${S} ${I} against ${g.b} ${w} = ${F}:1, need ${g.floor}:1`)}}for(const g of UI){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(v,g.role,T,L(V))&&n(`${v}: ${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(`${v}: ${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<gs.length;g++)for(let w=g+1;w<gs.length;w++){const[S,I]=[gs[g],gs[w]];if(!W(p[S])||!W(p[I]))continue;e.assertions++;const F=de(p[S],p[I]);F<sn&&n(`${v}: \`${S}\` ${p[S]} and \`${I}\` ${p[I]} are too close to tell apart (ΔE00 ${L(F)}, need ${sn}) — 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<sn&&n(`${v}: the second accent \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(I)} from \`accent\` ${p.accent} (need ${sn}) — two accents have to be two accents at the sizes this one is drawn at, and a value that buys its separation by darkening is the same hue at another weight rather than a second hue`)}for(const I of["success","warning","danger"]){if(!W(p[I]))continue;e.assertions++;const F=de(p.accentAlt,p[I]);F<sn&&n(`${v}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(F)} from \`${I}\` ${p[I]} (need ${sn}) — 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<Sr&&n(`${v}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(I)} from \`info\` ${p.info} (need ${Sr}) — \`info\` is the family the port mapped the TUI's \`signal\` onto, so the floor here is the reduced one and not ${sn}; below it the two take the same name`)}const[,g,w]=ie(p.accentAlt),S=Math.hypot(g,w);e.assertions++,S<Bo&&n(`${v}: \`accentAlt\` ${p.accentAlt} is C* ${L(S)} (need ${Bo}) — 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(v,p,"accentAlt",I,je.text,"second accent as text");r(v,p,"accentAlt","elevated",je.text,"second accent as text on a row's state ground")}if(o(v,p,"accentAlt","info",br,"the tool row's two category inks"),o(v,p,"info","accent",vr,"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(`${v}: \`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 QI){if(!W(p[g])||!W(p.inkDim))continue;e.assertions++;const w=de(p[g],p.inkDim);w<Sr&&n(`${v}: syntax \`${g}\` ${p[g]} sits at ΔE00 ${L(w)} from comment \`${p.inkDim}\` (need ${Sr}) — a token the eye cannot separate from the comment beside it is not highlighted`)}if(W(p[Jr])&&W(p.ink)){const g=JI.find(w=>w.theme===v);for(const w of XI){if(!W(p[w]))continue;e.assertions++;const S=se(p[Jr],p[w]);S<4.5&&n(`${v}: the command token \`tokenCommand\` ${p[Jr]} 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[Jr],p[w]);if(!!g?.against.includes(w)){y(g.got,S)||n(`${v}: 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<_s&&n(`${v}: the command token \`tokenCommand\` ${p[Jr]} sits at ΔE00 ${L(S)} from \`${w}\` ${p[w]} (need ${_s}) - 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<_s&&n(`${v}: the roster NAME's ink \`success\` ${p.success} sits at ΔE00 ${L(w)} from prose \`ink\` ${p.ink} (need ${_s}) - a resolved name that reads as prose is not a run`)}}if(W(p.inkMuted)&&W(p.inkDim)){e.assertions++,u.add(v);const g=de(p.inkMuted,p.inkDim),w=VI.find(S=>S.theme===v);w&&f.add(w),g<mo?w?y(w.got,g)||n(`${v}: 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(`${v}: the control ink \`inkMuted\` ${p.inkMuted} sits at ΔE00 ${L(g)} from the readout ink \`inkDim\` ${p.inkDim} (need ${mo}) - a chip that opens cannot be told from a reading that does not`):w&&!e.composed&&n(`${v}: the ink step is pinned at ${w.got} but now measures ${L(g)}, clearing the ${mo} 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",tT]]){if(!W(p[g])||!W(p[w]))continue;e.assertions++;const I=de(p[g],p[w]);I<S&&n(`${v}: 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<Kt.dark.canvasMin||g>Kt.dark.canvasMax)&&n(`${v}: dark \`canvas\` ${p.canvas} sits at L* ${L(g)} — the band is [${Kt.dark.canvasMin}, ${Kt.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>Kt.dark.elevatedMax&&n(`${v}: dark \`elevated\` ${p.elevated} sits at L* ${L(S)} — the ceiling is L* ${Kt.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>Kt.light.canvasMax&&n(`${v}: light \`canvas\` ${p.canvas} sits at L* ${L(g)} — the ceiling is L* ${Kt.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<Kt.light.sunkenMin&&n(`${v}: light \`sunken\` ${p.sunken} sits at L* ${L(I)} — the floor is L* ${Kt.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",En.canvasSurface,w-g],["surface -> elevated","surface","elevated",En.surfaceElevated,S-w],["canvas -> sunken","canvas","sunken",En.canvasSunken,g-I]])if(e.assertions++,(_e<V-1e-9||_e>Z+1e-9)&&n(`${v}: 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(v,p,ne,T,DI,`${$} step`),ne==="canvas"&&T==="sunken"||ne==="surface"&&T==="elevated"){e.assertions++;const z=de(p[ne],p[T]),me=ne==="canvas"?$I:nT;z<me&&n(ne==="canvas"?`${v}: \`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`:`${v}: \`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(v,p,"ink","canvas",Rl,"the transcript's body ink");for(const g of ln){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>rf*S+1e-9&&n(`${v}: \`inkDisabled\` on ${g} measures ${L(w)}:1 against \`inkDim\`'s ${L(S)}:1 — a factor of ${L(w/S)}, over the ${rf} 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<Js&&n(`${v}: \`${w}\` and \`${g}\` are ΔE00 ${L(S)} apart (need ${Js}) — 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<of&&n(`${v}: the palette/picker active row (\`sunken\` ${p.sunken}) is ΔE00 ${L(g)} from the dialog ground it is painted on (\`elevated\` ${p.elevated}), need ${of} — 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<sf&&n(`${v}: the palette/picker active row sits ${L(w)} L* from \`elevated\`, under the ${sf} 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(`${v}: 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<af&&n(`${v}: the user message block's fill \`messageSurface\` ${p.messageSurface} is ΔE00 ${L(g)} from \`canvas\` ${p.canvas} (need ${af}) — 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<cc&&n(`${v}: the user message block's fill sits ${L(w)} L* from \`canvas\`, under the ${cc} 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(`${v}: 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<cf&&n(`${v}: the media tile's fill \`mediaSurface\` ${p.mediaSurface} is ΔE00 ${L(g)} from \`canvas\` ${p.canvas} (need ${cf}) — 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<lf&&n(`${v}: the media tile's fill sits ${L(w)} L* from \`canvas\`, under the ${lf} 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<df&&n(`${v}: the accent wash on ${g} is ΔE00 ${L(w)} (need ${df}) — 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<uf&&n(`${v}: the keycap's ground \`sunken\` ${p.sunken} is ΔE00 ${L(w)} from ${g} ${p[g]} (need ${uf}) — 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[bs])){e.assertions++;const g=de(p.chartBarHover,p.accent);g<uc&&n(`${v}: \`chartBarHover\` ${p.chartBarHover} is ΔE00 ${L(g)} from \`accent\` ${p.accent}, need ${uc} — 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[bs]),S=se(p.accent,p[bs]);w<S&&n(`${v}: \`chartBarHover\` is ${L(w)}:1 on ${bs} 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<ff&&n(`${v}: \`hairline\` on \`${g}\` is ΔE00 ${L(w)} (need ${ff}) — 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<bf&&n(`${v}: \`hairline\` on \`${g}\` is ${L(S)}:1 (need ${bf}) — its ΔE00 is carried in chroma, which a 1px line does not survive`),e.assertions++,S>_f&&n(`${v}: \`hairline\` on \`${g}\` is ${L(S)}:1 (max ${_f}) — past this it is drawing a border, and the system already has one of those`)}for(const[g,w]of eT){if(!W(p.hairline)||!W(p[g])||!W(p[w]))continue;const S=Vu(p.hairline,p[g],qI);e.assertions++;const I=de(S,p[g]);I<it&&n(`${v}: 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(`${v}: 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=Vu(p.accent,p.surface,pf);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(`${v}: ${S} — ${g} ${I} on the arrival band ${C} (accent ${pf} over surface) = ${F}:1, need ${w}:1`)}const N=se(C,p.surface),O=se(p.rowHover,p.surface),R=se(p.rowSelected,p.surface);e.assertions+=2,N<=O&&n(`${v}: the arrival band is ${L(N)}: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`),N<=R&&n(`${v}: the arrival band is ${L(N)}: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`)}},fT=Object.freeze({soft:-100,gentle:-50,standard:0,strong:50,high:100}),pT=Object.freeze({dark:Object.freeze({high:5,soft:20}),light:Object.freeze({high:97,soft:89})}),hT=["canvas","surface","elevated","sunken","messageSurface","mediaSurface","rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash","hairline","hairlineStrong","inkDisabled"],mT=new Set(["rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash"]),Rs=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Tt=Rs.slice(0,4),qr=[...Tt,"accentWash","messageSurface"],pa={ink:[Rs,7],inkMuted:[Rs,5.5],inkDim:[Rs,5],borderControl:[Tt,3],accent:[[...qr,"warningWash"],4.5],accentHover:[Tt,4.5],accentActive:[Tt,4.5],tokenCommand:[["surface","elevated","messageSurface"],4.5],accentAlt:[Tt,4.5],success:[qr,4.5],warning:[[...qr,"rowSelected","rowHover"],4.5],danger:[qr,4.5],info:[qr,4.5],successBorder:[Tt,3],warningBorder:[Tt,3],dangerBorder:[Tt,3],infoBorder:[Tt,3],chartBarHover:[["surface"],3]},Ot=.05,vf=.3,yf=4.1,gT=.06,_T=/^#[0-9A-Fa-f]{6}$/,ot=e=>typeof e=="string"&&_T.test(e),Bt=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=Xs([r,t*o,n*o]);if(s)return s}return Xs([r,0,0])},qn=(e,t,n)=>Math.min(...n.filter(r=>ot(e[r])).map(r=>se(t,e[r]))),fc=(e,t,n,r,o=()=>!0)=>{const s=e[t];if(!ot(s)||qn(e,s,n)>=r+Ot&&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(qn(e,f,n)>=r+Ot&&o(f))return f}return s},xl=(e,t)=>{const n=t.filter(ot).map(Bt),r=n.find(o=>se(o,e)>=4.5);return r||[...n].sort((o,s)=>se(s,e)-se(o,e))[0]},vs=e=>1+.015*(e-50)**2/Math.sqrt(20+(e-50)**2),er=e=>{const[,t,n]=ie(e);return Math.hypot(t,n)},wf=(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)},bT=e=>{if(!ot(e.rowHover)||!ot(e.rowSelected))return;wT(e);const t=er(e.surface),n=Math.max(ei,dg*t),r=Math.max(t,ei),o=Math.max(ti,t),s=Math.min(Math.max(t+lc,ti),dc),a=(f,h,m)=>Math.min(Math.max(f,h),m),c=er(e.rowHover),l=er(e.rowSelected);if(c>=n&&c<=r&&l>=o&&l<=s&&l>=c+qs)return;const d=a(c,n+.1,r-.1),u=a(Math.max(l,d+qs+.2),o+.1,s-.1);e.rowHover=wf(e.rowHover,d),e.rowSelected=wf(e.rowSelected,u)},vT=6,yT=e=>{const[,t,n]=ie(e);return Math.atan2(n,t)},wT=e=>{const n=er(e.surface)>=dn?e.surface:er(e.accent)>=ug?e.accent:e.surface,r=yT(n);for(const o of["rowHover","rowSelected"]){const[s,a,c]=ie(e[o]),l=Math.hypot(a,c);l<dn||Math.abs(((Math.atan2(c,a)-r)*180/Math.PI+540)%360-180)<=vT||(e[o]=ct(s,l*Math.cos(r),l*Math.sin(r)))}},kT=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=>qn(e,m,o)>=s+Ot&&(!a||de(m,e[a])>=c+Ot)&&(r!=="ink"||se(m,e.canvas)>=Rl+Ot);if(d(l))return;const[u,f,h]=ie(l);for(let m=.25;m<=100;m+=.25){const y=ct(u+t*m,f,h);if(d(y)){e[r]=y;return}}};n("inkDim",ln,xs("inkDim"),null,0),n("inkMuted",ln,xs("inkMuted"),"inkDim",mo),n("ink",ln,xs("ink"),"inkMuted",Js)},xs=e=>cg.find(([t])=>t===e)[1],ST=.15,fg=.12,ET=(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+ST*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 y=ct(m,d,u);if(e.ink=y,se(y,e.canvas)>=f)return}return}const s=t*(1-fg*r),a=["ink","inkMuted","inkDim"].filter(l=>ot(e[l])),c=l=>a.every(d=>qn(e,l[d],ln)>=xs(d)+Ot)&&se(l.ink,e.canvas)>=Rl&&(!l.inkMuted||de(l.ink,l.inkMuted)>=Js+Ot)&&(!l.inkMuted||!l.inkDim||de(l.inkMuted,l.inkDim)>=mo+Ot);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,y,b]=d[h];f[h]=ct(m-o*u,y,b)}if(!c(f))break;for(const h of l)e[h]=f[h]}}},ys=(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+Ot)&&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}}},pg=(e,t,{spread:n=1,narrow:r=!1,ease:o=gT,travel:s=1}={})=>{if(t===0)return e;const a=t>0?"high":"soft",c=Math.abs(t)/100,l={...e},d=z=>ie(Bt(e[z])),u=d("canvas")[0],f=pT[e.mode][a],h=hT.filter(z=>ot(e[z])),m=a==="high"==(e.mode==="light")?1:-1;let y=Math.max(0,(f-u)*m)*m*c*s,b=u+y;const v=a==="soft"?1-.4*c:1,p=vs(b)/vs(u),E=(a==="soft"?p:Math.max(1,p))*n,k=Object.fromEntries(h.map(z=>[z,b+(d(z)[0]-u)*E])),C=e.mode==="dark"?1:-1,N=(z,[,me],oe)=>{const Me=(d(z)[0]-u)*oe,De=(k[z]-b)*oe,Ge=Math.max(Me,me-.15);De>Ge&&(k[z]=b+oe*Ge)};N("surface",En.canvasSurface,C),N("sunken",En.canvasSunken,-C);{const z=(d("elevated")[0]-d("surface")[0])*C,me=(k.elevated-k.surface)*C,oe=Math.max(z,En.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,lg/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+y,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-vf-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},De=[["canvas","surface",it],["surface","elevated",it],["canvas","elevated",yf],["canvas","messageSurface",yf]].filter(([ye,Ae])=>(ye==="canvas"||me.includes(ye))&&me.includes(Ae)),Ge=[["canvas","surface",En.canvasSurface[0]],["surface","elevated",En.surfaceElevated[0]],["canvas","messageSurface",cc]].filter(([ye,Ae])=>(ye==="canvas"||me.includes(ye))&&me.includes(Ae)),et=(ye,Ae,ut)=>ut+.02,be=ye=>De.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 Rt=Te<=u?1:Math.min(1,(100-vf-Te)/oe),Ne=Math.max(1,vs(Te)/vs(u))*n,Mt={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)*Rt:Te+(k[ye]-z)*(Ne/E);for(const ye of["rowHover","rowSelected"])ye in k&&Number.isFinite(Mt[ye])&&(k[ye]=k.surface+Mt[ye]);b=Te,y=Te-u}}if(a==="soft"&&r){const z=be=>e.mode==="dark"?be>b:be<b,me=be=>be>8?((be+16)/116)**3:Math.max(0,be)/903.3,oe=(be,Te)=>{const[Rt,Ne]=[me(be),me(Te)];return(Math.max(Rt,Ne)+.05)/(Math.min(Rt,Ne)+.05)},Me=ln.filter(be=>be in k&&z(k[be])),Ge=Math.max(1,...ln.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(b,b+(k[Te]-b)*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]=b+(k[Te]-b)*be)}}const F=Math.min(...Object.values(k)),$=Math.max(...Object.values(k)),ne=F<.5?.5-F:$>100?100-$:0,T=er(Bt(e.surface)),V=T>=dn?Math.max(v,Math.min(1,(dn+.4)/T)):v;for(const z of h){const[,me,oe]=d(z),Me=mT.has(z)?1:z==="surface"?V:v;l[z]=ct(k[z]+ne,me*Me,oe*Me)}bT(l),y=b+ne-u;for(const z of Object.keys(pa))ot(e[z])&&(l[z]=Bt(e[z]));kT(l),ET(l,se(Bt(e.ink),Bt(e.canvas)),t);const Z=ie(l.accent)[0];l.accent=fc(l,"accent",...pa.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(pa))z.startsWith("ink")||z==="accent"||(l[z]=fc(l,z,me,oe));return ys(l,"accentHover","accent",it,z=>qn(l,z,Tt)>=4.5+Ot),ys(l,"accentActive","accent,accentHover",it,z=>qn(l,z,Tt)>=4.5+Ot),ys(l,"accentAlt","accent",sn,z=>qn(l,z,Tt)>=4.5+Ot&&er(z)>=Bo),ys(l,"chartBarHover","accent",uc,z=>se(z,l.surface)>=se(l.accent,l.surface)),l.onAccent=xl(l.accent,[e.onAccent,l.ink,l.canvas,"#FFFFFF","#000000"]),l},ni=(e,t="custom")=>{const n=dT({composed:!0});return uT(n,{id:t,palette:e}),n.log},Is=(e,t)=>{const n=xl(e.accent,[t.onAccent,e.ink,e.canvas,"#FFFFFF","#000000"]);return n===e.onAccent?e:{...e,onAccent:n}},kf=new Set(["mode","overlayShadow","scrim","onAccent"]),AT=["rowHover","rowSelected","accentWash","surface"],RT=/\b[a-z][A-Za-z]+\b/g,xT=(e,t)=>{const n=new Map;for(const[o,s]of Object.entries(e))!kf.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 AT)r.add(s);for(const[s]of o.matchAll(RT))s in e&&!kf.has(s)&&ot(e[s])&&r.add(s);for(const[s]of o.matchAll(IT)){const a=n.get(s.toUpperCase());a&&r.add(a)}}return[...r]},IT=/#[0-9A-Fa-f]{6}\b/g,TT=/(?:= |ΔE00 )(\d+(?:\.\d+)?)(?::1)?[\s\S]*?need (\d+(?:\.\d+)?)/,CT=e=>{let t=0;for(const n of e){const r=n.match(TT);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+CT(e),OT=[.5,-.5,1,-1,2,-2,4,-4,7,-7,11,-11],PT=[.7,.85,1.15,1.35],MT=60,hg=(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:Is(h,n);let l=0,d=c(e),u=ni(d,t),f=Sf(u);for(let h=0;h<MT&&u.length>0;h++){let m=null;for(const y of xT(d,u)){if(a.has(y))continue;const[b,v,p]=ie(d[y]),E=[...OT.map(k=>ct(b+k,v,p)),...s?[]:PT.map(k=>ct(b,v*k,p*k))];for(const k of E){if(k===d[y])continue;if(++l>o)return{palette:d,findings:u};const C=c({...d,[y]:k}),N=ni(C,t),O=Sf(N);O<(m?m.score:f)-1e-9&&(m={next:C,findings:N,score:O})}}if(!m)break;d=m.next,u=m.findings,f=m.score}return{palette:d,findings:u}},jT=5,$T=[1,1.15],DT=[{spread:1,narrow:!0},{spread:1,narrow:!0,ease:0},...$T.map(e=>({spread:e})),{spread:1,travel:.5,soft:!0},{spread:1,travel:0,soft:!0}],Ef=.015,NT=(e,t,n)=>{const r=se(Bt(e.ink),Bt(e.canvas)),o=se(t.ink,t.canvas),s=ie(Bt(e.canvas))[0],a=ie(t.canvas)[0],c=n>0==(e.mode==="light")?1:-1;return n>0?o>=r-Ef&&(a-s)*c>=-.05:o<=r+Ef},LT=(e,t,n,r)=>{const s=se(Bt(t.ink),Bt(t.canvas))*(1-fg*(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[y,b,v]=u[m];h[m]=ct(y+a*f,b,v)}if(ni(Is(h,t),r).length>0)break;l=Is(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 y=Number.parseInt(l.ink.slice(1+2*f,3+2*f),16)+h;if(y<0||y>255)continue;const b=`#${l.ink.slice(1,1+2*f)}${y.toString(16).padStart(2,"0").toUpperCase()}${l.ink.slice(3+2*f)}`,v=se(b,l.canvas);if(v>=se(l.ink,l.canvas))continue;const p=Is({...l,ink:b},t);ni(p,r).length>0||(!u||v>u.r)&&(u={r:v,next:p})}if(!u)break;l=u.next}return l},FT=(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(jT,Math.abs(o)))for(const s of DT){if((s.narrow||s.soft)&&o>0)continue;const a=pg(e,o,s),c=hg(a,n,e);if(o<0&&c.findings.length===0&&(c.palette=LT(c.palette,e,o,n)),c.findings.length===0&&NT(e,c.palette,o))return{palette:c.palette,effectiveContrast:o}}return{palette:e,effectiveContrast:0}},zn=/^#[0-9A-Fa-f]{6}$/,UT=/^#[0-9A-Fa-f]{3}$/,mt=e=>{if(typeof e!="string")return null;let t=e.trim();return t.startsWith("#")||(t=`#${t}`),UT.test(t)&&(t=`#${[...t.slice(1)].map(n=>n+n).join("")}`),zn.test(t)?t.toUpperCase():null},BT=["accentHover","accentActive","accentWash","chartBarHover"],Ft=e=>{const[t,n,r]=ie(e);return[t,Math.hypot(n,r),Math.atan2(r,n)]},HT=e=>Ft(e)[1],ri=(e,t,n)=>ct(e,Math.max(0,t)*Math.cos(n),Math.max(0,t)*Math.sin(n)),WT=4,GT=(e,t,n)=>{const[r,o,s]=Ft(e),[a,c,l]=Ft(t),[d,u,f]=Ft(n);return o<WT?ri(d+(a-r),c,f):ri(d+(a-r),u*(c/o),f+(l-s))},zT=(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},KT=(e,t,{authored:n=e,id:r="custom",paletteAccent:o,preserveSecondary:s=!1}={})=>{const a=zT(t,n,o);if(!a)return{palette:e,applied:!1,adjusted:0,requested:a};const c={...e,accent:a};for(const h of BT)!zn.test(n[h]??"")||!zn.test(n.accent??"")||(c[h]=GT(n.accent,n[h],a));if(zn.test(e.accentWash??"")&&zn.test(n.accentWash??"")){const h=Ft(e.accentWash)[0],[,m,y]=Ft(c.accentWash);c.accentWash=ri(h,Math.max(m,Ft(n.accentWash)[1]),y)}if(HT(c.surface)<dn){const h=Ft(c.accent)[2];for(const m of["rowHover","rowSelected"]){if(!zn.test(c[m]??""))continue;const[y,b]=Ft(c[m]);b>=dn&&(c[m]=ri(y,b,h))}}!s&&t.kind==="theme-alt"?Ft(n.accent)[1]>=Bo&&(c.accentAlt=mt(n.accent)):!s&&de(c.accent,c.accentAlt)<sn&&Ft(n.accent)[1]>=Bo&&(c.accentAlt=mt(n.accent));const l=ie(c.accent)[0];c.accent=fc(c,"accent",VT,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(!zn.test(c[h]??""))continue;const[m,y,b]=ie(c[h]);c[h]=ct(m+d,y,b)}c.onAccent=xl(c.accent,[n.onAccent,c.ink,c.canvas,"#FFFFFF","#000000"]);const u=hg(c,r,n);return s&&ag.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}},VT=["canvas","surface","elevated","sunken","accentWash","messageSurface","warningWash"],Af=["dark","light"],ZT=12,J$=50,q$="custom-themes-storage",YT=60,mg=Object.freeze({dark:0,light:0}),An=Object.freeze({kind:"theme"}),gg=Object.freeze({dark:An,light:An}),pc=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(-100,Math.min(100,Math.round(e))),_g=e=>!e||typeof e!="object"?mg:{dark:pc(e.dark),light:pc(e.light)},hc=(e,t=()=>!0)=>{if(!e||typeof e!="object")return An;switch(e.kind){case"theme":return An;case"theme-alt":return{kind:"theme-alt"};case"palette":return typeof e.id=="string"&&t(e.id)?{kind:"palette",id:e.id}:An;case"custom":{const n=mt(e.hex);return n?{kind:"custom",hex:n}:An}default:return An}},bg=(e,t)=>!e||typeof e!="object"?gg:{dark:hc(e.dark,t),light:hc(e.light,t)},$r=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===ZT)break}return t},QT=(e,t)=>{const n=mt(t);return $r(n?[n,...Array.isArray(e)?e:[]]:e)},XT=/^custom-[a-z0-9]{1,30}$/,Il=e=>typeof e=="string"&&XT.test(e)?e:null,eD=(e,{isThemeName:t,isRole:n})=>{if(!e||typeof e!="object"||e.format!=="local-operator-theme"||e.version!==1)return null;const r=Il(e.id);if(!r||!yc(r)||typeof e.base!="string"||!t(e.base))return null;const o=typeof e.name=="string"&&e.name.trim()?e.name.trim().slice(0,YT):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&&wc(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}},Qt=Object.freeze(Object.entries(fT).sort(([,e],[,t])=>e-t).map(([e,t])=>Object.freeze({name:e,value:t}))),Rf=5,JT=8,qT=e=>Math.max(-100,Math.min(100,e)),tD=(e,{snap:t=!0}={})=>{if(!Number.isFinite(e))return 0;const n=qT(Math.round(e/Rf)*Rf);if(!t)return n;for(const{value:r}of Qt)if(Math.abs(e-r)<=JT)return r;return n},eC=e=>Qt.find(t=>t.value===e)?.name??null,nD=e=>{let t=Qt[2];for(const n of Qt){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},rD=e=>{if(eC(e))return null;for(let t=1;t<Qt.length;t++)if(e<Qt[t].value)return[Qt[t-1].name,Qt[t].name];return null},oD=(e,t)=>{const r=(t>0?Qt:[...Qt].reverse()).find(o=>t>0?o.value>e:o.value<e);return r?r.value:e},tC=[[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"]],Tl=8,Cl=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}},sD=e=>{const{C:t,h:n}=Cl(e);if(t<Tl)return"neutral";for(const[r,o]of tC)if(n<r)return o;return"pink"},iD=(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}=Cl(l.palette.accent);if(d<Tl){(!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},aD=(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}=Cl(s);return a<Tl?1e3:c};return r.sort((s,a)=>o(s.hex)-o(a.hex))},nC=40,Ts=(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,nC);s&&(n[r]=s)}return n},cD=Object.freeze({strip:"lo-preview",chip:e=>`lo-preview-${e}`}),lD=(e,t,n=null)=>{const r=[];for(const{id:o,contrast:s}of t){if(!yc(o))continue;const a=s===0?e:pg(e,s),c=n?{...a,...n}:a;Object.entries(c).every(([d,u])=>d==="mode"||wc(u))&&r.push($f(o,c))}return r.join(`
|
|
65
|
-
`)},dD=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}},uD=({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=Xs([r,s*Math.cos(o),s*Math.sin(o)]);if(a)return a}return Xs([r,0,0])??"#000000"},fD=e=>{const t=se("#FFFFFF",e),n=se("#000000",e);return t>=n?{ink:"#FFFFFF",ratio:t}:{ink:"#000000",ratio:n}},pD=Object.freeze(["accent","accentHover","accentActive","accentWash","onAccent","chartBarHover","accentAlt","accentAltWash"]),xf=64,mc=["canvas","run","browser","console","code"],rC={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function vg(e){return typeof e=="string"&&mc.includes(e)}function Ol(e){return e.startsWith("draft:")}function Yo(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function Pl(e){return e.length>xf?e.slice(e.length-xf):e}function yg(e,t,n){return Pl([...e.filter(([r])=>r!==t),[t,n]])}function oC(e,t,n){return Yo(e,t)!==n?e:e.filter(([r])=>r!==t)}function sC(e,t){return Yo(e,t)===void 0?e:e.filter(([n])=>n!==t)}function iC(e,t,n){const r=Yo(e,t);return r===void 0?e:Pl([...e.filter(([o])=>o!==t&&o!==n),[n,r]])}const If=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function Tf(e,t,n){if(n||typeof t!="string")return If;const r=Yo(e,t);return r===void 0?If:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function aC(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===""||Ol(r)||vg(o)&&(t.delete(r),t.set(r,o))}return Pl([...t.entries()])}function hD(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 Cf(e){return rC[e]}const cC={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},Qo=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,Si=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,lC=e=>{const t=Qo(e);return t===null||t==="ask"?null:cC[t]},kn=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Bn=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:yg(e.rightSlotMemory,n,t)}},eo=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=oC(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},dC=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=sC(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},uC=Object.freeze({mounted:!1,session:!1}),wg=Object.freeze([]);function mD(e,t){const n=Qo(t);if(n===null||!Si(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=to(vl,t.rightSlotWidth);break;case"run":r=to(Pf,t.rightSlotWidth);break;case"browser":r=to(gC,t.rightSlotWidth);break;case"console":r=to(_C,t.rightSlotWidth);break;case"code":r=to(Pf,t.rightSlotWidth);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,yl(e)):Math.min(r,Math.max(0,e-_l))}function to(e,t){return Math.min(Wm,Math.max(e,t||fC))}function gD(e){const t=Qo(e);return t!==null&&Si(t,e)}function _D(e){const t=Qo(e);return t!==null&&Si(t,e)?t:null}function bD(e){const t=Qo(e);return(t==="canvas"||t==="ask")&&Si(t,e)}const fC=640,Of=bi,pC=20,hC=4,mC=20,Pf=320,gC=480,_C=480,bC=5e3,vD=(e,t)=>e.some(n=>n.surface===t),yD=(e,t=Date.now())=>e.some(n=>t-n.at<bC),vC=[],yC=5,wC=["chatMeasureWidth"],wD=Go()(ci((e,t)=>({finderFiles:tg,setFinderFiles:n=>e({finderFiles:Sl({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:og,agentAvatarSize:Km,themeName:Cg,contrast:mg,accent:gg,customAccents:[],customAccentNames:{},customThemeId:null,setContrast:(n,r)=>e(o=>({contrast:{...o.contrast,[n]:pc(r)}})),setAccent:(n,r)=>e(o=>({accent:{...o.accent,[n]:hc(r,bc)}})),addCustomAccent:(n,r)=>e(o=>{const s=QT(o.customAccents,n),a=mt(n),c=Ts(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 Af){const l=s[c];l.kind==="custom"&&l.hex===o&&(s[c]=An)}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:Ts({...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=$r(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 Af){const m=f[h];m.kind==="custom"&&m.hex===s&&(f[h]={kind:"custom",hex:a})}return{customAccents:d,customAccentNames:Ts(u,d),accent:f}}),rightSlotWidth:0,chatSidebarWidth:Of,chatSidebarRegions:vI,chatSidebarView:_r,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:wg,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:uC,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:vC,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?{...kn("isCanvasOpen"),...Bn(r,"canvas")}:{isCanvasOpen:!1,...eo(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...kn("isRunPanelOpen"),...Bn(r,"run")}:{isRunPanelOpen:!1,...eo(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...kn("isBrowserPaneOpen"),...Bn(r,"browser")}:{isBrowserPaneOpen:!1,...eo(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...kn("isConsolePaneOpen"),...Bn(r,"console")}:{isConsolePaneOpen:!1,...eo(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...kn("isCodeReviewPaneOpen"),...Bn(r,"code")}:{isCodeReviewPaneOpen:!1,...eo(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...kn("isCodeReviewPaneOpen"),...Bn(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,o)=>{e(s=>{const a=typeof s.rightSlotKey=="string";if(n)return{...kn("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:a?null:lC(s),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?o?.dismissSlot?{...c,...dC(s)}:{...c,...Tf(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=iC(s,c,n)),n===null||(Ol(n)?a=null:a!==null&&Yo(s,n)===void 0&&(s=yg(s,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:s,rightSlotLegacySeed:a,...Tf(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=Al(r);s!==null&&MI(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=>({...kn("isRunPanelOpen"),...Bn(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(gl,Math.max(ml,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:Of})},rememberMention:(n,r)=>{e(o=>{const s=o.mentionRecents,a=s?.cwd===n?s.paths:[],c=[r,...a.filter(l=>l!==r)].slice(0,pC);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(o=>({profileRecents:{...o.profileRecents,[n]:kC(o.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const o=AC(r.conversationRecents),s=SC(o,n);return s.length===o.length&&s.every((a,c)=>a===o[c])?r:{conversationRecents:s}})}}),{name:"ui-preferences-storage",version:yC,migrate:TC,partialize:RC,merge:IC}));function kC(e,t){return[t,...e.filter(n=>n!==t)].slice(0,hC)}function SC(e,t){return[t,...e.filter(n=>n!==t)].slice(0,mC)}const EC=[];function AC(e){return Array.isArray(e)?e:EC}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:y,rightSlotKey:b,...v}=e;return{...v,rightSlotMemory:xC(e.rightSlotMemory)}}function xC(e){return(e??wg).filter(([t])=>!Ol(t))}function IC(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:o,isBrowserPaneOpen:s,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:Sl(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:aC(n.rightSlotMemory),rightSlotLegacySeed:vg(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:jI(n.shortcutBindings),contrast:_g(n.contrast),accent:bg(n.accent,bc),customAccents:$r(n.customAccents),customAccentNames:Ts(n.customAccentNames,$r(n.customAccents)),customThemeId:Il(n.customThemeId)}}function TC(e,t){const n={...e??{}};if(t<1&&CC(n),t<2)for(const r of wC)delete n[r];if(t<3){let r=null;for(const o of mc)if(n[Cf(o)]===!0){r=o;break}r!==null&&(n.rightSlotLegacySeed=r);for(const o of mc)delete n[Cf(o)]}return t<4&&(n.finderFiles=Sl(n.finderFiles)),t<5&&(n.contrast=_g(n.contrast),n.accent=bg(n.accent,bc),n.customAccents=$r(n.customAccents),n.customThemeId=Il(n.customThemeId)),n}function CC(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 gc=e=>e.replace(/\\/g,"/"),kD=()=>window.location.hash?gc(window.location.hash.substring(1)):gc(window.location.pathname),SD=(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,"/")},ED=(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=y=>{const b=t-y.length-(y?3:2);let v=[];for(let p=a.length-1;p>=0;p-=1){const E=[a[p],...v];if(E.join("/").length>b)break;v=E}return v},l=(y,b)=>y?`${y}/…/${b.join("/")}`:`…/${b.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)]):"…"},AD=(e,t)=>gc(e).includes(t),_c=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)},OC=(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=FT(e,t,{id:r});let l=c.palette,d=!0,u=0;if(!a){const f=KT(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-${_c(l)}`,effectiveContrast:c.effectiveContrast,requestedContrast:t,accentApplied:d,accentAdjusted:u}},Mf="lo-composed-theme",PC=4,Hn=new Map,MC=(e,t)=>{const n=Hn.get(e);if(n)return Hn.delete(e),Hn.set(e,n),n;const r=Og(t);if(Hn.set(e,r),Hn.size>PC){const o=Hn.keys().next().value;o!==void 0&&Hn.delete(o)}return r},jC=e=>vc(e)?.palette.accent,$C=16,pr=new Map,DC=(e,t,n)=>{const r=jf(e.themeName),o=vc(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?_c(t):null,l,d??null]);let f=pr.get(u);if(f?pr.delete(u):f=OC(s,{contrast:l,accent:d,id:c,preserveSecondary:t!==void 0,paletteAccent:jC}),pr.set(u,f),pr.size>$C){const m=pr.keys().next().value;m!==void 0&&pr.delete(m)}if(f.identity&&!n)return{...f,id:r.id,muiTheme:r.theme};const h=`lo-${_c(f.palette)}`;return{...f,id:h,identity:!1,muiTheme:MC(h,f.palette)}},NC=(e,t)=>yc(e)&&Object.entries(t).every(([n,r])=>n==="mode"||wc(r))&&(t.mode==="dark"||t.mode==="light"),RD=(e,t=document,n,r,o=s=>DC(s,n,r))=>{let s=o(e);if(!s.identity&&!NC(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=jf(e.themeName),d=vc(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(Mf);if(s.identity)c?.remove();else{const l=c??t.createElement("style");l.id=Mf,l.textContent=$f(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},xD=e=>({themeName:e.themeName,customThemeId:e.customThemeId??null,contrast:e.contrast,accent:e.accent}),ID=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{ij as $,Aj as A,zR as B,WR as C,V$ as D,RD as E,xD as F,wD as G,at as H,SI as I,ID as J,DC as K,i as L,yp as M,Pe as N,PR as O,xd as P,MR as Q,fj as R,ht as S,lm as T,fm as U,aj as V,lj as W,dm as X,cj as Y,oj as Z,uj as _,BO as a,Nj as a$,dj as a0,Wj as a1,kD as a2,yu as a3,lM as a4,bm as a5,xj as a6,Ij as a7,_i as a8,Jj as a9,nO as aA,hP as aB,iO as aC,Db as aD,sO as aE,aO as aF,zC as aG,Uf as aH,xi as aI,Ob as aJ,Cb as aK,sA as aL,yR as aM,uM as aN,pM as aO,hM as aP,Xh as aQ,t$ as aR,F1 as aS,e$ as aT,U1 as aU,B1 as aV,mt as aW,ZT as aX,sD as aY,fD as aZ,nC as a_,AC as aa,hn as ab,st as ac,Nr as ad,fc as ae,BC as af,Ly as ag,QM as ah,Go as ai,LM as aj,fO as ak,WC as al,Ct as am,Ia as an,ci as ao,gv as ap,FO as aq,PO as ar,Rv as as,xv as at,Md as au,uO as av,dO as aw,mp as ax,gc as ay,D0 as az,$O as b,CR as b$,eC as b0,nD as b1,Qt as b2,cD as b3,Rf as b4,tD as b5,rD as b6,oD as b7,iD as b8,aD as b9,lx as bA,Rj as bB,gj as bC,AD as bD,tO as bE,eO as bF,qC as bG,JC as bH,oO as bI,Bb as bJ,Lt as bK,po as bL,bp as bM,rv as bN,By as bO,LO as bP,NO as bQ,DO as bR,_D as bS,Y$ as bT,$M as bU,jn as bV,dd as bW,Cc as bX,jv as bY,ii as bZ,cp as b_,lD as ba,pD as bb,nk as bc,tx as bd,UO as be,ag as bf,OC as bg,dD as bh,X$ as bi,ac as bj,z$ as bk,Ho as bl,rt as bm,Nf as bn,qg as bo,r_ as bp,i_ as bq,u_ as br,c_ as bs,l_ as bt,td as bu,p_ as bv,nd as bw,f_ as bx,d_ as by,Dj as bz,HO as c,r$ as c$,sj as c0,ae as c1,rj as c2,gr as c3,Qa as c4,Xa as c5,tj as c6,nj as c7,XM as c8,JM as c9,l$ as cA,vm as cB,$j as cC,N$ as cD,S$ as cE,x$ as cF,I$ as cG,E$ as cH,A$ as cI,_r as cJ,i$ as cK,eg as cL,m$ as cM,P$ as cN,Fo as cO,O$ as cP,M$ as cQ,Tr as cR,Wu as cS,_$ as cT,g$ as cU,b$ as cV,y$ as cW,v$ as cX,u$ as cY,T$ as cZ,C$ as c_,qM as ca,Q$ as cb,yD as cc,bC as cd,vD as ce,gp as cf,xO as cg,yO as ch,_p as ci,$y as cj,Kb as ck,Lg as cl,Vb as cm,kl as cn,SO as co,Uu as cp,IO as cq,ex as cr,w$ as cs,k$ as ct,uI as cu,ef as cv,d$ as cw,j$ as cx,$$ as cy,D$ as cz,Ye as d,_M as d$,o$ as d0,pj as d1,mj as d2,a$ as d3,hj as d4,vi as d5,c$ as d6,Tj as d7,qm as d8,R$ as d9,to as dA,mD as dB,Vj as dC,Zj as dD,Kj as dE,vl as dF,yl as dG,RO as dH,AO as dI,gC as dJ,Wm as dK,_C as dL,Pf as dM,_l as dN,aM as dO,cM as dP,Oj as dQ,Cj as dR,Pj as dS,jj as dT,Mj as dU,o0 as dV,Vo as dW,jO as dX,Vf as dY,al as dZ,DM as d_,p$ as da,h$ as db,f$ as dc,s$ as dd,L$ as de,F$ as df,H$ as dg,W$ as dh,bI as di,U$ as dj,ws as dk,Uo as dl,B$ as dm,G$ as dn,cO as dp,qj as dq,SD as dr,ED as ds,K$ as dt,XC as du,fA as dv,KO as dw,gD as dx,sc as dy,uC as dz,WO as e,Hj as e$,KM as e0,VM as e1,gm as e2,ZR as e3,hi as e4,Sj as e5,Ej as e6,W0 as e7,NM as e8,yM as e9,Xj as eA,zj as eB,C1 as eC,Gm as eD,GO as eE,zO as eF,Kg as eG,kI as eH,YC as eI,Ol as eJ,hD as eK,Jl as eL,ZC as eM,VC as eN,ma as eO,go as eP,Qg as eQ,a_ as eR,h_ as eS,Kk as eT,Lj as eU,ir as eV,$m as eW,Uj as eX,g1 as eY,Pm as eZ,Fj as e_,lR as ea,BR as eb,mm as ec,FR as ed,Lu as ee,_j as ef,N1 as eg,kj as eh,ej as ei,gO as ej,_O as ek,OO as el,wi as em,ki as en,ig as eo,MI as ep,El as eq,BM as er,qp as es,Fs as et,bP as eu,Dn as ev,Jn as ew,Gb as ex,Z$ as ey,Aa as ez,Fy as f,Qw as f$,Gj as f0,CO as f1,MO as f2,ai as f3,Et as f4,Jg as f5,JR as f6,bD as f7,Qj as f8,bl as f9,mM as fA,wr as fB,EO as fC,TO as fD,kO as fE,_P as fF,gP as fG,tP as fH,Uc as fI,Dc as fJ,$n as fK,Jt as fL,ni as fM,J$ as fN,eD as fO,uD as fP,xl as fQ,dT as fR,uT as fS,hg as fT,q$ as fU,Il as fV,jP as fW,$P as fX,$k as fY,Yw as fZ,Kw as f_,Yj as fa,Hm as fb,j1 as fc,ml as fd,bO as fe,hd as ff,gy as fg,vO as fh,Xb as fi,FM as fj,xM as fk,IM as fl,hO as fm,mO as fn,RM as fo,Jh as fp,cA as fq,Ah as fr,og as fs,sh as ft,yy as fu,wO as fv,dM as fw,fM as fx,vM as fy,bM as fz,Pc as g,aP as g$,Rr as g0,PP as g1,OP as g2,AP as g3,vP as g4,yP as g5,kP as g6,wP as g7,ih as g8,TP as g9,FP as gA,UP as gB,BP as gC,HP as gD,WP as gE,tM as gF,Zb as gG,Yb as gH,Qb as gI,Zd as gJ,sP as gK,xP as gL,Ek as gM,oh as gN,Hp as gO,lP as gP,Ic as gQ,gd as gR,Al as gS,wI as gT,C0 as gU,EP as gV,wk as gW,IP as gX,MP as gY,RP as gZ,lw as g_,Z0 as ga,sM as gb,uw as gc,CP as gd,SS as ge,JP as gf,vh as gg,eM as gh,YP as gi,QP as gj,qP as gk,yS as gl,zi as gm,XP as gn,ES as go,KP as gp,NP as gq,GP as gr,nM as gs,DP as gt,zP as gu,ZP as gv,oM as gw,rM as gx,VP as gy,LP as gz,Kf as h,vj as h$,tw as h0,dP as h1,uP as h2,pP as h3,fP as h4,mP as h5,SP as h6,iM as h7,n$ as h8,OM as h9,rP as hA,k0 as hB,Mp as hC,Nc as hD,Tp as hE,c0 as hF,l0 as hG,eP as hH,Wb as hI,qO as hJ,YO as hK,XO as hL,Wd as hM,ZO as hN,VO as hO,JO as hP,Gd as hQ,QO as hR,fp as hS,oP as hT,nP as hU,yj as hV,wM as hW,AM as hX,SM as hY,EM as hZ,bj as h_,TM as ha,wA as hb,MM as hc,CM as hd,PM as he,jM as hf,iP as hg,cP as hh,Oc as hi,wl as hj,z1 as hk,pO as hl,gM as hm,HM as hn,WM as ho,Ga as hp,zM as hq,oA as hr,GM as hs,ZM as ht,vR as hu,YM as hv,Yy as hw,kM as hx,Pp as hy,Oo as hz,fv as i,Pb as i0,md as i1,KC as i2,UM as i3,pv as j,hv as k,mv as l,HC as m,GC as n,m_ as o,lO as p,Bj as q,Hy as r,h1 as s,Vy as t,n_ as u,rO as v,QC as w,ix as x,kt as y,wj as z};
|
|
64
|
+
*/function Bo(){return Bo=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},Bo.apply(this,arguments)}const wl=x.createContext(null),C1=x.createContext(null),lr=x.createContext(null),vi=x.createContext(null),bn=x.createContext({outlet:null,matches:[],isDataRoute:!1}),Km=x.createContext(null);function s$(e,t){let{relative:n}=t===void 0?{}:t;Br()||We(!1);let{basename:r,navigator:o}=x.useContext(lr),{hash:s,pathname:a,search:c}=M1(e,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:On([r,a])),o.createHref({pathname:l,search:c,hash:s})}function Br(){return x.useContext(vi)!=null}function yi(){return Br()||We(!1),x.useContext(vi).location}function Vm(e){x.useContext(lr).static||x.useLayoutEffect(e)}function O1(){let{isDataRoute:e}=x.useContext(bn);return e?z1():P1()}function P1(){Br()||We(!1);let e=x.useContext(wl),{basename:t,future:n,navigator:r}=x.useContext(lr),{matches:o}=x.useContext(bn),{pathname:s}=yi(),a=JSON.stringify(vl(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=yl(d,JSON.parse(a),s,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:On([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,a,s,e])}function i$(){let{matches:e}=x.useContext(bn),t=e[e.length-1];return t?t.params:{}}function M1(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=x.useContext(lr),{matches:o}=x.useContext(bn),{pathname:s}=yi(),a=JSON.stringify(vl(o,r.v7_relativeSplatPath));return x.useMemo(()=>yl(e,JSON.parse(a),s,n==="path"),[e,a,s,n])}function j1(e,t){return $1(e,t)}function $1(e,t,n,r){Br()||We(!1);let{navigator:o,static:s}=x.useContext(lr),{matches:a}=x.useContext(bn),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=yi(),f;if(t){var h;let p=typeof t=="string"?cr(t):t;d==="/"||(h=p.pathname)!=null&&h.startsWith(d)||We(!1),f=p}else f=u;let m=f.pathname||"/",y=m;if(d!=="/"){let p=d.replace(/^\//,"").split("/");y="/"+m.replace(/^\//,"").split("/").slice(p.length).join("/")}let b=a1(e,{pathname:y}),v=U1(b&&b.map(p=>Object.assign({},p,{params:Object.assign({},l,p.params),pathname:On([d,o.encodeLocation?o.encodeLocation(p.pathname).pathname:p.pathname]),pathnameBase:p.pathnameBase==="/"?d:On([d,o.encodeLocation?o.encodeLocation(p.pathnameBase).pathname:p.pathnameBase])})),a,n,r);return t&&v?x.createElement(vi.Provider,{value:{location:Bo({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:Tn.Pop}},v):v}function D1(){let e=G1(),t=I1(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 N1=x.createElement(D1,null);class L1 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(bn.Provider,{value:this.props.routeContext},x.createElement(Km.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function F1(e){let{routeContext:t,match:n,children:r}=e,o=x.useContext(wl);return o&&o.static&&o.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(o.staticContext._deepestRenderedBoundaryId=n.route.id),x.createElement(bn.Provider,{value:t},r)}function U1(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,y=f.route.loader&&h[f.route.id]===void 0&&(!m||m[f.route.id]===void 0);if(f.route.lazy||y){l=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}return a.reduceRight((u,f,h)=>{let m,y=!1,b=null,v=null;n&&(m=c&&f.route.id?c[f.route.id]:void 0,b=f.route.errorElement||N1,l&&(d<0&&h===0?(K1("route-fallback"),y=!0,v=null):d===h&&(y=!0,v=f.route.hydrateFallbackElement||null)));let p=t.concat(a.slice(0,h+1)),E=()=>{let k;return m?k=b:y?k=v:f.route.Component?k=x.createElement(f.route.Component,null):f.route.element?k=f.route.element:k=u,x.createElement(F1,{match:f,routeContext:{outlet:u,matches:p,isDataRoute:n!=null},children:k})};return n&&(f.route.ErrorBoundary||f.route.errorElement||h===0)?x.createElement(L1,{location:n.location,revalidation:n.revalidation,component:b,error:m,children:E(),routeContext:{outlet:null,matches:p,isDataRoute:!0}}):E()},null)}var Zm=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Zm||{}),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 B1(e){let t=x.useContext(wl);return t||We(!1),t}function H1(e){let t=x.useContext(C1);return t||We(!1),t}function W1(e){let t=x.useContext(bn);return t||We(!1),t}function Jm(e){let t=W1(),n=t.matches[t.matches.length-1];return n.route.id||We(!1),n.route.id}function G1(){var e;let t=x.useContext(Km),n=H1(),r=Jm();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function z1(){let{router:e}=B1(Zm.UseNavigateStable),t=Jm(Ym.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,Bo({fromRouteId:t},s)))},[e,t])}const af={};function K1(e,t,n){af[e]||(af[e]=!0)}function a$(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function c$(e){let{to:t,replace:n,state:r,relative:o}=e;Br()||We(!1);let{future:s,static:a}=x.useContext(lr),{matches:c}=x.useContext(bn),{pathname:l}=yi(),d=O1(),u=yl(t,vl(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 V1(e){We(!1)}function l$(e){let{basename:t="/",children:n=null,location:r,navigationType:o=Tn.Pop,navigator:s,static:a=!1,future:c}=e;Br()&&We(!1);let l=t.replace(/^\/*/,"/"),d=x.useMemo(()=>({basename:l,navigator:s,static:a,future:Bo({v7_relativeSplatPath:!1},c)}),[l,c,s,a]);typeof r=="string"&&(r=cr(r));let{pathname:u="/",search:f="",hash:h="",state:m=null,key:y="default"}=r,b=x.useMemo(()=>{let v=Gm(u,l);return v==null?null:{location:{pathname:v,search:f,hash:h,state:m,key:y},navigationType:o}},[l,u,f,h,m,y,o]);return b==null?null:x.createElement(lr.Provider,{value:d},x.createElement(vi.Provider,{children:n,value:b}))}function d$(e){let{children:t,location:n}=e;return j1(uc(t),n)}new Promise(()=>{});function uc(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,uc(r.props.children,s));return}r.type!==V1&&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=uc(r.props.children,s)),n.push(a)}),n}const wi=260,kl=220,Sl=320,Xm=56,El=480,u$=8,Al=44,Rl=400,Qm=1200;function xl(e){return Math.max(0,Math.min(Qm,e-El))}function fc(e){return xl(e)>=Rl?"docked":"overlay"}const Z1=48,Y1=16;function f$(e,t){if(fc(e)==="docked")return{mode:"docked",width:Math.min(t,xl(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,Rl),e-Z1));return e-n>=Y1?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function p$({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 J1(e,t=wi,n=Al){return fc(e-qm(t)-n)==="overlay"&&fc(e-Xm-n)==="docked"}function qm(e){return Number.isNaN(e)?wi:Math.min(Sl,Math.max(kl,e))}function X1(e,t=Al){return Math.max(0,Math.min(Sl,e-El-t))}function h$(e,t,n=wi,r=!1,o=Al){const s=!t&&r&&J1(e,n,o),a=t||s,c=X1(e,o);return{mode:a?"strip":"docked",width:a?Xm:Math.min(qm(n),c),collapsed:a,resizable:!a&&c>=kl}}function m$(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const g$=e=>e?"⌘B":"Ctrl+B",Q1="data-canvas-shortcuts",q1=`[${Q1}]`,eI=e=>eg(e,q1),tI='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',_$=e=>eg(e,tI);function eg(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const b$=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&eI(e.target)?"new-file":null},tg="small",nI=["small","medium","large"],ng="before:absolute before:-inset-0.5 before:content-['']",rI={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:ng},medium:{px:28,className:"size-7",glyphClassName:"size-3.5",hitClassName:""},large:{px:36,className:"size-9",glyphClassName:"size-4",hitClassName:""}},oI={small:{px:4,className:"mb-1"},medium:{px:6,className:"mb-1.5"},large:{px:8,className:"mb-2"}},v$={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:ng,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 y$(e){for(const t of nI)if(e===t)return t;return tg}function w$(e){return rI[e].px+oI[e].px}const rg="delegating",bs=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,ha=e=>Math.max(1,Math.floor(e)),sI=e=>e===rg,og=e=>e.locality==="remote"&&e.link_down===!0||e.peer_reach==="not-attempted"||e.peer_reach==="unknown";function Il(e){return og(e)?!1:typeof e.background_work=="boolean"?e.background_work:e.status?.code===rg}const iI=Intl.ListFormat;let ma=null;const aI=e=>{const t=_n();return ma?.tag!==t&&(ma={tag:t,format:new iI(t,{type:"conjunction",style:"narrow"})}),ma.format.format(e)};function k$(e){if(og(e))return"";const t=Il(e);if(!t&&typeof e.background_work=="boolean")return"";const n=!sI(e.status?.code),r=[];n&&bs(e.subagents_running)&&r.push(_("ui.chat.sidebar.row.bg.subagents",{count:ha(e.subagents_running)})),t&&bs(e.jobs_running)&&r.push(_("ui.chat.sidebar.row.bg.jobs",{count:ha(e.jobs_running)}));const o=[];if(r.length>0&&o.push(_("ui.chat.sidebar.row.bg.running",{items:aI(r)})),n&&bs(e.subagents_queued)){const s=ha(e.subagents_queued);o.push(r.length>0?_("ui.chat.sidebar.row.bg.queued",{count:s}):_("ui.chat.sidebar.row.bg.subagents_queued",{count:s}))}return t&&o.length===0&&e.status?.code!=="waiting"&&bs(e.waiting_on)&&o.push(_("ui.chat.sidebar.row.bg.waiting")),o.join(" · ")}const cI=new Set(["idle","recent"]);function S$(e,t){return t!==""&&cI.has(e.status?.code??"recent")&&Il(e)}const lI=["active","created"],E$={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"},dI=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function ki(e){return dI.has(e.status?.code??"")||Il(e)}const uI=new Set(["approval","answer"]);function sg(e){return uI.has(e.status?.code??"")}const fI=24*60*60*1e3,pI=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function Tl(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 hI="last_user_at";function mI(e){const t=e[hI],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 gI(e,t,n){if(ki(e))return"running";const r=Tl(e,n);if(r===null)return"older";const o=pI(t);return r>=o?"today":r>=o-6*fI?"week":"older"}function A$(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const o of e)r[gI(o,t,n)].push(o);return r}function ig(e,t,n){const r=Tl(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 R$(e,t,n){const r=ig(e,t,n);return r?_("ui.chat.sidebar_view.relative_short",r):""}function x$(e,t,n){const r=ig(e,t,n);return r?n==="created"?_("ui.chat.sidebar_view.relative_created",r):_("ui.chat.sidebar_view.relative_active",r):""}const pc=["pinned","running","today","week","older","agents","teams"],I$={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 T$(e){return e==="agents"||e==="teams"}const Ho=8;function _I(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function C$(e,t){return{...e,[t]:(e[t]??Ho)+Ho}}function O$(e,t,n,r,o){const s=!(e[n]??r);return{expanded:{...e,[n]:s},caps:!s&&!o?_I(t,n):t}}function ag(e){return`tag:${e}`}function cg(e,t){return e[ag(t)]===!1}function P$(e,t){const n=ag(t);if(cg(e,t)){const{[n]:r,...o}=e;return o}return{...e,[n]:!1}}function M$(e,t,n){return cg(t,n)?[]:e}function j$(e,t,n,r){return(e||t!=="")&&(r>Ho||n.trim()!=="")}const $$="Collapse, then reopen, to restore the compact list";function D$(e){return(e??Ho)>Ho}const N$=e=>`section-grown-hint-${e}`,L$=e=>_("ui.chat.sidebar.catalogue.show_more",{hidden:e});function F$(e,t){return t==="agents"?_("ui.chat.sidebar.catalogue.show_more_agents",{count:e}):_("ui.chat.sidebar.catalogue.show_more_teams",{count:e})}function U$(e,t){return e.groupBy==="tag"&&!t?"section":e.groupBy}function B$(e){return e.tagsEnabled||e.groupBy==="tag"}const yr={hidden:[],order:[...pc],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},bI=10,eo=[25,50],vI=50,yI=500,wI=64,kI=2;function H$(e){return e.groupBy==="tag"?Math.max(e.loads,kI):e.loads}function Pr(e){const t=Math.max(0,Math.floor(e));return t===0?bI:t<=eo.length?eo[t-1]:eo[eo.length-1]+(t-eo.length)*vI}function W$(e,t){const n=Pr(e+1)-Pr(e),r=Math.max(0,Math.min(n,t));return _("ui.chat.sidebar.catalogue.show_more_chats",{add:r})}function G$(e,t,n){const r=Pr(t+1)-Pr(t),o=Pr(t),s=Math.min(o+r,e.length);let a=0;for(let l=o;l<s;l+=1)Si(e[l])&&(a+=1);const c=Math.max(0,s-o-a);return c>0?c:Math.max(0,Math.min(r,n))}function z$(e,t){if(!t)return null;const n=e.filter(r=>Si(r));return n.length===0?null:{row:n.find(r=>sg(r))??n[0],count:n.length}}function Si(e){return ki(e)}function SI(e){return sg(e)?0:ki(e)?1:2}function EI(e,t){return ki(e)?mI(e):Tl(e,t)}function AI(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function K$(e,t,n){const r=e.map((o,s)=>({row:o,index:s,lane:t==="active-first"?SI(o):0,at:EI(o,n)}));return r.sort((o,s)=>o.lane-s.lane||AI(o.at,s.at)||o.index-s.index),r.map(o=>o.row)}function V$(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}Si(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 Z$(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=Pr(t.loads),r=[];let o=n;for(const l of e){if(Si(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 Y$(e){if(e.add<=0)return null;const t=_("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 RI="mt-4",xI="mt-2";function J$(e){return e?RI:xI}function X$(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function Q$(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 II(e,t){return!e.hidden.includes(t)}function lg(e){return e.order.filter(t=>II(e,t))}function q$(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function eD(e,t,n){const r=lg(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 TI=["running","today","week","older"];function cf(e){return TI.includes(e)}function tD(e,t,n,r){if(!cf(t)||r&&!r(t))return!1;const o=lg(e),s=o.indexOf(t);if(s<0)return!1;const a=o[s+n];return a===void 0||!cf(a)?!1:r?r(a):!0}const CI=["section","tag","agent","flat"],OI=["active-first","recent"];function nD(e){if(typeof e!="object"||e===null)return yr;const t=e,n=new Set(pc),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 pc)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=CI.includes(t.groupBy)?t.groupBy:yr.groupBy,a=lI.includes(t.basis)?t.basis:yr.basis,c=OI.includes(t.orderBy)?t.orderBy:yr.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(yI,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>=wI)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:yr.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const dg={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},PI=["recent","name","kind","modified","created","size"],MI=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function Cl(e){const t=e&&typeof e=="object"?e:{};return{sort:PI.includes(t.sort??"")?t.sort:dg.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=>[Wo,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>MI.includes(n)))]:[]}}const Wo="Attachments";function rD(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 jI=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 oD(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:Wo,label:_("ui.canvas.files.attachments"),items:o,open:n||!r.has(Wo),highlights:!1}),s.length&&c.push({id:"Highlights",label:_("ui.canvas.finder_layout.highlights"),items:s,open:n||!r.has("Highlights"),highlights:!0}),s.length&&a.length&&(c.push({id:"Working files",label:_("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:_("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=>jI(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const $I=32,sD=4,ug=32,fg=18;function iD(e){return e.height-ug-(e.kind==="tiles"&&e.section.id===Wo?fg:0)}function aD(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((y,b)=>o.set(y.row.document.id,{band:r.length,column:b})),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",$I,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(d.id===Wo){const u=d.items.filter(y=>y.row.media!=="image"),f=d.items.filter(y=>y.row.media==="image");for(const y of u)l(d,"compact",36,[y]);const h=(s-4*(a-1))/a,m=Math.round((h-8)*3/4)+ug+fg;for(let y=0;y<f.length;y+=a)l(d,"tiles",m,f.slice(y,y+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 cD(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 lD(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 DI="both",pg="by-turn",hc=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function dD(e){for(const t of hc)if(e===t.value)return t.value;return pg}function uD(e){return hc.find(t=>t.value===e)?.label??hc[0].label}const fD="primary+alt+shift+space",NI=/^f([1-9]|1[0-9]|2[0-4])$/;function LI(e){return NI.test(e)}function FI(e,t){const n=UI(e,t);return t==="mac"?n.join(""):n.join("+")}function UI(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]:LI(s)||s.length===1?s.toUpperCase():s)}const Ei=[{id:"panel.console",get label(){return _("ui.settings.shortcuts.action.open_console")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return _("ui.settings.shortcuts.action.open_canvas")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return _("ui.settings.shortcuts.action.open_run_details")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return _("ui.settings.shortcuts.action.open_asks")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return _("ui.settings.shortcuts.action.open_browser")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return _("ui.settings.shortcuts.action.open_code_review")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],BI=new Map(Ei.map(e=>[e.id,e])),HI=e=>BI.get(e),WI=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 GI 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 Ol=new GI([["primary+p",()=>_("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>_("ui.settings.shortcuts.reserved.palette_commands")],["primary+k",()=>_("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>_("ui.settings.shortcuts.reserved.new_chat")],["primary+b",()=>_("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>_("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>_("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>_("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>_("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>_("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>_("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>_("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>_("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>_("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>_("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>_("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>_("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>_("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>_("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>_("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>_("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>_("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>_("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>_("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>_("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>_("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>_("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>_("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>_("ui.settings.shortcuts.reserved.browser_last_tab"):()=>_("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>_("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>_("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>_("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>_("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>_("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>_("ui.settings.shortcuts.reserved.close")],["primary+m",()=>_("ui.settings.shortcuts.reserved.minimise")]]),zI=["primary","alt","shift"],KI={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},VI=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),ZI=e=>VI.has(e)||/^[a-z0-9]$/.test(e);function Pl(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(!ZI(n))return null;const r=new Set;for(const s of t.slice(0,-1)){const a=KI[s];if(a===void 0)return null;r.add(a)}return[...zI.filter(s=>r.has(s)),n].join("+")}const hg=e=>e.split("+").includes("primary");function Ai(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!Ol.has(n)?n:HI(e)?.defaultChord??null}function pD(e){const t=new Map;for(const n of Ei){const r=Ai(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const YI=e=>e==="mac"?_("ui.settings.shortcuts.capture.needs_modifier_mac"):_("ui.settings.shortcuts.capture.needs_modifier");function JI(e,t,n,r="linux",o=new Map){const s=e===null?null:Pl(e);if(s===null)return _("ui.settings.shortcuts.capture.unbindable");if(!hg(s))return YI(r);const a=Ol.get(s);if(a!==void 0)return a;const c=o.get(s);if(c!==void 0)return _("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of Ei)if(l.id!==t&&Ai(l.id,n)===s)return _("ui.settings.shortcuts.capture.already_assigned",{label:l.label});return null}function XI(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const o of Ei){const s=t[o.id];if(s===null){r[o.id]=null;continue}const a=typeof s=="string"?Pl(s):null,c=a!==null&&WI.has(a),l=a!==null&&hg(a)&&(c||!Ol.has(a)&&!n.has(a))?a:null;l!==null&&(r[o.id]=l);const d=Ai(o.id,r);d!==null&&n.add(d)}return r}function hD(e,t,n){const r=Ai(e,t);return r===null?null:mg(r,n)}function mg(e,t){return FI(e,t)}function mD(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:mg(e,t),aria:[...o,r.length===1?r.toUpperCase():r].join("+")}}const lf=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)})},gg=Object.freeze([lf({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"}),lf({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"})]),gD=e=>gg.some(t=>t.role===e||t.variants.includes(e)),je={strongText:7,text:4.5,nonText:3},df=new Set(["inkDisabled"]),He=["canvas","surface","elevated","sunken"],_g=[["ink",je.strongText],["inkMuted",5.5],["inkDim",5]],un=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Vt={dark:{canvasMin:9,canvasMax:15,elevatedMax:22},light:{canvasMax:94,sunkenMin:80}},Rn={canvasSurface:[2.5,5],surfaceElevated:[2,6],canvasSunken:[1.5,6]},QI=2,qI=1.03,Ml=8,ti=2,uf=.8,ff=3,pf=2,hf=4,mc=2.5,mf=4,gf=2.5,_f=2,bf=2,eT=[{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}],tT=[{name:"context wheel arc against its track",a:["info","warning","danger"],b:"sunken",floor:je.nonText}],nT=[{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"}],rT=[{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}],oT=["borderControl","accent","successBorder","warningBorder","dangerBorder","infoBorder"],sT=["accent","success","warning","danger","info"],iT=[{fg:"surface",on:"accent",floor:je.text,name:"the console terminal's cursor ink on its own cursor (9.1)"}],aT=[],cT=[{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"}],wr=15,kr=8,lT=[{theme:"catppuccinMocha",a:"accentAlt",b:"info",floor:wr,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:wr,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:wr,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:wr,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:wr,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:kr,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:kr,got:0,why:"`info` IS `accent` (`#00EFFF`), the palette's single cyan"},{theme:"obsidian",a:"info",b:"accent",floor:kr,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:kr,got:0,why:"`info` IS `accent` (`#91B7E9`), the palette's single steel blue"},{theme:"githubLight",a:"info",b:"accent",floor:kr,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"}],dT=[],uT=[],fT=["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"],vs=["success","warning","danger","info"],pT=["success","warning","danger","info","ink"],Rr=8,to="tokenCommand",ys=Rr,hT=["surface","elevated","messageSurface"],mT=[{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."}],an=15,Go=15,bo=Rr,it=2,vf=4,gT=.75,yf=.12,_T=[["surface","canvas"],["surface","elevated"],["elevated","canvas"]],bT=4,vT=2,yT=2,ga=1,ni=2,_a=2,wf=.5,wT=1.5,kT=1.5,bg=5,ri=2.5,vg=.5,oi=5,gc=4,_c=24,kf=12,ST=.45,Sf=.75,ET=.25,fn=2,yg=2,AT=[{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"}],RT=[{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"}],bc=10,ws="surface",Ef=2,Af=1.15,xT=({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=cT.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=lT.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}`,y=[],b=R=>{n.failures++,y.push(`FAIL ${R}`)},v=new Set,p=(R,g,w,S)=>{const I=aT.find(F=>F.theme===R&&F.fg===g&&F.bg===w&&o(F.got,S));return I&&v.add(I),I};return Object.assign(n,{readings:r,pinMatches:o,ledgerHolds:s,log:y,fail:b,exceptionSeen:v,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)||b(`${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&&b(`${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}b(`${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)=>AT.find(S=>S.id===R&&S.role===g)??null,shortfallPin:(R,g,w)=>RT.find(I=>I.id===R&&I.role===g&&I.bound===w)??null}),n},IT=(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:y,ledgerHolds:b}=e;for(const{id:v,palette:p}of[t]){for(const g of fT)e.assertions++,g in p||n(`${v}: missing required role \`${g}\``);for(const[g,w]of _g)if(!df.has(g))for(const S of un)r(v,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(`${v}: 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(ri,vg*g),castCeiling:g=>Math.max(g,ri),stepFloor:wT,stepCeiling:null},{role:"rowSelected",castFloor:g=>Math.max(oi,g),castCeiling:g=>Math.min(Math.max(g+gc,oi),_c),stepFloor:kT,stepCeiling:bg}];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),De=g.castCeiling(me),Ge=me<fn;e.assertions++;const et=me>=fn?{name:"the panel's",hue:Math.atan2(V,T)}:z>=yg?{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>=fn&&Te>kf&&n(`${v}: \`${w}\` ${S} sits ${L(Te)} degrees off ${et.name} hue (the limit is ${kf}) — 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>De+1e-9?(d.add(`${v}:${w}:floor`),e.assertions++,c(v,w)||n(`${v}: \`${w}\` ${S} carries C* ${L(oe)}, and its cast floor ${L(Me)} 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 \`${v}\`'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-Sf&&n(`${v}: \`${w}\` ${S} carries C* ${L(oe)} where its cast floor ${L(Me)} 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<Me-ST&&n(`${v}: \`${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>De+Sf&&n(`${v}: \`${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 ${gc} above it, and no more`}, and the flat cap is ${_c}. 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 Rt=I-ne,Ne=p.mode==="dark"?Rt:-Rt;if(Ne<g.stepFloor-1e-9&&n(`${v}: \`${w}\` ${S} sits ${L(Math.abs(Rt))} \`L*\` ${p.mode==="dark"?"above":"below"} \`surface\` ${p.surface}, so the step is ${p.mode==="dark"?"LIGHTER":"DARKER"}-by-${L(Ne)} 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++,Ne>g.stepCeiling+ET+1e-9&&n(`${v}: \`${w}\` ${S} sits ${L(Ne)} \`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),jt=p.mode==="dark"?Ae-ne:ne-Ae,Hr=Math.hypot(ut,gt);if(e.assertions++,Ne<jt+ga-1e-9){const dr=l(v,"rowSelected","rank");d.add(`${v}:rowSelected:rank`),e.assertions++,dr?b(dr.measured,Ne-jt,.05)||n(`${v}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${dr.measured} and the pair now ranks ${L(Ne-jt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${v}: \`rowSelected\` ${S} is ${L(Ne)} \`L*\` from \`surface\` where \`rowHover\` ${p.rowHover} is ${L(jt)} — the selection has to be at least ${ga} \`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(v,"rowSelected","rank")&&n(`${v}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — the pair ranks ${L(Ne-jt)} \`L*\`, clear of the ${ga} the row claims it misses. Remove the row`);e.assertions++,oe<Hr+ni-1e-9&&n(`${v}: \`rowSelected\` ${S} carries C* ${L(oe)} where \`rowHover\` ${p.rowHover} carries ${L(Hr)} — the selection has to carry at least ${ni} 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++,jt<wf*Ne-1e-9&&n(`${v}: \`rowHover\` ${p.rowHover} takes ${L(jt)} \`L*\` of the ${L(Ne)} the selection takes (${Math.round(jt/Ne*100)}%), under the ${Math.round(wf*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 Mt=de(S,p.surface);if(Mt<it-1e-9){const Ae=l(v,w,"band");d.add(`${v}:${w}:band`),e.assertions++,Ae?b(Ae.measured,Mt,.05)||n(`${v}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Ae.measured} and the palette now measures ${L(Mt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${v}: \`${w}\` ${S} is ΔE00 ${L(Mt)} 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(v,w,"band")&&n(`${v}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${L(Mt)} 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<_a){const Ae=l(v,w,"wash");d.add(`${v}:${w}:wash`),e.assertions++,Ae?b(Ae.measured,ye,.05)||n(`${v}: 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(`${v}: \`${w}\` ${S} is ΔE00 ${L(ye)} from \`accentWash\` ${p.accentWash} (need ${_a}) — 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(v,w,"wash")&&n(`${v}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${L(ye)} from \`accentWash\`, clear of the ${_a} 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=yT;g<w-1e-9&&n(`${v}: \`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(`${v}: 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 un){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(`${v}: 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 oT)for(const w of He)r(v,p,g,w,je.nonText,"structural edge");const k=[...He,"accentWash","messageSurface"];for(const g of sT)for(const w of k)r(v,p,g,w,je.text,"colour as text");r(v,p,"warning","elevated",je.text,"the picker's partial-listing note"),r(v,p,"danger","elevated",je.text,"danger as text on a dialog's ground"),r(v,p,"warning","rowSelected",je.text,"integration status text on a deep-linked row"),r(v,p,"accent","warningWash",je.text,"model-access band links on the warning wash"),r(v,p,"warning","rowHover",je.text,"the partial delivery word on the hovered row's ground"),r(v,p,"dangerBorder","elevated",je.nonText,"the danger control's only edge on a dialog's ground");for(const g of eT)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&&!df.has(g.ink)&&!s(v,g.ink,g.fill??w,ne)&&n(`${v}: ${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=uT.find(z=>z.control===g.name&&z.ground===w&&z.theme===v&&y(z.got,L(Z)));_e?h.add(m(_e.control,_e.ground,_e.theme)):n(`${v}: ${g.name} on ${w} has no perceivable edge — fill ${T}:1, border ${V}:1, need one at ${je.nonText}:1`)}}}for(const g of iT)r(v,p,g.fg,g.on,g.floor,g.name);for(const g of nT)for(const w of g.on)r(v,p,g.fg,w,g.floor??je.nonText,g.name);for(const g of tT){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(v,S,g.b,F)&&n(`${v}: ${g.name} — ${S} ${I} against ${g.b} ${w} = ${F}:1, need ${g.floor}:1`)}}for(const g of rT){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(v,g.role,T,L(V))&&n(`${v}: ${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(`${v}: ${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<vs.length;g++)for(let w=g+1;w<vs.length;w++){const[S,I]=[vs[g],vs[w]];if(!W(p[S])||!W(p[I]))continue;e.assertions++;const F=de(p[S],p[I]);F<an&&n(`${v}: \`${S}\` ${p[S]} and \`${I}\` ${p[I]} are too close to tell apart (ΔE00 ${L(F)}, need ${an}) — 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<an&&n(`${v}: the second accent \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(I)} from \`accent\` ${p.accent} (need ${an}) — 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<an&&n(`${v}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(F)} from \`${I}\` ${p[I]} (need ${an}) — 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<Rr&&n(`${v}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(I)} from \`info\` ${p.info} (need ${Rr}) — \`info\` is the family the port mapped the TUI's \`signal\` onto, so the floor here is the reduced one and not ${an}; below it the two take the same name`)}const[,g,w]=ie(p.accentAlt),S=Math.hypot(g,w);e.assertions++,S<Go&&n(`${v}: \`accentAlt\` ${p.accentAlt} is C* ${L(S)} (need ${Go}) — 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(v,p,"accentAlt",I,je.text,"second accent as text");r(v,p,"accentAlt","elevated",je.text,"second accent as text on a row's state ground")}if(o(v,p,"accentAlt","info",wr,"the tool row's two category inks"),o(v,p,"info","accent",kr,"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(`${v}: \`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 pT){if(!W(p[g])||!W(p.inkDim))continue;e.assertions++;const w=de(p[g],p.inkDim);w<Rr&&n(`${v}: syntax \`${g}\` ${p[g]} sits at ΔE00 ${L(w)} from comment \`${p.inkDim}\` (need ${Rr}) — a token the eye cannot separate from the comment beside it is not highlighted`)}if(W(p[to])&&W(p.ink)){const g=mT.find(w=>w.theme===v);for(const w of hT){if(!W(p[w]))continue;e.assertions++;const S=se(p[to],p[w]);S<4.5&&n(`${v}: the command token \`tokenCommand\` ${p[to]} 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[to],p[w]);if(!!g?.against.includes(w)){y(g.got,S)||n(`${v}: 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<ys&&n(`${v}: the command token \`tokenCommand\` ${p[to]} sits at ΔE00 ${L(S)} from \`${w}\` ${p[w]} (need ${ys}) - 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<ys&&n(`${v}: the roster NAME's ink \`success\` ${p.success} sits at ΔE00 ${L(w)} from prose \`ink\` ${p.ink} (need ${ys}) - a resolved name that reads as prose is not a run`)}}if(W(p.inkMuted)&&W(p.inkDim)){e.assertions++,u.add(v);const g=de(p.inkMuted,p.inkDim),w=dT.find(S=>S.theme===v);w&&f.add(w),g<bo?w?y(w.got,g)||n(`${v}: 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(`${v}: the control ink \`inkMuted\` ${p.inkMuted} sits at ΔE00 ${L(g)} from the readout ink \`inkDim\` ${p.inkDim} (need ${bo}) - a chip that opens cannot be told from a reading that does not`):w&&!e.composed&&n(`${v}: the ink step is pinned at ${w.got} but now measures ${L(g)}, clearing the ${bo} 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",bT]]){if(!W(p[g])||!W(p[w]))continue;e.assertions++;const I=de(p[g],p[w]);I<S&&n(`${v}: 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<Vt.dark.canvasMin||g>Vt.dark.canvasMax)&&n(`${v}: dark \`canvas\` ${p.canvas} sits at L* ${L(g)} — the band is [${Vt.dark.canvasMin}, ${Vt.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>Vt.dark.elevatedMax&&n(`${v}: dark \`elevated\` ${p.elevated} sits at L* ${L(S)} — the ceiling is L* ${Vt.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>Vt.light.canvasMax&&n(`${v}: light \`canvas\` ${p.canvas} sits at L* ${L(g)} — the ceiling is L* ${Vt.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<Vt.light.sunkenMin&&n(`${v}: light \`sunken\` ${p.sunken} sits at L* ${L(I)} — the floor is L* ${Vt.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",Rn.canvasSurface,w-g],["surface -> elevated","surface","elevated",Rn.surfaceElevated,S-w],["canvas -> sunken","canvas","sunken",Rn.canvasSunken,g-I]])if(e.assertions++,(_e<V-1e-9||_e>Z+1e-9)&&n(`${v}: 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(v,p,ne,T,qI,`${$} step`),ne==="canvas"&&T==="sunken"||ne==="surface"&&T==="elevated"){e.assertions++;const z=de(p[ne],p[T]),me=ne==="canvas"?QI:vT;z<me&&n(ne==="canvas"?`${v}: \`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`:`${v}: \`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(v,p,"ink","canvas",Ml,"the transcript's body ink");for(const g of un){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>uf*S+1e-9&&n(`${v}: \`inkDisabled\` on ${g} measures ${L(w)}:1 against \`inkDim\`'s ${L(S)}:1 — a factor of ${L(w/S)}, over the ${uf} 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<ti&&n(`${v}: \`${w}\` and \`${g}\` are ΔE00 ${L(S)} apart (need ${ti}) — 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<ff&&n(`${v}: the palette/picker active row (\`sunken\` ${p.sunken}) is ΔE00 ${L(g)} from the dialog ground it is painted on (\`elevated\` ${p.elevated}), need ${ff} — 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<pf&&n(`${v}: the palette/picker active row sits ${L(w)} L* from \`elevated\`, under the ${pf} 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(`${v}: 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<hf&&n(`${v}: the user message block's fill \`messageSurface\` ${p.messageSurface} is ΔE00 ${L(g)} from \`canvas\` ${p.canvas} (need ${hf}) — 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<mc&&n(`${v}: the user message block's fill sits ${L(w)} L* from \`canvas\`, under the ${mc} 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(`${v}: 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<mf&&n(`${v}: the media tile's fill \`mediaSurface\` ${p.mediaSurface} is ΔE00 ${L(g)} from \`canvas\` ${p.canvas} (need ${mf}) — 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<gf&&n(`${v}: the media tile's fill sits ${L(w)} L* from \`canvas\`, under the ${gf} 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<_f&&n(`${v}: the accent wash on ${g} is ΔE00 ${L(w)} (need ${_f}) — 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<bf&&n(`${v}: the keycap's ground \`sunken\` ${p.sunken} is ΔE00 ${L(w)} from ${g} ${p[g]} (need ${bf}) — 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[ws])){e.assertions++;const g=de(p.chartBarHover,p.accent);g<bc&&n(`${v}: \`chartBarHover\` ${p.chartBarHover} is ΔE00 ${L(g)} from \`accent\` ${p.accent}, need ${bc} — 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[ws]),S=se(p.accent,p[ws]);w<S&&n(`${v}: \`chartBarHover\` is ${L(w)}:1 on ${ws} 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<vf&&n(`${v}: \`hairline\` on \`${g}\` is ΔE00 ${L(w)} (need ${vf}) — 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<Af&&n(`${v}: \`hairline\` on \`${g}\` is ${L(S)}:1 (need ${Af}) — its ΔE00 is carried in chroma, which a 1px line does not survive`),e.assertions++,S>Ef&&n(`${v}: \`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 _T){if(!W(p.hairline)||!W(p[g])||!W(p[w]))continue;const S=ef(p.hairline,p[g],gT);e.assertions++;const I=de(S,p[g]);I<it&&n(`${v}: 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(`${v}: 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=ef(p.accent,p.surface,yf);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(`${v}: ${S} — ${g} ${I} on the arrival band ${C} (accent ${yf} over surface) = ${F}:1, need ${w}:1`)}const N=se(C,p.surface),O=se(p.rowHover,p.surface),R=se(p.rowSelected,p.surface);e.assertions+=2,N<=O&&n(`${v}: the arrival band is ${L(N)}: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`),N<=R&&n(`${v}: the arrival band is ${L(N)}: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`)}},TT=Object.freeze({soft:-100,gentle:-50,standard:0,strong:50,high:100}),CT=Object.freeze({dark:Object.freeze({high:5,soft:20}),light:Object.freeze({high:97,soft:89})}),OT=["canvas","surface","elevated","sunken","messageSurface","mediaSurface","rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash","hairline","hairlineStrong","inkDisabled"],PT=new Set(["rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash"]),Ts=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Tt=Ts.slice(0,4),no=[...Tt,"accentWash","messageSurface"],ba={ink:[Ts,7],inkMuted:[Ts,5.5],inkDim:[Ts,5],borderControl:[Tt,3],accent:[[...no,"warningWash"],4.5],accentHover:[Tt,4.5],accentActive:[Tt,4.5],tokenCommand:[["surface","elevated","messageSurface"],4.5],accentAlt:[Tt,4.5],success:[no,4.5],warning:[[...no,"rowSelected","rowHover"],4.5],danger:[no,4.5],info:[no,4.5],successBorder:[Tt,3],warningBorder:[Tt,3],dangerBorder:[Tt,3],infoBorder:[Tt,3],chartBarHover:[["surface"],3]},Ot=.05,Rf=.3,xf=4.1,MT=.06,jT=/^#[0-9A-Fa-f]{6}$/,ot=e=>typeof e=="string"&&jT.test(e),Bt=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=ei([r,t*o,n*o]);if(s)return s}return ei([r,0,0])},nr=(e,t,n)=>Math.min(...n.filter(r=>ot(e[r])).map(r=>se(t,e[r]))),vc=(e,t,n,r,o=()=>!0)=>{const s=e[t];if(!ot(s)||nr(e,s,n)>=r+Ot&&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(nr(e,f,n)>=r+Ot&&o(f))return f}return s},jl=(e,t)=>{const n=t.filter(ot).map(Bt),r=n.find(o=>se(o,e)>=4.5);return r||[...n].sort((o,s)=>se(s,e)-se(o,e))[0]},ks=e=>1+.015*(e-50)**2/Math.sqrt(20+(e-50)**2),rr=e=>{const[,t,n]=ie(e);return Math.hypot(t,n)},If=(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)},$T=e=>{if(!ot(e.rowHover)||!ot(e.rowSelected))return;LT(e);const t=rr(e.surface),n=Math.max(ri,vg*t),r=Math.max(t,ri),o=Math.max(oi,t),s=Math.min(Math.max(t+gc,oi),_c),a=(f,h,m)=>Math.min(Math.max(f,h),m),c=rr(e.rowHover),l=rr(e.rowSelected);if(c>=n&&c<=r&&l>=o&&l<=s&&l>=c+ni)return;const d=a(c,n+.1,r-.1),u=a(Math.max(l,d+ni+.2),o+.1,s-.1);e.rowHover=If(e.rowHover,d),e.rowSelected=If(e.rowSelected,u)},DT=6,NT=e=>{const[,t,n]=ie(e);return Math.atan2(n,t)},LT=e=>{const n=rr(e.surface)>=fn?e.surface:rr(e.accent)>=yg?e.accent:e.surface,r=NT(n);for(const o of["rowHover","rowSelected"]){const[s,a,c]=ie(e[o]),l=Math.hypot(a,c);l<fn||Math.abs(((Math.atan2(c,a)-r)*180/Math.PI+540)%360-180)<=DT||(e[o]=ct(s,l*Math.cos(r),l*Math.sin(r)))}},FT=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=>nr(e,m,o)>=s+Ot&&(!a||de(m,e[a])>=c+Ot)&&(r!=="ink"||se(m,e.canvas)>=Ml+Ot);if(d(l))return;const[u,f,h]=ie(l);for(let m=.25;m<=100;m+=.25){const y=ct(u+t*m,f,h);if(d(y)){e[r]=y;return}}};n("inkDim",un,Cs("inkDim"),null,0),n("inkMuted",un,Cs("inkMuted"),"inkDim",bo),n("ink",un,Cs("ink"),"inkMuted",ti)},Cs=e=>_g.find(([t])=>t===e)[1],UT=.15,wg=.12,BT=(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+UT*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 y=ct(m,d,u);if(e.ink=y,se(y,e.canvas)>=f)return}return}const s=t*(1-wg*r),a=["ink","inkMuted","inkDim"].filter(l=>ot(e[l])),c=l=>a.every(d=>nr(e,l[d],un)>=Cs(d)+Ot)&&se(l.ink,e.canvas)>=Ml&&(!l.inkMuted||de(l.ink,l.inkMuted)>=ti+Ot)&&(!l.inkMuted||!l.inkDim||de(l.inkMuted,l.inkDim)>=bo+Ot);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,y,b]=d[h];f[h]=ct(m-o*u,y,b)}if(!c(f))break;for(const h of l)e[h]=f[h]}}},Ss=(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+Ot)&&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}}},kg=(e,t,{spread:n=1,narrow:r=!1,ease:o=MT,travel:s=1}={})=>{if(t===0)return e;const a=t>0?"high":"soft",c=Math.abs(t)/100,l={...e},d=z=>ie(Bt(e[z])),u=d("canvas")[0],f=CT[e.mode][a],h=OT.filter(z=>ot(e[z])),m=a==="high"==(e.mode==="light")?1:-1;let y=Math.max(0,(f-u)*m)*m*c*s,b=u+y;const v=a==="soft"?1-.4*c:1,p=ks(b)/ks(u),E=(a==="soft"?p:Math.max(1,p))*n,k=Object.fromEntries(h.map(z=>[z,b+(d(z)[0]-u)*E])),C=e.mode==="dark"?1:-1,N=(z,[,me],oe)=>{const Me=(d(z)[0]-u)*oe,De=(k[z]-b)*oe,Ge=Math.max(Me,me-.15);De>Ge&&(k[z]=b+oe*Ge)};N("surface",Rn.canvasSurface,C),N("sunken",Rn.canvasSunken,-C);{const z=(d("elevated")[0]-d("surface")[0])*C,me=(k.elevated-k.surface)*C,oe=Math.max(z,Rn.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,bg/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+y,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-Rf-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},De=[["canvas","surface",it],["surface","elevated",it],["canvas","elevated",xf],["canvas","messageSurface",xf]].filter(([ye,Ae])=>(ye==="canvas"||me.includes(ye))&&me.includes(Ae)),Ge=[["canvas","surface",Rn.canvasSurface[0]],["surface","elevated",Rn.surfaceElevated[0]],["canvas","messageSurface",mc]].filter(([ye,Ae])=>(ye==="canvas"||me.includes(ye))&&me.includes(Ae)),et=(ye,Ae,ut)=>ut+.02,be=ye=>De.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 Rt=Te<=u?1:Math.min(1,(100-Rf-Te)/oe),Ne=Math.max(1,ks(Te)/ks(u))*n,Mt={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)*Rt:Te+(k[ye]-z)*(Ne/E);for(const ye of["rowHover","rowSelected"])ye in k&&Number.isFinite(Mt[ye])&&(k[ye]=k.surface+Mt[ye]);b=Te,y=Te-u}}if(a==="soft"&&r){const z=be=>e.mode==="dark"?be>b:be<b,me=be=>be>8?((be+16)/116)**3:Math.max(0,be)/903.3,oe=(be,Te)=>{const[Rt,Ne]=[me(be),me(Te)];return(Math.max(Rt,Ne)+.05)/(Math.min(Rt,Ne)+.05)},Me=un.filter(be=>be in k&&z(k[be])),Ge=Math.max(1,...un.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(b,b+(k[Te]-b)*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]=b+(k[Te]-b)*be)}}const F=Math.min(...Object.values(k)),$=Math.max(...Object.values(k)),ne=F<.5?.5-F:$>100?100-$:0,T=rr(Bt(e.surface)),V=T>=fn?Math.max(v,Math.min(1,(fn+.4)/T)):v;for(const z of h){const[,me,oe]=d(z),Me=PT.has(z)?1:z==="surface"?V:v;l[z]=ct(k[z]+ne,me*Me,oe*Me)}$T(l),y=b+ne-u;for(const z of Object.keys(ba))ot(e[z])&&(l[z]=Bt(e[z]));FT(l),BT(l,se(Bt(e.ink),Bt(e.canvas)),t);const Z=ie(l.accent)[0];l.accent=vc(l,"accent",...ba.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(ba))z.startsWith("ink")||z==="accent"||(l[z]=vc(l,z,me,oe));return Ss(l,"accentHover","accent",it,z=>nr(l,z,Tt)>=4.5+Ot),Ss(l,"accentActive","accent,accentHover",it,z=>nr(l,z,Tt)>=4.5+Ot),Ss(l,"accentAlt","accent",an,z=>nr(l,z,Tt)>=4.5+Ot&&rr(z)>=Go),Ss(l,"chartBarHover","accent",bc,z=>se(z,l.surface)>=se(l.accent,l.surface)),l.onAccent=jl(l.accent,[e.onAccent,l.ink,l.canvas,"#FFFFFF","#000000"]),l},si=(e,t="custom")=>{const n=xT({composed:!0});return IT(n,{id:t,palette:e}),n.log},Os=(e,t)=>{const n=jl(e.accent,[t.onAccent,e.ink,e.canvas,"#FFFFFF","#000000"]);return n===e.onAccent?e:{...e,onAccent:n}},Tf=new Set(["mode","overlayShadow","scrim","onAccent"]),HT=["rowHover","rowSelected","accentWash","surface"],WT=/\b[a-z][A-Za-z]+\b/g,GT=(e,t)=>{const n=new Map;for(const[o,s]of Object.entries(e))!Tf.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 HT)r.add(s);for(const[s]of o.matchAll(WT))s in e&&!Tf.has(s)&&ot(e[s])&&r.add(s);for(const[s]of o.matchAll(zT)){const a=n.get(s.toUpperCase());a&&r.add(a)}}return[...r]},zT=/#[0-9A-Fa-f]{6}\b/g,KT=/(?:= |ΔE00 )(\d+(?:\.\d+)?)(?::1)?[\s\S]*?need (\d+(?:\.\d+)?)/,VT=e=>{let t=0;for(const n of e){const r=n.match(KT);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},Cf=e=>e.length*1e3+VT(e),ZT=[.5,-.5,1,-1,2,-2,4,-4,7,-7,11,-11],YT=[.7,.85,1.15,1.35],JT=60,Sg=(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:Os(h,n);let l=0,d=c(e),u=si(d,t),f=Cf(u);for(let h=0;h<JT&&u.length>0;h++){let m=null;for(const y of GT(d,u)){if(a.has(y))continue;const[b,v,p]=ie(d[y]),E=[...ZT.map(k=>ct(b+k,v,p)),...s?[]:YT.map(k=>ct(b,v*k,p*k))];for(const k of E){if(k===d[y])continue;if(++l>o)return{palette:d,findings:u};const C=c({...d,[y]:k}),N=si(C,t),O=Cf(N);O<(m?m.score:f)-1e-9&&(m={next:C,findings:N,score:O})}}if(!m)break;d=m.next,u=m.findings,f=m.score}return{palette:d,findings:u}},XT=5,QT=[1,1.15],qT=[{spread:1,narrow:!0},{spread:1,narrow:!0,ease:0},...QT.map(e=>({spread:e})),{spread:1,travel:.5,soft:!0},{spread:1,travel:0,soft:!0}],Of=.015,eC=(e,t,n)=>{const r=se(Bt(e.ink),Bt(e.canvas)),o=se(t.ink,t.canvas),s=ie(Bt(e.canvas))[0],a=ie(t.canvas)[0],c=n>0==(e.mode==="light")?1:-1;return n>0?o>=r-Of&&(a-s)*c>=-.05:o<=r+Of},tC=(e,t,n,r)=>{const s=se(Bt(t.ink),Bt(t.canvas))*(1-wg*(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[y,b,v]=u[m];h[m]=ct(y+a*f,b,v)}if(si(Os(h,t),r).length>0)break;l=Os(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 y=Number.parseInt(l.ink.slice(1+2*f,3+2*f),16)+h;if(y<0||y>255)continue;const b=`#${l.ink.slice(1,1+2*f)}${y.toString(16).padStart(2,"0").toUpperCase()}${l.ink.slice(3+2*f)}`,v=se(b,l.canvas);if(v>=se(l.ink,l.canvas))continue;const p=Os({...l,ink:b},t);si(p,r).length>0||(!u||v>u.r)&&(u={r:v,next:p})}if(!u)break;l=u.next}return l},nC=(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(XT,Math.abs(o)))for(const s of qT){if((s.narrow||s.soft)&&o>0)continue;const a=kg(e,o,s),c=Sg(a,n,e);if(o<0&&c.findings.length===0&&(c.palette=tC(c.palette,e,o,n)),c.findings.length===0&&eC(e,c.palette,o))return{palette:c.palette,effectiveContrast:o}}return{palette:e,effectiveContrast:0}},Vn=/^#[0-9A-Fa-f]{6}$/,rC=/^#[0-9A-Fa-f]{3}$/,mt=e=>{if(typeof e!="string")return null;let t=e.trim();return t.startsWith("#")||(t=`#${t}`),rC.test(t)&&(t=`#${[...t.slice(1)].map(n=>n+n).join("")}`),Vn.test(t)?t.toUpperCase():null},oC=["accentHover","accentActive","accentWash","chartBarHover"],Ft=e=>{const[t,n,r]=ie(e);return[t,Math.hypot(n,r),Math.atan2(r,n)]},sC=e=>Ft(e)[1],ii=(e,t,n)=>ct(e,Math.max(0,t)*Math.cos(n),Math.max(0,t)*Math.sin(n)),iC=4,aC=(e,t,n)=>{const[r,o,s]=Ft(e),[a,c,l]=Ft(t),[d,u,f]=Ft(n);return o<iC?ii(d+(a-r),c,f):ii(d+(a-r),u*(c/o),f+(l-s))},cC=(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},lC=(e,t,{authored:n=e,id:r="custom",paletteAccent:o,preserveSecondary:s=!1}={})=>{const a=cC(t,n,o);if(!a)return{palette:e,applied:!1,adjusted:0,requested:a};const c={...e,accent:a};for(const h of oC)!Vn.test(n[h]??"")||!Vn.test(n.accent??"")||(c[h]=aC(n.accent,n[h],a));if(Vn.test(e.accentWash??"")&&Vn.test(n.accentWash??"")){const h=Ft(e.accentWash)[0],[,m,y]=Ft(c.accentWash);c.accentWash=ii(h,Math.max(m,Ft(n.accentWash)[1]),y)}if(sC(c.surface)<fn){const h=Ft(c.accent)[2];for(const m of["rowHover","rowSelected"]){if(!Vn.test(c[m]??""))continue;const[y,b]=Ft(c[m]);b>=fn&&(c[m]=ii(y,b,h))}}!s&&t.kind==="theme-alt"?Ft(n.accent)[1]>=Go&&(c.accentAlt=mt(n.accent)):!s&&de(c.accent,c.accentAlt)<an&&Ft(n.accent)[1]>=Go&&(c.accentAlt=mt(n.accent));const l=ie(c.accent)[0];c.accent=vc(c,"accent",dC,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(!Vn.test(c[h]??""))continue;const[m,y,b]=ie(c[h]);c[h]=ct(m+d,y,b)}c.onAccent=jl(c.accent,[n.onAccent,c.ink,c.canvas,"#FFFFFF","#000000"]);const u=Sg(c,r,n);return s&&gg.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}},dC=["canvas","surface","elevated","sunken","accentWash","messageSurface","warningWash"],Pf=["dark","light"],uC=12,_D=50,bD="custom-themes-storage",fC=60,Eg=Object.freeze({dark:0,light:0}),xn=Object.freeze({kind:"theme"}),Ag=Object.freeze({dark:xn,light:xn}),yc=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(-100,Math.min(100,Math.round(e))),Rg=e=>!e||typeof e!="object"?Eg:{dark:yc(e.dark),light:yc(e.light)},wc=(e,t=()=>!0)=>{if(!e||typeof e!="object")return xn;switch(e.kind){case"theme":return xn;case"theme-alt":return{kind:"theme-alt"};case"palette":return typeof e.id=="string"&&t(e.id)?{kind:"palette",id:e.id}:xn;case"custom":{const n=mt(e.hex);return n?{kind:"custom",hex:n}:xn}default:return xn}},xg=(e,t)=>!e||typeof e!="object"?Ag:{dark:wc(e.dark,t),light:wc(e.light,t)},Lr=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===uC)break}return t},pC=(e,t)=>{const n=mt(t);return Lr(n?[n,...Array.isArray(e)?e:[]]:e)},hC=/^custom-[a-z0-9]{1,30}$/,$l=e=>typeof e=="string"&&hC.test(e)?e:null,vD=(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||!xc(r)||typeof e.base!="string"||!t(e.base))return null;const o=typeof e.name=="string"&&e.name.trim()?e.name.trim().slice(0,fC):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&&Ic(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}},Xt=Object.freeze(Object.entries(TT).sort(([,e],[,t])=>e-t).map(([e,t])=>Object.freeze({name:e,value:t}))),Mf=5,mC=8,gC=e=>Math.max(-100,Math.min(100,e)),yD=(e,{snap:t=!0}={})=>{if(!Number.isFinite(e))return 0;const n=gC(Math.round(e/Mf)*Mf);if(!t)return n;for(const{value:r}of Xt)if(Math.abs(e-r)<=mC)return r;return n},_C=e=>Xt.find(t=>t.value===e)?.name??null,wD=e=>{let t=Xt[2];for(const n of Xt){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},kD=e=>{if(_C(e))return null;for(let t=1;t<Xt.length;t++)if(e<Xt[t].value)return[Xt[t-1].name,Xt[t].name];return null},SD=(e,t)=>{const r=(t>0?Xt:[...Xt].reverse()).find(o=>t>0?o.value>e:o.value<e);return r?r.value:e},bC=[[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"]],Dl=8,Nl=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}},ED=e=>{const{C:t,h:n}=Nl(e);if(t<Dl)return"neutral";for(const[r,o]of bC)if(n<r)return o;return"pink"},AD=(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}=Nl(l.palette.accent);if(d<Dl){(!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},RD=(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}=Nl(s);return a<Dl?1e3:c};return r.sort((s,a)=>o(s.hex)-o(a.hex))},vC=40,Ps=(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,vC);s&&(n[r]=s)}return n},xD=Object.freeze({strip:"lo-preview",chip:e=>`lo-preview-${e}`}),ID=(e,t,n=null)=>{const r=[];for(const{id:o,contrast:s}of t){if(!xc(o))continue;const a=s===0?e:kg(e,s),c=n?{...a,...n}:a;Object.entries(c).every(([d,u])=>d==="mode"||Ic(u))&&r.push(Hf(o,c))}return r.join(`
|
|
65
|
+
`)},TD=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}},CD=({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=ei([r,s*Math.cos(o),s*Math.sin(o)]);if(a)return a}return ei([r,0,0])??"#000000"},OD=e=>{const t=se("#FFFFFF",e),n=se("#000000",e);return t>=n?{ink:"#FFFFFF",ratio:t}:{ink:"#000000",ratio:n}},PD=Object.freeze(["accent","accentHover","accentActive","accentWash","onAccent","chartBarHover","accentAlt","accentAltWash"]),jf=64,kc=["canvas","run","browser","console","code"],yC={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function Ig(e){return typeof e=="string"&&kc.includes(e)}function Ll(e){return e.startsWith("draft:")}function Qo(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function Fl(e){return e.length>jf?e.slice(e.length-jf):e}function Tg(e,t,n){return Fl([...e.filter(([r])=>r!==t),[t,n]])}function wC(e,t,n){return Qo(e,t)!==n?e:e.filter(([r])=>r!==t)}function kC(e,t){return Qo(e,t)===void 0?e:e.filter(([n])=>n!==t)}function SC(e,t,n){const r=Qo(e,t);return r===void 0?e:Fl([...e.filter(([o])=>o!==t&&o!==n),[n,r]])}const $f=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function Df(e,t,n){if(n||typeof t!="string")return $f;const r=Qo(e,t);return r===void 0?$f:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function EC(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===""||Ll(r)||Ig(o)&&(t.delete(r),t.set(r,o))}return Fl([...t.entries()])}function MD(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 Nf(e){return yC[e]}const AC={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},qo=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,Ri=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,RC=e=>{const t=qo(e);return t===null||t==="ask"?null:AC[t]},En=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Wn=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:Tg(e.rightSlotMemory,n,t)}},ro=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=wC(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},xC=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=kC(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},IC=Object.freeze({mounted:!1,session:!1}),Cg=Object.freeze([]);function jD(e,t){const n=qo(t);if(n===null||!Ri(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=oo(Rl,t.rightSlotWidth);break;case"run":r=oo(Ff,t.rightSlotWidth);break;case"browser":r=oo(MC,t.rightSlotWidth);break;case"console":r=oo(jC,t.rightSlotWidth);break;case"code":r=oo(Ff,t.rightSlotWidth);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,xl(e)):Math.min(r,Math.max(0,e-El))}function oo(e,t){return Math.min(Qm,Math.max(e,t||TC))}function $D(e){const t=qo(e);return t!==null&&Ri(t,e)}function DD(e){const t=qo(e);return t!==null&&Ri(t,e)?t:null}function ND(e){const t=qo(e);return(t==="canvas"||t==="ask")&&Ri(t,e)}const TC=640,Lf=wi,CC=20,OC=4,PC=20,Ff=320,MC=480,jC=480,$C=5e3,LD=(e,t)=>e.some(n=>n.surface===t),FD=(e,t=Date.now())=>e.some(n=>t-n.at<$C),DC=[],NC=5,LC=["chatMeasureWidth"],UD=Vo()(ui((e,t)=>({finderFiles:dg,setFinderFiles:n=>e({finderFiles:Cl({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:pg,agentAvatarSize:tg,themeName:Fg,contrast:Eg,accent:Ag,customAccents:[],customAccentNames:{},customThemeId:null,setContrast:(n,r)=>e(o=>({contrast:{...o.contrast,[n]:yc(r)}})),setAccent:(n,r)=>e(o=>({accent:{...o.accent,[n]:wc(r,Ac)}})),addCustomAccent:(n,r)=>e(o=>{const s=pC(o.customAccents,n),a=mt(n),c=Ps(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 Pf){const l=s[c];l.kind==="custom"&&l.hex===o&&(s[c]=xn)}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:Ps({...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=Lr(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 Pf){const m=f[h];m.kind==="custom"&&m.hex===s&&(f[h]={kind:"custom",hex:a})}return{customAccents:d,customAccentNames:Ps(u,d),accent:f}}),rightSlotWidth:0,chatSidebarWidth:Lf,chatSidebarRegions:DI,chatSidebarView:yr,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:Cg,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:IC,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:DC,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?{...En("isCanvasOpen"),...Wn(r,"canvas")}:{isCanvasOpen:!1,...ro(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...En("isRunPanelOpen"),...Wn(r,"run")}:{isRunPanelOpen:!1,...ro(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...En("isBrowserPaneOpen"),...Wn(r,"browser")}:{isBrowserPaneOpen:!1,...ro(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...En("isConsolePaneOpen"),...Wn(r,"console")}:{isConsolePaneOpen:!1,...ro(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...En("isCodeReviewPaneOpen"),...Wn(r,"code")}:{isCodeReviewPaneOpen:!1,...ro(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...En("isCodeReviewPaneOpen"),...Wn(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,o)=>{e(s=>{const a=typeof s.rightSlotKey=="string";if(n)return{...En("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:a?null:RC(s),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?o?.dismissSlot?{...c,...xC(s)}:{...c,...Df(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=SC(s,c,n)),n===null||(Ll(n)?a=null:a!==null&&Qo(s,n)===void 0&&(s=Tg(s,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:s,rightSlotLegacySeed:a,...Df(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=Pl(r);s!==null&&JI(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=>({...En("isRunPanelOpen"),...Wn(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(kl,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:Lf})},rememberMention:(n,r)=>{e(o=>{const s=o.mentionRecents,a=s?.cwd===n?s.paths:[],c=[r,...a.filter(l=>l!==r)].slice(0,CC);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(o=>({profileRecents:{...o.profileRecents,[n]:FC(o.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const o=HC(r.conversationRecents),s=UC(o,n);return s.length===o.length&&s.every((a,c)=>a===o[c])?r:{conversationRecents:s}})}}),{name:"ui-preferences-storage",version:NC,migrate:KC,partialize:WC,merge:zC}));function FC(e,t){return[t,...e.filter(n=>n!==t)].slice(0,OC)}function UC(e,t){return[t,...e.filter(n=>n!==t)].slice(0,PC)}const BC=[];function HC(e){return Array.isArray(e)?e:BC}function WC(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:y,rightSlotKey:b,...v}=e;return{...v,rightSlotMemory:GC(e.rightSlotMemory)}}function GC(e){return(e??Cg).filter(([t])=>!Ll(t))}function zC(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:o,isBrowserPaneOpen:s,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:Cl(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:EC(n.rightSlotMemory),rightSlotLegacySeed:Ig(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:XI(n.shortcutBindings),contrast:Rg(n.contrast),accent:xg(n.accent,Ac),customAccents:Lr(n.customAccents),customAccentNames:Ps(n.customAccentNames,Lr(n.customAccents)),customThemeId:$l(n.customThemeId)}}function KC(e,t){const n={...e??{}};if(t<1&&VC(n),t<2)for(const r of LC)delete n[r];if(t<3){let r=null;for(const o of kc)if(n[Nf(o)]===!0){r=o;break}r!==null&&(n.rightSlotLegacySeed=r);for(const o of kc)delete n[Nf(o)]}return t<4&&(n.finderFiles=Cl(n.finderFiles)),t<5&&(n.contrast=Rg(n.contrast),n.accent=xg(n.accent,Ac),n.customAccents=Lr(n.customAccents),n.customThemeId=$l(n.customThemeId)),n}function VC(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 Sc=e=>e.replace(/\\/g,"/"),BD=()=>window.location.hash?Sc(window.location.hash.substring(1)):Sc(window.location.pathname),HD=(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,"/")},WD=(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=y=>{const b=t-y.length-(y?3:2);let v=[];for(let p=a.length-1;p>=0;p-=1){const E=[a[p],...v];if(E.join("/").length>b)break;v=E}return v},l=(y,b)=>y?`${y}/…/${b.join("/")}`:`…/${b.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)]):"…"},GD=(e,t)=>Sc(e).includes(t),Ec=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)},ZC=(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=nC(e,t,{id:r});let l=c.palette,d=!0,u=0;if(!a){const f=lC(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-${Ec(l)}`,effectiveContrast:c.effectiveContrast,requestedContrast:t,accentApplied:d,accentAdjusted:u}},Uf="lo-composed-theme",YC=4,Gn=new Map,JC=(e,t)=>{const n=Gn.get(e);if(n)return Gn.delete(e),Gn.set(e,n),n;const r=Ug(t);if(Gn.set(e,r),Gn.size>YC){const o=Gn.keys().next().value;o!==void 0&&Gn.delete(o)}return r},XC=e=>Rc(e)?.palette.accent,QC=16,gr=new Map,qC=(e,t,n)=>{const r=Bf(e.themeName),o=Rc(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?Ec(t):null,l,d??null]);let f=gr.get(u);if(f?gr.delete(u):f=ZC(s,{contrast:l,accent:d,id:c,preserveSecondary:t!==void 0,paletteAccent:XC}),gr.set(u,f),gr.size>QC){const m=gr.keys().next().value;m!==void 0&&gr.delete(m)}if(f.identity&&!n)return{...f,id:r.id,muiTheme:r.theme};const h=`lo-${Ec(f.palette)}`;return{...f,id:h,identity:!1,muiTheme:JC(h,f.palette)}},eO=(e,t)=>xc(e)&&Object.entries(t).every(([n,r])=>n==="mode"||Ic(r))&&(t.mode==="dark"||t.mode==="light"),zD=(e,t=document,n,r,o=s=>qC(s,n,r))=>{let s=o(e);if(!s.identity&&!eO(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=Rc(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(Uf);if(s.identity)c?.remove();else{const l=c??t.createElement("style");l.id=Uf,l.textContent=Hf(s.id,s.palette),c||t.head.appendChild(l)}return o1(t,s.identity?null:s.palette),a.dataset.theme=s.id,a.classList.toggle("dark",s.palette.mode==="dark"),s},KD=e=>({themeName:e.themeName,customThemeId:e.customThemeId??null,contrast:e.contrast,accent:e.accent}),VD=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{Aj as $,Gj as A,cx as B,ix as C,fD as D,zD as E,KD as F,UD as G,at as H,UI as I,VD as J,qC as K,i as L,Tp as M,Pe as N,YR as O,jd as P,JR as Q,Oj as R,ht as S,bm as T,wm as U,Rj as V,Ij as W,vm as X,xj as Y,Sj as Z,Cj as _,aP as a,ED as a$,Tj as a0,c$ as a1,XO as a2,BD as a3,ea as a4,IM as a5,YO as a6,JO as a7,xm as a8,Kj as a9,kp as aA,Sc as aB,q0 as aC,vO as aD,MP as aE,SO as aF,zb as aG,kO as aH,EO as aI,cO as aJ,Vf as aK,Ci as aL,Ub as aM,Fb as aN,kA as aO,NR as aP,CM as aQ,PM as aR,MM as aS,im as aT,y$ as aU,nI as aV,v$ as aW,rI as aX,oI as aY,mt as aZ,uC as a_,Vj as aa,yi as ab,_$ as ac,HC as ad,gn as ae,st as af,Ur as ag,vc as ah,oO as ai,e0 as aj,mj as ak,Vo as al,rj as am,TO as an,iO as ao,Ct as ap,Ma as aq,ui as ar,Av as as,sP as at,QO as au,$v as av,Dv as aw,Ud as ax,IO as ay,xO as az,tP as b,Wv as b$,OD as b0,vC as b1,n$ as b2,_C as b3,wD as b4,Xt as b5,xD as b6,Mf as b7,yD as b8,kD as b9,w_ as bA,v_ as bB,t$ as bC,Rx as bD,zj as bE,$j as bF,GD as bG,bO as bH,_O as bI,gO as bJ,mO as bK,wO as bL,Jb as bM,Lt as bN,go as bO,Rp as bP,fv as bQ,r0 as bR,oP as bS,rP as bT,nP as bU,DD as bV,hD as bW,ej as bX,Dn as bY,_d as bZ,Nc as b_,SD as ba,AD as bb,RD as bc,ID as bd,PD as be,vk as bf,bx as bg,iP as bh,gg as bi,ZC as bj,TD as bk,gD as bl,hc as bm,dD as bn,zo as bo,rt as bp,Gf as bq,c_ as br,f_ as bs,m_ as bt,y_ as bu,__ as bv,b_ as bw,cd as bx,k_ as by,ld as bz,Gi as c,C$ as c$,li as c0,mp as c1,VR as c2,Ej as c3,ae as c4,kj as c5,vr as c6,rc as c7,oc as c8,yj as c9,q$ as cA,eD as cB,tD as cC,I$ as cD,Im as cE,e$ as cF,nD as cG,H$ as cH,K$ as cI,V$ as cJ,W$ as cK,G$ as cL,yr as cM,A$ as cN,lg as cO,j$ as cP,X$ as cQ,Ho as cR,J$ as cS,Q$ as cT,Pr as cU,Ju as cV,D$ as cW,$$ as cX,N$ as cY,F$ as cZ,L$ as c_,wj as ca,gj as cb,_j as cc,bj as cd,mD as ce,FD as cf,$C as cg,LD as ch,Sp as ci,GO as cj,NO as ck,Ap as cl,zy as cm,tv as cn,Vg as co,nv as cp,Tl as cq,UO as cr,Vu as cs,zO as ct,_x as cu,U$ as cv,B$ as cw,II as cx,cf as cy,T$ as cz,Ye as d,ep as d$,Z$ as d0,Y$ as d1,k$ as d2,S$ as d3,Pj as d4,jj as d5,R$ as d6,Mj as d7,ki as d8,x$ as d9,$D as dA,fc as dB,IC as dC,oo as dD,jD as dE,f$ as dF,p$ as dG,u$ as dH,Rl as dI,xl as dJ,WO as dK,HO as dL,MC as dM,Qm as dN,jC as dO,Ff as dP,El as dQ,RM as dR,xM as dS,Jj as dT,Yj as dU,Xj as dV,qj as dW,Qj as dX,w0 as dY,Jo as dZ,eP as d_,Zj as da,cg as db,z$ as dc,P$ as dd,M$ as de,O$ as df,E$ as dg,rD as dh,oD as di,aD as dj,cD as dk,$I as dl,sD as dm,Es as dn,Wo as dp,iD as dq,lD as dr,AO as ds,b$ as dt,HD as du,WD as dv,uD as dw,hO as dx,TA as dy,uP as dz,cP as e,M1 as e$,hl as e0,tj as e1,DM as e2,uj as e3,fj as e4,Am as e5,ux as e6,_i as e7,Hj as e8,Wj as e9,qb as eA,pD as eB,Ca as eC,g$ as eD,d$ as eE,V1 as eF,qm as eG,lP as eH,dP as eI,t_ as eJ,FI as eK,fO as eL,Ll as eM,MD as eN,sd as eO,uO as eP,dO as eQ,ya as eR,vo as eS,s_ as eT,g_ as eU,S_ as eV,lS as eW,r$ as eX,lr as eY,Gm as eZ,s$ as e_,iw as ea,nj as eb,FM as ec,RR as ed,ox as ee,Em as ef,nx as eg,zu as eh,Dj as ei,eI as ej,Bj as ek,vj as el,MO as em,jO as en,ZO as eo,Ei as ep,Ai as eq,mg as er,JI as es,Ol as et,ij as eu,ch as ev,Hs as ew,NP as ex,Ln as ey,tr as ez,t0 as f,Qk as f$,Bm as f0,o$ as f1,a$ as f2,l$ as f3,VO as f4,qO as f5,di as f6,Et as f7,a_ as f8,mx as f9,OM as fA,LM as fB,NM as fC,jM as fD,Er as fE,BO as fF,KO as fG,FO as fH,DP as fI,$P as fJ,yP as fK,Vc as fL,Wc as fM,Nn as fN,qt as fO,si as fP,_D as fQ,vD as fR,CD as fS,jl as fT,xT as fU,IT as fV,Sg as fW,bD as fX,$l as fY,qP as fZ,eM as f_,ND as fa,m$ as fb,Al as fc,h$ as fd,Xm as fe,X1 as ff,kl as fg,$O as fh,wd as fi,Ay as fj,DO as fk,iv as fl,oj as fm,KM as fn,VM as fo,OO as fp,PO as fq,zM as fr,am as fs,AA as ft,jh as fu,pg as fv,hh as fw,Ty as fx,LO as fy,TM as fz,Fc as g,QP as g$,fk as g0,lk as g1,pk as g2,Tr as g3,XP as g4,JP as g5,GP as g6,LP as g7,FP as g8,BP as g9,kM as gA,fM as gB,rM as gC,oM as gD,sM as gE,iM as gF,aM as gG,cM as gH,yM as gI,rv as gJ,ov as gK,sv as gL,nu as gM,EP as gN,KP as gO,Bk as gP,ph as gQ,Xp as gR,IP as gS,$c as gT,Sd as gU,Pl as gV,LI as gW,V0 as gX,WP as gY,Lk as gZ,VP as g_,UP as ga,mh as gb,ZP as gc,uw as gd,EM as ge,Iw as gf,YP as gg,US as gh,_M as gi,Ih as gj,vM as gk,hM as gl,mM as gm,bM as gn,NS as go,Yi as gp,gM as gq,BS as gr,uM as gs,nM as gt,lM as gu,wM as gv,tM as gw,dM as gx,pM as gy,SM as gz,qf as h,HM as h$,zP as h0,Rw as h1,RP as h2,bw as h3,TP as h4,CP as h5,PP as h6,OP as h7,jP as h8,HP as h9,BM as hA,Bp as hB,jo as hC,kP as hD,F0 as hE,Hp as hF,Gc as hG,Lp as hH,A0 as hI,R0 as hJ,vP as hK,Qb as hL,bP as hM,hP as hN,gP as hO,Xd as hP,pP as hQ,fP as hR,_P as hS,Qd as hT,mP as hU,vp as hV,SP as hW,wP as hX,Fj as hY,UM as hZ,GM as h_,AM as ha,w$ as hb,JM as hc,ZM as hd,LA as he,QM as hf,YM as hg,XM as hh,qM as hi,AP as hj,xP as hk,Lc as hl,Il as hm,cI as hn,CO as ho,$M as hp,aj as hq,cj as hr,Xa as hs,dj as ht,wA as hu,lj as hv,pj as hw,DR as hx,hj as hy,f0 as hz,wv as i,WM as i0,Nj as i1,Lj as i2,Bb as i3,kd as i4,lO as i5,sj as i6,kv as j,Sv as k,Ev as l,sO as m,aO as n,E_ as o,RO as p,i$ as q,o0 as r,O1 as s,l0 as t,u_ as u,yO as v,pO as w,Sx as x,kt as y,Uj as z};
|