local-operator-ui 0.57.3 → 0.57.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/main/index.js +1044 -63
- package/out/preload/index.js +102 -21
- package/out/renderer/assets/{_basePickBy-BeAzmqgq.js → _basePickBy-D2upKftS.js} +1 -1
- package/out/renderer/assets/{_baseUniq-Clx9gdFs.js → _baseUniq-BGD19KIN.js} +1 -1
- package/out/renderer/assets/{agent-details-page-BMztNR89.js → agent-details-page-OPyFw_dI.js} +1 -1
- package/out/renderer/assets/{agent-hub-page-quUNNwcr.js → agent-hub-page-B3V1y16n.js} +1 -1
- package/out/renderer/assets/{agents-page-BTYHgMAf.js → agents-page-CowgZsSO.js} +3 -3
- package/out/renderer/assets/appearance-DO4VPBSi.js +65 -0
- package/out/renderer/assets/{approvalsOverlay-BxwEca1y.js → approvalsOverlay-CBPXn0ct.js} +1 -1
- package/out/renderer/assets/{arc-BOZHzyJm.js → arc-Cv6N9gTJ.js} +1 -1
- package/out/renderer/assets/{architectureDiagram-IEHRJDOE-CpE8Siol.js → architectureDiagram-IEHRJDOE-DHtB5fE0.js} +1 -1
- package/out/renderer/assets/{avatar-cropper-BWJE7j7A.js → avatar-cropper-Bjo9zUPg.js} +1 -1
- package/out/renderer/assets/{blockDiagram-JOT3LUYC-D4LTtQ_H.js → blockDiagram-JOT3LUYC-4WEK73Je.js} +1 -1
- package/out/renderer/assets/{book-open-fa_DaJBq.js → book-open-CmfjhXrg.js} +1 -1
- package/out/renderer/assets/browser-page-2S7sbehs.js +1 -0
- package/out/renderer/assets/{browser-webauthn-prompt-VC7pNm9O.js → browser-webauthn-prompt-D8Tgtg83.js} +1 -1
- package/out/renderer/assets/{c4Diagram-VJAJSXHY-DRtUDXOF.js → c4Diagram-VJAJSXHY-kaGHtOK6.js} +1 -1
- package/out/renderer/assets/channel-DRHru1K8.js +1 -0
- package/out/renderer/assets/{chunk-4BMEZGHF-Cw4VudrA.js → chunk-4BMEZGHF-CpC8J2AT.js} +1 -1
- package/out/renderer/assets/{chunk-A2AXSNBT-0JOiKMb-.js → chunk-A2AXSNBT-DKmX4atq.js} +1 -1
- package/out/renderer/assets/{chunk-AEK57VVT-CAKCg9DA.js → chunk-AEK57VVT-Dtej3BD4.js} +1 -1
- package/out/renderer/assets/{chunk-D6G4REZN-CFZ2DTGX.js → chunk-D6G4REZN-DUXxF-pw.js} +1 -1
- package/out/renderer/assets/{chunk-RZ5BOZE2-CupwUHva.js → chunk-RZ5BOZE2-DeeJjU3w.js} +1 -1
- package/out/renderer/assets/{chunk-XZIHB7SX-B1vcbFku.js → chunk-XZIHB7SX-D4R6kzHb.js} +1 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-Cs0VSRpc.js +1 -0
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-Cs0VSRpc.js +1 -0
- package/out/renderer/assets/clone-_NlCUljT.js +1 -0
- package/out/renderer/assets/{console-mirror-IB35kNI8.js → console-mirror-Bp3thuUi.js} +1 -1
- package/out/renderer/assets/{consoleCapture-D4G96kDb.js → consoleCapture-BJR8BDEY.js} +1 -1
- package/out/renderer/assets/{conversation-input-sync-DlorrZ6B.js → conversation-input-sync-FnnZiNnd.js} +4 -4
- package/out/renderer/assets/{dagre-OKDRZEBW-CunvCCGM.js → dagre-OKDRZEBW-DDY_IkmM.js} +1 -1
- package/out/renderer/assets/{diagram-SSKATNLV-DlpXMePq.js → diagram-SSKATNLV-D7AGoSSj.js} +1 -1
- package/out/renderer/assets/{diagram-VNBRO52H-CtgMK6MT.js → diagram-VNBRO52H-CcgAGaBN.js} +1 -1
- package/out/renderer/assets/{erDiagram-Q7BY3M3F-C-QNezLB.js → erDiagram-Q7BY3M3F-LEYxek3-.js} +1 -1
- package/out/renderer/assets/{error-boundary-C1x5W-AX.js → error-boundary-BsWceBKP.js} +1 -1
- package/out/renderer/assets/{flowDiagram-4HSFHLVR-DjwRYw0E.js → flowDiagram-4HSFHLVR-CQLUaH8T.js} +1 -1
- package/out/renderer/assets/{ganttDiagram-APWFNJXF-Tb5F1KXD.js → ganttDiagram-APWFNJXF-Ole27PT-.js} +1 -1
- package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-BokP9Y1T.js → gitGraphDiagram-7IBYFJ6S-BNYa___9.js} +1 -1
- package/out/renderer/assets/{graph-DEHYXN6b.js → graph-Bibb0aeq.js} +1 -1
- package/out/renderer/assets/{heart-DqMMtrJ1.js → heart-Cix0tXFr.js} +1 -1
- package/out/renderer/assets/index-BKLUTBo0.css +1 -0
- package/out/renderer/assets/index-BKh47kLl.js +857 -0
- package/out/renderer/assets/{index-D7fnBkIK.js → index-C9UzsV82.js} +1 -1
- package/out/renderer/assets/{index-CJ8BPUHQ.js → index-CMJfInon.js} +1 -1
- package/out/renderer/assets/{index-BWQzFq0n.js → index-D0qlrLIs.js} +10 -10
- package/out/renderer/assets/infoDiagram-PH2N3AL5-BXhry1Gr.js +2 -0
- package/out/renderer/assets/{inline-error-boundary-ChbTvdIh.js → inline-error-boundary-Ba_FWBMT.js} +1 -1
- package/out/renderer/assets/{installer-Bplg-bpo.js → installer-bmE_RNOZ.js} +1 -1
- package/out/renderer/assets/{journeyDiagram-U35MCT3I-BfXoBW-2.js → journeyDiagram-U35MCT3I-DI32aDKT.js} +1 -1
- package/out/renderer/assets/{kanban-definition-NDS4AKOZ-BeT3LOJG.js → kanban-definition-NDS4AKOZ-CZ-ELIdr.js} +1 -1
- package/out/renderer/assets/{layout-B71SsWep.js → layout-Dza9PMRJ.js} +1 -1
- package/out/renderer/assets/{legacy-agents-page-BaSX_kru.js → legacy-agents-page-CPFGYWOZ.js} +1 -1
- package/out/renderer/assets/{library-page-BwmVBhNJ.js → library-page-DiaLon0b.js} +3 -3
- package/out/renderer/assets/{log-in-C4tjIXzF.js → log-in-Bd6fDqyJ.js} +1 -1
- package/out/renderer/assets/{mermaid.core-D7wfsRjY.js → mermaid.core-BcJdc-X6.js} +5 -5
- package/out/renderer/assets/{mesh-page-DbC0RmVo.js → mesh-page-7T5BtRTh.js} +1 -1
- package/out/renderer/assets/{messages-B7aIuFuF.js → messages-BYDbMAVA.js} +10 -10
- package/out/renderer/assets/{mindmap-definition-ALO5MXBD-BPTOzHuL.js → mindmap-definition-ALO5MXBD-D2CXGzTD.js} +1 -1
- package/out/renderer/assets/{mini-DXMqE-0u.js → mini-CJlFVLUZ.js} +1 -1
- package/out/renderer/assets/{notebook-pen-CQdB2BC5.js → notebook-pen-D05OGtSm.js} +1 -1
- package/out/renderer/assets/{notifications-page-C9PU2typ.js → notifications-page-BjrfZb8l.js} +1 -1
- package/out/renderer/assets/{org-access-Fw38H9fZ.js → org-access-B9_h9w7n.js} +1 -1
- package/out/renderer/assets/{org-surface-gate-CKBjFWJL.js → org-surface-gate-sm4xQvjq.js} +1 -1
- package/out/renderer/assets/{page-header-CAW9G_fb.js → page-header-DXwYxMB-.js} +1 -1
- package/out/renderer/assets/{pieDiagram-IB7DONF6-C0JN0KMq.js → pieDiagram-IB7DONF6-DUG4cv-v.js} +1 -1
- package/out/renderer/assets/{projects-page-D9F4QotN.js → projects-page-DlCYJUiP.js} +1 -1
- package/out/renderer/assets/{publication-validation-DygSOQkj.js → publication-validation-Bn7rmCS6.js} +1 -1
- package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-BRgjFQlM.js → quadrantDiagram-7GDLP6J5-DaYms9_B.js} +1 -1
- package/out/renderer/assets/{radar-MK3ICKWK-VE0niGVF.js → radar-MK3ICKWK-B97TgRmB.js} +1 -1
- package/out/renderer/assets/{radient-auth-buttons-CXMLVkUO.js → radient-auth-buttons-CEfTJcvg.js} +1 -1
- package/out/renderer/assets/{requirementDiagram-KVF5MWMF-DkwJBmMi.js → requirementDiagram-KVF5MWMF-DgyICZXf.js} +1 -1
- package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-DFv3zh8B.js → sankeyDiagram-QLVOVGJD-DHgZL_Zc.js} +1 -1
- package/out/renderer/assets/{schedules-page-aTbxrD_M.js → schedules-page-CNdkudlY.js} +1 -1
- package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-BXcr3er8.js → sequenceDiagram-X6HHIX6F-pU2H-s2W.js} +1 -1
- package/out/renderer/assets/settings-page-B9GORgXK.js +319 -0
- package/out/renderer/assets/{smartart-CWBh1X_F.js → smartart-gFtvTNRW.js} +1 -1
- package/out/renderer/assets/{stateDiagram-DGXRK772-Cw08neDd.js → stateDiagram-DGXRK772-HwW2OpHh.js} +1 -1
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-BwCPC1S5.js +1 -0
- package/out/renderer/assets/{team-bridge-page-BHAdGSZS.js → team-bridge-page-ChcIcnje.js} +17 -17
- package/out/renderer/assets/{timeline-definition-BDJGKUSR-B-ZFBehC.js → timeline-definition-BDJGKUSR-CPNzpTN8.js} +1 -1
- package/out/renderer/assets/{use-default-on-banner-C8DUslhy.js → use-default-on-banner-CuXTqN3l.js} +1 -1
- package/out/renderer/assets/{use-download-agent-mutation-DMGaSxDK.js → use-download-agent-mutation-BCbr9wLe.js} +1 -1
- package/out/renderer/assets/{xychartDiagram-VJFVF3MP-BGB8PPzY.js → xychartDiagram-VJFVF3MP-TZFrKw4j.js} +1 -1
- package/out/renderer/browser-approvals-overlay.html +2 -2
- package/out/renderer/console-capture.html +6 -6
- package/out/renderer/index.html +8 -8
- package/out/renderer/installer.html +5 -5
- package/out/renderer/mini.html +7 -7
- package/package.json +1 -1
- package/out/renderer/assets/appearance-DCqlsN7S.js +0 -65
- package/out/renderer/assets/browser-page-AgwdXhLM.js +0 -1
- package/out/renderer/assets/channel-DMQl-cpj.js +0 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-DJsxDWD8.js +0 -1
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-DJsxDWD8.js +0 -1
- package/out/renderer/assets/clone-B9GxWhWi.js +0 -1
- package/out/renderer/assets/index-BnqyWEPM.css +0 -1
- package/out/renderer/assets/index-Buuz619t.js +0 -852
- package/out/renderer/assets/infoDiagram-PH2N3AL5-bdAhVGkO.js +0 -2
- package/out/renderer/assets/settings-page-DWZ3Mguh.js +0 -319
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-BtazAv7-.js +0 -1
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import{r as x,j as U_,b as Sd,D as B_,l as Vc,m as Ep,n as Zc,o as H_}from"./index-D0qlrLIs.js";import{c as sn,t as g,a as W_}from"./messages-BYDbMAVA.js";import{P as G_,i as Yc,a as Xc,p as Ip}from"./roles-D1pcbxAx.js";const Ed=new Map,Id=new Map,Ad=new Map,Rd=new Map;function Jc(e){return e===void 0?"":JSON.stringify(e)}function Qc(e,t){const n=`${e}\0${Jc(t)}`;let o=Ed.get(n);return o===void 0&&(o=new Intl.DateTimeFormat(e,t),Ed.set(n,o)),o}function z_(e,t){const n=`${e}\0${Jc(t)}`;let o=Id.get(n);return o===void 0&&(o=new Intl.NumberFormat(e,t),Id.set(n,o)),o}function mM(e,t,n){return Qc(n??sn(),t).format(e)}const gM={year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"};function _M(e,t,n){return Qc(n??sn(),t).format(e)}function K_(e,t,n){return Qc(n??sn(),t).format(e)}function V_(e,t,n){return z_(n??sn(),t).format(e)}function bM(e,t,n,o){const r=o??sn(),i=`${r}\0${Jc(n)}`;let a=Ad.get(i);return a===void 0&&(a=new Intl.RelativeTimeFormat(r,n),Ad.set(i,a)),a.format(e,t)}const Z_={B:"byte",KB:"kilobyte",MB:"megabyte",GB:"gigabyte",TB:"terabyte",PB:"petabyte"},xd=new Map,Td=new Map;function Y_(e){return e.split("-")[0]?.toLowerCase()==="en"}function X_(e,t){if(e==="KiB"||e==="MiB"||e==="GiB"||Y_(t))return e;const n=`${t}\0${e}`;let o=xd.get(n);if(o===void 0){o=e;try{o=new Intl.NumberFormat(t,{style:"unit",unit:Z_[e],unitDisplay:"narrow"}).formatToParts(1).find(i=>i.type==="unit")?.value??e}catch{}xd.set(n,o)}return o}function J_(e){let t=Td.get(e);if(t===void 0){t=" ";try{t=new Intl.NumberFormat(e,{style:"unit",unit:"kilobyte",unitDisplay:"short"}).formatToParts(1).find(o=>o.type==="literal")?.value??" "}catch{}Td.set(e,t)}return t}function wr(e,t,n,o){const r=sn();return`${V_(e,{useGrouping:!1,...n},r)}${J_(r)}${X_(t,r)}`}function Ni(e,t){const n=sn();let o=Rd.get(n);return o===void 0&&(o=new Intl.ListFormat(n,{type:"conjunction",style:"narrow"}),Rd.set(n,o)),o.format(e)}const Q_={zh:";",ja:";",ur:"؛ ",ar:"؛ "};function vM(e,t){const n=sn().split("-")[0]?.toLowerCase();return e.join(Q_[n??""]??"; ")}var ni=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(){}},io=typeof window>"u"||"Deno"in globalThis;function Tt(){}function q_(e,t){return typeof e=="function"?e(t):e}function Fa(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ap(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Mo(e,t){return typeof e=="function"?e(t):e}function Ht(e,t){return typeof e=="function"?e(t):e}function Cd(e,t){const{type:n="all",exact:o,fetchStatus:r,predicate:i,queryKey:a,stale:c}=e;if(a){if(o){if(t.queryHash!==qc(a,t.options))return!1}else if(!xr(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||r&&r!==t.state.fetchStatus||i&&!i(t))}function Od(e,t){const{exact:n,status:o,predicate:r,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Rr(t.options.mutationKey)!==Rr(i))return!1}else if(!xr(t.options.mutationKey,i))return!1}return!(o&&t.state.status!==o||r&&!r(t))}function qc(e,t){return(t?.queryKeyHashFn||Rr)(e)}function Rr(e){return JSON.stringify(e,(t,n)=>Ba(n)?Object.keys(n).sort().reduce((o,r)=>(o[r]=n[r],o),{}):n)}function xr(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>xr(e[n],t[n])):!1}function Rp(e,t){if(e===t)return e;const n=Pd(e)&&Pd(t);if(n||Ba(e)&&Ba(t)){const o=n?e:Object.keys(e),r=o.length,i=n?t:Object.keys(t),a=i.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:i[d];(!n&&o.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=Rp(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return r===a&&l===r?e:c}return t}function Ua(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 Pd(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ba(e){if(!Md(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Md(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Md(e){return Object.prototype.toString.call(e)==="[object Object]"}function eb(e){return new Promise(t=>{setTimeout(t,e)})}function Ha(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Rp(e,t):t}function tb(e){return e}function nb(e,t,n=0){const o=[...e,t];return n&&o.length>n?o.slice(1):o}function ob(e,t,n=0){const o=[t,...e];return n&&o.length>n?o.slice(0,-1):o}var el=Symbol();function xp(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===el?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var rb=class extends ni{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!io&&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"}},tl=new rb,ib=class extends ni{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!io&&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}},Vi=new ib;function Wa(){let e,t;const n=new Promise((r,i)=>{e=r,t=i});n.status="pending",n.catch(()=>{});function o(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{o({status:"fulfilled",value:r}),e(r)},n.reject=r=>{o({status:"rejected",reason:r}),t(r)},n}function sb(e){return Math.min(1e3*2**e,3e4)}function Tp(e){return(e??"online")==="online"?Vi.isOnline():!0}var Cp=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Zs(e){return e instanceof Cp}function Op(e){let t=!1,n=0,o=!1,r;const i=Wa(),a=v=>{o||(h(new Cp(v)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>tl.isFocused()&&(e.networkMode==="always"||Vi.isOnline())&&e.canRun(),u=()=>Tp(e.networkMode)&&e.canRun(),f=v=>{o||(o=!0,e.onSuccess?.(v),r?.(),i.resolve(v))},h=v=>{o||(o=!0,e.onError?.(v),r?.(),i.reject(v))},_=()=>new Promise(v=>{r=b=>{(o||d())&&v(b)},e.onPause?.()}).then(()=>{r=void 0,o||e.onContinue?.()}),y=()=>{if(o)return;let v;const b=n===0?e.initialPromise:void 0;try{v=b??e.fn()}catch(p){v=Promise.reject(p)}Promise.resolve(v).then(f).catch(p=>{if(o)return;const A=e.retry??(io?0:3),k=e.retryDelay??sb,M=typeof k=="function"?k(n,p):k,P=A===!0||typeof A=="number"&&n<A||typeof A=="function"&&A(n,p);if(t||!P){h(p);return}n++,e.onFail?.(n,p),eb(M).then(()=>d()?void 0:_()).then(()=>{t?h(p):y()})})};return{promise:i,cancel:a,continue:()=>(r?.(),i),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?y():_().then(y),i)}}var ab=e=>setTimeout(e,0);function cb(){let e=[],t=0,n=c=>{c()},o=c=>{c()},r=ab;const i=c=>{t?e.push(c):r(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&r(()=>{o(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{i(()=>{c(...l)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{o=c},setScheduler:c=>{r=c}}}var rt=cb(),Pp=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Fa(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(io?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},lb=class extends Pp{#t;#e;#n;#o;#r;#a;#s;constructor(e){super(),this.#s=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#o=e.client,this.#n=this.#o.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=db(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#r?.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=Ha(this.state.data,e,this.options);return this.#i({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(Tt).catch(Tt):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>Ht(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===el||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||!Ap(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.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.#r&&(this.#s?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({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.#r)return this.#r.continueRetry(),this.#r.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,o=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},r=()=>{const c=xp(this.options,t),l={client:this.#o,queryKey:this.queryKey,meta:this.meta};return o(l),this.#s=!1,this.options.persister?this.options.persister(c,l,this):c(l)},i={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#o,state:this.state,fetchFn:r};o(i),this.options.behavior?.onFetch(i,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==i.fetchOptions?.meta)&&this.#i({type:"fetch",meta:i.fetchOptions?.meta});const a=c=>{Zs(c)&&c.silent||this.#i({type:"error",error:c}),Zs(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#r=Op({initialPromise:t?.initialPromise,fn:i.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.#i({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:i.options.retry,retryDelay:i.options.retryDelay,networkMode:i.options.networkMode,canRun:()=>!0}),this.#r.start()}#i(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,...Mp(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 o=e.error;return Zs(o)&&o.revert&&this.#e?{...this.#e,fetchStatus:"idle"}:{...n,error:o,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:o,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 Mp(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Tp(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function db(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,o=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?o??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var ub=class extends ni{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const o=t.queryKey,r=t.queryHash??qc(o,t);let i=this.get(r);return i||(i=new lb({client:e,queryKey:o,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(o)}),this.add(i)),i}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=>Cd(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Cd(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()})})}},fb=class extends Pp{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||pb(),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=Op({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(o,r)=>{this.#o({type:"failed",failureCount:o,error:r})},onPause:()=>{this.#o({type:"pause"})},onContinue:()=>{this.#o({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.#o({type:"pending",variables:e,isPaused:n}),await this.#e.config.onMutate?.(e,this);const r=await this.options.onMutate?.(e);r!==this.state.context&&this.#o({type:"pending",context:r,variables:e,isPaused:n})}const o=await this.#n.start();return await this.#e.config.onSuccess?.(o,e,this.state.context,this),await this.options.onSuccess?.(o,e,this.state.context),await this.#e.config.onSettled?.(o,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(o,null,e,this.state.context),this.#o({type:"success",data:o}),o}catch(o){try{throw await this.#e.config.onError?.(o,e,this.state.context,this),await this.options.onError?.(o,e,this.state.context),await this.#e.config.onSettled?.(void 0,o,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,o,e,this.state.context),o}finally{this.#o({type:"error",error:o})}}finally{this.#e.runNext(this)}}#o(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 pb(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var hb=class extends ni{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 o=new fb({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(o),o}add(e){this.#t.add(e);const t=pi(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=pi(e);if(typeof t=="string"){const n=this.#e.get(t);if(n)if(n.length>1){const o=n.indexOf(e);o!==-1&&n.splice(o,1)}else n[0]===e&&this.#e.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=pi(e);if(typeof t=="string"){const o=this.#e.get(t)?.find(r=>r.state.status==="pending");return!o||o===e}else return!0}runNext(e){const t=pi(e);return typeof t=="string"?this.#e.get(t)?.find(o=>o!==e&&o.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=>Od(t,n))}findAll(e={}){return this.getAll().filter(t=>Od(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(Tt))))}};function pi(e){return e.options.scope?.id}function jd(e){return{onFetch:(t,n)=>{const o=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,i=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=xp(t.options,t.fetchOptions),_=async(y,v,b)=>{if(u)return Promise.reject();if(v==null&&y.pages.length)return Promise.resolve(y);const p={client:t.client,queryKey:t.queryKey,pageParam:v,direction:b?"backward":"forward",meta:t.options.meta};f(p);const A=await h(p),{maxPages:k}=t.options,M=b?ob:nb;return{pages:M(y.pages,A,k),pageParams:M(y.pageParams,v,k)}};if(r&&i.length){const y=r==="backward",v=y?jp:Ga,b={pages:i,pageParams:a},p=v(o,b);c=await _(b,p,y)}else{const y=e??i.length;do{const v=l===0?a[0]??o.initialPageParam:Ga(o,c);if(l>0&&v==null)break;c=await _(c,v),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 Ga(e,{pages:t,pageParams:n}){const o=t.length-1;return t.length>0?e.getNextPageParam(t[o],t,n[o],n):void 0}function jp(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function yM(e,t){return t?Ga(e,t)!=null:!1}function wM(e,t){return!t||!e.getPreviousPageParam?!1:jp(e,t)!=null}var mb=class{#t;#e;#n;#o;#r;#a;#s;#i;constructor(e={}){this.#t=e.queryCache||new ub,this.#e=e.mutationCache||new hb,this.#n=e.defaultOptions||{},this.#o=new Map,this.#r=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#s=tl.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#i=Vi.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#s?.(),this.#s=void 0,this.#i?.(),this.#i=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),o=n.state.data;return o===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Mo(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(o))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:n})=>{const o=n.data;return[t,o]})}setQueryData(e,t,n){const o=this.defaultQueryOptions({queryKey:e}),i=this.#t.get(o.queryHash)?.state.data,a=q_(t,i);if(a!==void 0)return this.#t.build(this,o).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return rt.batch(()=>this.#t.findAll(e).map(({queryKey:o})=>[o,this.setQueryData(o,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(o=>{o.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},o=rt.batch(()=>this.#t.findAll(e).map(r=>r.cancel(n)));return Promise.all(o).then(Tt).catch(Tt)}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},o=rt.batch(()=>this.#t.findAll(e).filter(r=>!r.isDisabled()).map(r=>{let i=r.fetch(void 0,n);return n.throwOnError||(i=i.catch(Tt)),r.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(o).then(Tt)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(Mo(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Tt).catch(Tt)}fetchInfiniteQuery(e){return e.behavior=jd(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Tt).catch(Tt)}ensureInfiniteQueryData(e){return e.behavior=jd(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Vi.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.#o.set(Rr(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(o=>{xr(e,o.queryKey)&&Object.assign(n,o.defaultOptions)}),n}setMutationDefaults(e,t){this.#r.set(Rr(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(o=>{xr(e,o.mutationKey)&&Object.assign(n,o.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=qc(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===el&&(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()}},gb=class extends ni{constructor(e,t){super(),this.options=t,this.#t=e,this.#i=null,this.#s=Wa(),this.options.experimental_prefetchInRender||this.#s.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#o=void 0;#r;#a;#s;#i;#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),$d(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return za(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return za(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 Ht(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&&!Ua(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const o=this.hasListeners();o&&Dd(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),o&&(this.#e!==n||Ht(this.options.enabled,this.#e)!==Ht(t.enabled,this.#e)||Mo(this.options.staleTime,this.#e)!==Mo(t.staleTime,this.#e))&&this.#g();const r=this.#_();o&&(this.#e!==n||Ht(this.options.enabled,this.#e)!==Ht(t.enabled,this.#e)||r!==this.#c)&&this.#b(r)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return bb(this,n)&&(this.#o=n,this.#a=this.options,this.#r=this.#e.state),n}getCurrentResult(){return this.#o}trackResult(e,t){const n={};return Object.keys(e).forEach(o=>{Object.defineProperty(n,o,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(o),t?.(o),e[o])})}),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.#o))}#u(e){this.#k();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Tt)),t}#g(){this.#y();const e=Mo(this.options.staleTime,this.#e);if(io||this.#o.isStale||!Fa(e))return;const n=Ap(this.#o.dataUpdatedAt,e)+1;this.#l=setTimeout(()=>{this.#o.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,!(io||Ht(this.options.enabled,this.#e)===!1||!Fa(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||tl.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,o=this.options,r=this.#o,i=this.#r,a=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,h;if(t._optimisticResults){const m=this.hasListeners(),w=!m&&$d(e,t),S=m&&Dd(e,n,t,o);(w||S)&&(u={...u,...Mp(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:_,errorUpdatedAt:y,status:v}=u;h=u.data;let b=!1;if(t.placeholderData!==void 0&&h===void 0&&v==="pending"){let m;r?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(m=r.data,b=!0):m=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,m!==void 0&&(v="success",h=Ha(r?.data,m,t),f=!0)}if(t.select&&h!==void 0&&!b)if(r&&h===i?.data&&t.select===this.#m)h=this.#f;else try{this.#m=t.select,h=t.select(h),h=Ha(r?.data,h,t),this.#f=h,this.#i=null}catch(m){this.#i=m}this.#i&&(_=this.#i,h=this.#f,y=Date.now(),v="error");const p=u.fetchStatus==="fetching",A=v==="pending",k=v==="error",M=A&&p,P=h!==void 0,R={status:v,fetchStatus:u.fetchStatus,isPending:A,isSuccess:v==="success",isError:k,isInitialLoading:M,isLoading:M,data:h,dataUpdatedAt:u.dataUpdatedAt,error:_,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&&!A,isLoadingError:k&&!P,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:k&&P,isStale:nl(e,t),refetch:this.refetch,promise:this.#s};if(this.options.experimental_prefetchInRender){const m=T=>{R.status==="error"?T.reject(R.error):R.data!==void 0&&T.resolve(R.data)},w=()=>{const T=this.#s=R.promise=Wa();m(T)},S=this.#s;switch(S.status){case"pending":e.queryHash===n.queryHash&&m(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.#o,t=this.createResult(this.#e,this.options);if(this.#r=this.#e.state,this.#a=this.options,this.#r.data!==void 0&&(this.#p=this.#e),Ua(t,e))return;this.#o=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:o}=this.options,r=typeof o=="function"?o():o;if(r==="all"||!r&&!this.#h.size)return!0;const i=new Set(r??this.#h);return this.options.throwOnError&&i.add("error"),Object.keys(this.#o).some(a=>{const c=a;return this.#o[c]!==e[c]&&i.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.#o)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function _b(e,t){return Ht(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function $d(e,t){return _b(e,t)||e.state.data!==void 0&&za(e,t,t.refetchOnMount)}function za(e,t,n){if(Ht(t.enabled,e)!==!1){const o=typeof n=="function"?n(e):n;return o==="always"||o!==!1&&nl(e,t)}return!1}function Dd(e,t,n,o){return(e!==t||Ht(o.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&nl(e,n)}function nl(e,t){return Ht(t.enabled,e)!==!1&&e.isStaleByTime(Mo(t.staleTime,e))}function bb(e,t){return!Ua(e.getCurrentResult(),t)}var ol=x.createContext(void 0),vb=e=>{const t=x.useContext(ol);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},kM=({client:e,children:t})=>(x.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),U_.jsx(ol.Provider,{value:e,children:t})),$p=x.createContext(!1),yb=()=>x.useContext($p);$p.Provider;function wb(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var kb=x.createContext(wb()),Sb=()=>x.useContext(kb);function Eb(e,t){return typeof e=="function"?e(...t):!!e}function Nd(){}var Ib=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},Ab=e=>{x.useEffect(()=>{e.clearReset()},[e])},Rb=({result:e,errorResetBoundary:t,throwOnError:n,query:o,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&o&&(r&&e.data===void 0||Eb(n,[e.error,o])),xb=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)))},Tb=(e,t)=>e.isLoading&&e.isFetching&&!t,Cb=(e,t)=>e?.suspense&&t.isPending,Ld=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Ob(e,t,n){const o=vb(n),r=yb(),i=Sb(),a=o.defaultQueryOptions(e);o.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=r?"isRestoring":"optimistic",xb(a),Ib(a,i),Ab(i);const c=!o.getQueryCache().get(a.queryHash),[l]=x.useState(()=>new t(o,a)),d=l.getOptimisticResult(a),u=!r&&e.subscribed!==!1;if(x.useSyncExternalStore(x.useCallback(f=>{const h=u?l.subscribe(rt.batchCalls(f)):Nd;return l.updateResult(),h},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),x.useEffect(()=>{l.setOptions(a)},[a,l]),Cb(a,d))throw Ld(a,l,i);if(Rb({result:d,errorResetBoundary:i,throwOnError:a.throwOnError,query:o.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw d.error;return o.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!io&&Tb(d,r)&&(c?Ld(a,l,i):o.getQueryCache().get(a.queryHash)?.promise)?.catch(Nd).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function Dp(e,t){return Ob(e,gb,t)}const Pb=()=>{const e=x.useContext(ol)??null,t=x.useMemo(()=>new mb({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 SM(e){return e!=="detached"&&e!=="wedged"}function Np(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function EM(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,o=Np(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:o};case"detached":return e.reconnecting?{title:o?"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:o}:{title:o?"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:o};default:return null}}var ve;(function(e){e.assertEqual=r=>r;function t(r){}e.assertIs=t;function n(r){throw new Error}e.assertNever=n,e.arrayToEnum=r=>{const i={};for(const a of r)i[a]=a;return i},e.getValidEnumValues=r=>{const i=e.objectKeys(r).filter(c=>typeof r[r[c]]!="number"),a={};for(const c of i)a[c]=r[c];return e.objectValues(a)},e.objectValues=r=>e.objectKeys(r).map(function(i){return r[i]}),e.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const a in r)Object.prototype.hasOwnProperty.call(r,a)&&i.push(a);return i},e.find=(r,i)=>{for(const a of r)if(i(a))return a},e.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&isFinite(r)&&Math.floor(r)===r;function o(r,i=" | "){return r.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}e.joinValues=o,e.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(ve||(ve={}));var Ka;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ka||(Ka={}));const B=ve.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),un=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"]),Mb=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class kt extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=o=>{this.issues=[...this.issues,o]},this.addIssues=(o=[])=>{this.issues=[...this.issues,...o]};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(i){return i.message},o={_errors:[]},r=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(r);else if(a.code==="invalid_return_type")r(a.returnTypeError);else if(a.code==="invalid_arguments")r(a.argumentsError);else if(a.path.length===0)o._errors.push(n(a));else{let c=o,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 r(this),o}static assert(t){if(!(t instanceof kt))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ve.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},o=[];for(const r of this.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):o.push(t(r));return{formErrors:o,fieldErrors:n}}get formErrors(){return this.flatten()}}kt.create=e=>new kt(e);const Ho=(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 Lp=Ho;function jb(e){Lp=e}function Zi(){return Lp}const Yi=e=>{const{data:t,path:n,errorMaps:o,issueData:r}=e,i=[...n,...r.path||[]],a={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let c="";const l=o.filter(d=>!!d).slice().reverse();for(const d of l)c=d(a,{data:t,defaultError:c}).message;return{...r,path:i,message:c}},$b=[];function L(e,t){const n=Zi(),o=Yi({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Ho?void 0:Ho].filter(r=>!!r)});e.common.issues.push(o)}class ut{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const o=[];for(const r of n){if(r.status==="aborted")return ee;r.status==="dirty"&&t.dirty(),o.push(r.value)}return{status:t.value,value:o}}static async mergeObjectAsync(t,n){const o=[];for(const r of n){const i=await r.key,a=await r.value;o.push({key:i,value:a})}return ut.mergeObjectSync(t,o)}static mergeObjectSync(t,n){const o={};for(const r of n){const{key:i,value:a}=r;if(i.status==="aborted"||a.status==="aborted")return ee;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||r.alwaysSet)&&(o[i.value]=a.value)}return{status:t.value,value:o}}}const ee=Object.freeze({status:"aborted"}),xo=e=>({status:"dirty",value:e}),ft=e=>({status:"valid",value:e}),Va=e=>e.status==="aborted",Za=e=>e.status==="dirty",so=e=>e.status==="valid",Tr=e=>typeof Promise<"u"&&e instanceof Promise;function Xi(e,t,n,o){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 Fp(e,t,n,o,r){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 hr,mr;class on{constructor(t,n,o,r){this._cachedPath=[],this.parent=t,this.data=n,this._path=o,this._key=r}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 Fd=(e,t)=>{if(so(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new kt(e.common.issues);return this._error=n,this._error}}};function ce(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:o,description:r}=e;if(t&&(n||o))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:r}:{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??o)!==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:r}}class ue{get description(){return this._def.description}_getType(t){return un(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:un(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ut,ctx:{common:t.parent.common,data:t.data,parsedType:un(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Tr(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 o=this.safeParse(t,n);if(o.success)return o.data;throw o.error}safeParse(t,n){var o;const r={common:{issues:[],async:(o=n?.async)!==null&&o!==void 0?o:!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:un(t)},i=this._parseSync({data:t,path:r.path,parent:r});return Fd(r,i)}"~validate"(t){var n,o;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:un(t)};if(!this["~standard"].async)try{const i=this._parseSync({data:t,path:[],parent:r});return so(i)?{value:i.value}:{issues:r.common.issues}}catch(i){!((o=(n=i?.message)===null||n===void 0?void 0:n.toLowerCase())===null||o===void 0)&&o.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(i=>so(i)?{value:i.value}:{issues:r.common.issues})}async parseAsync(t,n){const o=await this.safeParseAsync(t,n);if(o.success)return o.data;throw o.error}async safeParseAsync(t,n){const o={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:un(t)},r=this._parse({data:t,path:o.path,parent:o}),i=await(Tr(r)?r:Promise.resolve(r));return Fd(o,i)}refine(t,n){const o=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;return this._refinement((r,i)=>{const a=t(r),c=()=>i.addIssue({code:j.custom,...o(r)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((o,r)=>t(o)?!0:(r.addIssue(typeof n=="function"?n(o,r):n),!1))}_refinement(t){return new Vt({schema:this,typeName:q.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return tn.create(this,this._def)}nullable(){return $n.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zt.create(this)}promise(){return Go.create(this,this._def)}or(t){return Mr.create([this,t],this._def)}and(t){return jr.create(this,t,this._def)}transform(t){return new Vt({...ce(this._def),schema:this,typeName:q.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Fr({...ce(this._def),innerType:this,defaultValue:n,typeName:q.ZodDefault})}brand(){return new rl({typeName:q.ZodBranded,type:this,...ce(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Ur({...ce(this._def),innerType:this,catchValue:n,typeName:q.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return oi.create(this,t)}readonly(){return Br.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Db=/^c[^\s-]{8,}$/i,Nb=/^[0-9a-z]+$/,Lb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fb=/^[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,Ub=/^[a-z0-9_-]{21}$/i,Bb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Hb=/^[-+]?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)?)??$/,Wb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Gb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ys;const zb=/^(?:(?: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])$/,Kb=/^(?:(?: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])$/,Vb=/^(([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]))$/,Zb=/^(([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])$/,Yb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Xb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Up="((\\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])))",Jb=new RegExp(`^${Up}$`);function Bp(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 Qb(e){return new RegExp(`^${Bp(e)}$`)}function Hp(e){let t=`${Up}T${Bp(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 qb(e,t){return!!((t==="v4"||!t)&&zb.test(e)||(t==="v6"||!t)&&Vb.test(e))}function ev(e,t){if(!Bb.test(e))return!1;try{const[n]=e.split("."),o=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(o));return!(typeof r!="object"||r===null||!r.typ||!r.alg||t&&r.alg!==t)}catch{return!1}}function tv(e,t){return!!((t==="v4"||!t)&&Kb.test(e)||(t==="v6"||!t)&&Zb.test(e))}class Gt extends ue{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==B.string){const i=this._getOrReturnCtx(t);return L(i,{code:j.invalid_type,expected:B.string,received:i.parsedType}),ee}const o=new ut;let r;for(const i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(r=this._getOrReturnCtx(t,r),L(r,{code:j.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),o.dirty());else if(i.kind==="max")t.data.length>i.value&&(r=this._getOrReturnCtx(t,r),L(r,{code:j.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),o.dirty());else if(i.kind==="length"){const a=t.data.length>i.value,c=t.data.length<i.value;(a||c)&&(r=this._getOrReturnCtx(t,r),a?L(r,{code:j.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&L(r,{code:j.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),o.dirty())}else if(i.kind==="email")Wb.test(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{validation:"email",code:j.invalid_string,message:i.message}),o.dirty());else if(i.kind==="emoji")Ys||(Ys=new RegExp(Gb,"u")),Ys.test(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{validation:"emoji",code:j.invalid_string,message:i.message}),o.dirty());else if(i.kind==="uuid")Fb.test(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{validation:"uuid",code:j.invalid_string,message:i.message}),o.dirty());else if(i.kind==="nanoid")Ub.test(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{validation:"nanoid",code:j.invalid_string,message:i.message}),o.dirty());else if(i.kind==="cuid")Db.test(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{validation:"cuid",code:j.invalid_string,message:i.message}),o.dirty());else if(i.kind==="cuid2")Nb.test(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{validation:"cuid2",code:j.invalid_string,message:i.message}),o.dirty());else if(i.kind==="ulid")Lb.test(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{validation:"ulid",code:j.invalid_string,message:i.message}),o.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{r=this._getOrReturnCtx(t,r),L(r,{validation:"url",code:j.invalid_string,message:i.message}),o.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{validation:"regex",code:j.invalid_string,message:i.message}),o.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(t,r),L(r,{code:j.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),o.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(r=this._getOrReturnCtx(t,r),L(r,{code:j.invalid_string,validation:{startsWith:i.value},message:i.message}),o.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(r=this._getOrReturnCtx(t,r),L(r,{code:j.invalid_string,validation:{endsWith:i.value},message:i.message}),o.dirty()):i.kind==="datetime"?Hp(i).test(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{code:j.invalid_string,validation:"datetime",message:i.message}),o.dirty()):i.kind==="date"?Jb.test(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{code:j.invalid_string,validation:"date",message:i.message}),o.dirty()):i.kind==="time"?Qb(i).test(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{code:j.invalid_string,validation:"time",message:i.message}),o.dirty()):i.kind==="duration"?Hb.test(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{validation:"duration",code:j.invalid_string,message:i.message}),o.dirty()):i.kind==="ip"?qb(t.data,i.version)||(r=this._getOrReturnCtx(t,r),L(r,{validation:"ip",code:j.invalid_string,message:i.message}),o.dirty()):i.kind==="jwt"?ev(t.data,i.alg)||(r=this._getOrReturnCtx(t,r),L(r,{validation:"jwt",code:j.invalid_string,message:i.message}),o.dirty()):i.kind==="cidr"?tv(t.data,i.version)||(r=this._getOrReturnCtx(t,r),L(r,{validation:"cidr",code:j.invalid_string,message:i.message}),o.dirty()):i.kind==="base64"?Yb.test(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{validation:"base64",code:j.invalid_string,message:i.message}),o.dirty()):i.kind==="base64url"?Xb.test(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{validation:"base64url",code:j.invalid_string,message:i.message}),o.dirty()):ve.assertNever(i);return{status:o.value,value:t.data}}_regex(t,n,o){return this.refinement(r=>t.test(r),{validation:n,code:j.invalid_string,...K.errToObj(o)})}_addCheck(t){return new Gt({...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,o;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:(o=t?.local)!==null&&o!==void 0?o:!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 Gt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Gt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Gt({...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}}Gt.create=e=>{var t;return new Gt({checks:[],typeName:q.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};function nv(e,t){const n=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,r=n>o?n:o,i=parseInt(e.toFixed(r).replace(".","")),a=parseInt(t.toFixed(r).replace(".",""));return i%a/Math.pow(10,r)}class Pn extends ue{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 i=this._getOrReturnCtx(t);return L(i,{code:j.invalid_type,expected:B.number,received:i.parsedType}),ee}let o;const r=new ut;for(const i of this._def.checks)i.kind==="int"?ve.isInteger(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{code:j.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(o=this._getOrReturnCtx(t,o),L(o,{code:j.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(o=this._getOrReturnCtx(t,o),L(o,{code:j.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?nv(t.data,i.value)!==0&&(o=this._getOrReturnCtx(t,o),L(o,{code:j.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{code:j.not_finite,message:i.message}),r.dirty()):ve.assertNever(i);return{status:r.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,o,r){return new Pn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:o,message:K.toString(r)}]})}_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 o of this._def.checks){if(o.kind==="finite"||o.kind==="int"||o.kind==="multipleOf")return!0;o.kind==="min"?(n===null||o.value>n)&&(n=o.value):o.kind==="max"&&(t===null||o.value<t)&&(t=o.value)}return Number.isFinite(n)&&Number.isFinite(t)}}Pn.create=e=>new Pn({checks:[],typeName:q.ZodNumber,coerce:e?.coerce||!1,...ce(e)});class Mn extends ue{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 o;const r=new ut;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(o=this._getOrReturnCtx(t,o),L(o,{code:j.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(o=this._getOrReturnCtx(t,o),L(o,{code:j.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(o=this._getOrReturnCtx(t,o),L(o,{code:j.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):ve.assertNever(i);return{status:r.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return L(n,{code:j.invalid_type,expected:B.bigint,received:n.parsedType}),ee}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,o,r){return new Mn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:o,message:K.toString(r)}]})}_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:q.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};class Cr extends ue{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==B.boolean){const o=this._getOrReturnCtx(t);return L(o,{code:j.invalid_type,expected:B.boolean,received:o.parsedType}),ee}return ft(t.data)}}Cr.create=e=>new Cr({typeName:q.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});class ao extends ue{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==B.date){const i=this._getOrReturnCtx(t);return L(i,{code:j.invalid_type,expected:B.date,received:i.parsedType}),ee}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return L(i,{code:j.invalid_date}),ee}const o=new ut;let r;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(r=this._getOrReturnCtx(t,r),L(r,{code:j.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),o.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(r=this._getOrReturnCtx(t,r),L(r,{code:j.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),o.dirty()):ve.assertNever(i);return{status:o.value,value:new Date(t.data.getTime())}}_addCheck(t){return new ao({...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}}ao.create=e=>new ao({checks:[],coerce:e?.coerce||!1,typeName:q.ZodDate,...ce(e)});class Ji extends ue{_parse(t){if(this._getType(t)!==B.symbol){const o=this._getOrReturnCtx(t);return L(o,{code:j.invalid_type,expected:B.symbol,received:o.parsedType}),ee}return ft(t.data)}}Ji.create=e=>new Ji({typeName:q.ZodSymbol,...ce(e)});class Or extends ue{_parse(t){if(this._getType(t)!==B.undefined){const o=this._getOrReturnCtx(t);return L(o,{code:j.invalid_type,expected:B.undefined,received:o.parsedType}),ee}return ft(t.data)}}Or.create=e=>new Or({typeName:q.ZodUndefined,...ce(e)});class Pr extends ue{_parse(t){if(this._getType(t)!==B.null){const o=this._getOrReturnCtx(t);return L(o,{code:j.invalid_type,expected:B.null,received:o.parsedType}),ee}return ft(t.data)}}Pr.create=e=>new Pr({typeName:q.ZodNull,...ce(e)});class Wo extends ue{constructor(){super(...arguments),this._any=!0}_parse(t){return ft(t.data)}}Wo.create=e=>new Wo({typeName:q.ZodAny,...ce(e)});class Jn extends ue{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ft(t.data)}}Jn.create=e=>new Jn({typeName:q.ZodUnknown,...ce(e)});class gn extends ue{_parse(t){const n=this._getOrReturnCtx(t);return L(n,{code:j.invalid_type,expected:B.never,received:n.parsedType}),ee}}gn.create=e=>new gn({typeName:q.ZodNever,...ce(e)});class Qi extends ue{_parse(t){if(this._getType(t)!==B.undefined){const o=this._getOrReturnCtx(t);return L(o,{code:j.invalid_type,expected:B.void,received:o.parsedType}),ee}return ft(t.data)}}Qi.create=e=>new Qi({typeName:q.ZodVoid,...ce(e)});class zt extends ue{_parse(t){const{ctx:n,status:o}=this._processInputParams(t),r=this._def;if(n.parsedType!==B.array)return L(n,{code:j.invalid_type,expected:B.array,received:n.parsedType}),ee;if(r.exactLength!==null){const a=n.data.length>r.exactLength.value,c=n.data.length<r.exactLength.value;(a||c)&&(L(n,{code:a?j.too_big:j.too_small,minimum:c?r.exactLength.value:void 0,maximum:a?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),o.dirty())}if(r.minLength!==null&&n.data.length<r.minLength.value&&(L(n,{code:j.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),o.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(L(n,{code:j.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),o.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>r.type._parseAsync(new on(n,a,n.path,c)))).then(a=>ut.mergeArray(o,a));const i=[...n.data].map((a,c)=>r.type._parseSync(new on(n,a,n.path,c)));return ut.mergeArray(o,i)}get element(){return this._def.type}min(t,n){return new zt({...this._def,minLength:{value:t,message:K.toString(n)}})}max(t,n){return new zt({...this._def,maxLength:{value:t,message:K.toString(n)}})}length(t,n){return new zt({...this._def,exactLength:{value:t,message:K.toString(n)}})}nonempty(t){return this.min(1,t)}}zt.create=(e,t)=>new zt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:q.ZodArray,...ce(t)});function ko(e){if(e instanceof He){const t={};for(const n in e.shape){const o=e.shape[n];t[n]=tn.create(ko(o))}return new He({...e._def,shape:()=>t})}else return e instanceof zt?new zt({...e._def,type:ko(e.element)}):e instanceof tn?tn.create(ko(e.unwrap())):e instanceof $n?$n.create(ko(e.unwrap())):e instanceof rn?rn.create(e.items.map(t=>ko(t))):e}class He extends ue{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 L(d,{code:j.invalid_type,expected:B.object,received:d.parsedType}),ee}const{status:o,ctx:r}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof gn&&this._def.unknownKeys==="strip"))for(const d in r.data)a.includes(d)||c.push(d);const l=[];for(const d of a){const u=i[d],f=r.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new on(r,f,r.path,d)),alwaysSet:d in r.data})}if(this._def.catchall instanceof gn){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(d==="strict")c.length>0&&(L(r,{code:j.unrecognized_keys,keys:c}),o.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=r.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new on(r,f,r.path,u)),alwaysSet:u in r.data})}}return r.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=>ut.mergeObjectSync(o,d)):ut.mergeObjectSync(o,l)}get shape(){return this._def.shape()}strict(t){return K.errToObj,new He({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,o)=>{var r,i,a,c;const l=(a=(i=(r=this._def).errorMap)===null||i===void 0?void 0:i.call(r,n,o).message)!==null&&a!==void 0?a:o.defaultError;return n.code==="unrecognized_keys"?{message:(c=K.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new He({...this._def,unknownKeys:"strip"})}passthrough(){return new He({...this._def,unknownKeys:"passthrough"})}extend(t){return new He({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new He({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:q.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new He({...this._def,catchall:t})}pick(t){const n={};return ve.objectKeys(t).forEach(o=>{t[o]&&this.shape[o]&&(n[o]=this.shape[o])}),new He({...this._def,shape:()=>n})}omit(t){const n={};return ve.objectKeys(this.shape).forEach(o=>{t[o]||(n[o]=this.shape[o])}),new He({...this._def,shape:()=>n})}deepPartial(){return ko(this)}partial(t){const n={};return ve.objectKeys(this.shape).forEach(o=>{const r=this.shape[o];t&&!t[o]?n[o]=r:n[o]=r.optional()}),new He({...this._def,shape:()=>n})}required(t){const n={};return ve.objectKeys(this.shape).forEach(o=>{if(t&&!t[o])n[o]=this.shape[o];else{let i=this.shape[o];for(;i instanceof tn;)i=i._def.innerType;n[o]=i}}),new He({...this._def,shape:()=>n})}keyof(){return Wp(ve.objectKeys(this.shape))}}He.create=(e,t)=>new He({shape:()=>e,unknownKeys:"strip",catchall:gn.create(),typeName:q.ZodObject,...ce(t)});He.strictCreate=(e,t)=>new He({shape:()=>e,unknownKeys:"strict",catchall:gn.create(),typeName:q.ZodObject,...ce(t)});He.lazycreate=(e,t)=>new He({shape:e,unknownKeys:"strip",catchall:gn.create(),typeName:q.ZodObject,...ce(t)});class Mr extends ue{_parse(t){const{ctx:n}=this._processInputParams(t),o=this._def.options;function r(i){for(const c of i)if(c.result.status==="valid")return c.result;for(const c of i)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const a=i.map(c=>new kt(c.ctx.common.issues));return L(n,{code:j.invalid_union,unionErrors:a}),ee}if(n.common.async)return Promise.all(o.map(async i=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(r);{let i;const a=[];for(const l of o){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"&&!i&&(i={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const c=a.map(l=>new kt(l));return L(n,{code:j.invalid_union,unionErrors:c}),ee}}get options(){return this._def.options}}Mr.create=(e,t)=>new Mr({options:e,typeName:q.ZodUnion,...ce(t)});const cn=e=>e instanceof Dr?cn(e.schema):e instanceof Vt?cn(e.innerType()):e instanceof Nr?[e.value]:e instanceof jn?e.options:e instanceof Lr?ve.objectValues(e.enum):e instanceof Fr?cn(e._def.innerType):e instanceof Or?[void 0]:e instanceof Pr?[null]:e instanceof tn?[void 0,...cn(e.unwrap())]:e instanceof $n?[null,...cn(e.unwrap())]:e instanceof rl||e instanceof Br?cn(e.unwrap()):e instanceof Ur?cn(e._def.innerType):[];class ws extends ue{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.object)return L(n,{code:j.invalid_type,expected:B.object,received:n.parsedType}),ee;const o=this.discriminator,r=n.data[o],i=this.optionsMap.get(r);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(L(n,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[o]}),ee)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,o){const r=new Map;for(const i of n){const a=cn(i.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(r.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);r.set(c,i)}}return new ws({typeName:q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:r,...ce(o)})}}function Ya(e,t){const n=un(e),o=un(t);if(e===t)return{valid:!0,data:e};if(n===B.object&&o===B.object){const r=ve.objectKeys(t),i=ve.objectKeys(e).filter(c=>r.indexOf(c)!==-1),a={...e,...t};for(const c of i){const l=Ya(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===B.array&&o===B.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let i=0;i<e.length;i++){const a=e[i],c=t[i],l=Ya(a,c);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return n===B.date&&o===B.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class jr extends ue{_parse(t){const{status:n,ctx:o}=this._processInputParams(t),r=(i,a)=>{if(Va(i)||Va(a))return ee;const c=Ya(i.value,a.value);return c.valid?((Za(i)||Za(a))&&n.dirty(),{status:n.value,value:c.data}):(L(o,{code:j.invalid_intersection_types}),ee)};return o.common.async?Promise.all([this._def.left._parseAsync({data:o.data,path:o.path,parent:o}),this._def.right._parseAsync({data:o.data,path:o.path,parent:o})]).then(([i,a])=>r(i,a)):r(this._def.left._parseSync({data:o.data,path:o.path,parent:o}),this._def.right._parseSync({data:o.data,path:o.path,parent:o}))}}jr.create=(e,t,n)=>new jr({left:e,right:t,typeName:q.ZodIntersection,...ce(n)});class rn extends ue{_parse(t){const{status:n,ctx:o}=this._processInputParams(t);if(o.parsedType!==B.array)return L(o,{code:j.invalid_type,expected:B.array,received:o.parsedType}),ee;if(o.data.length<this._def.items.length)return L(o,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ee;!this._def.rest&&o.data.length>this._def.items.length&&(L(o,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...o.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new on(o,a,o.path,c)):null}).filter(a=>!!a);return o.common.async?Promise.all(i).then(a=>ut.mergeArray(n,a)):ut.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new rn({...this._def,rest:t})}}rn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new rn({items:e,typeName:q.ZodTuple,rest:null,...ce(t)})};class $r extends ue{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:o}=this._processInputParams(t);if(o.parsedType!==B.object)return L(o,{code:j.invalid_type,expected:B.object,received:o.parsedType}),ee;const r=[],i=this._def.keyType,a=this._def.valueType;for(const c in o.data)r.push({key:i._parse(new on(o,c,o.path,c)),value:a._parse(new on(o,o.data[c],o.path,c)),alwaysSet:c in o.data});return o.common.async?ut.mergeObjectAsync(n,r):ut.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(t,n,o){return n instanceof ue?new $r({keyType:t,valueType:n,typeName:q.ZodRecord,...ce(o)}):new $r({keyType:Gt.create(),valueType:t,typeName:q.ZodRecord,...ce(n)})}}class qi extends ue{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:o}=this._processInputParams(t);if(o.parsedType!==B.map)return L(o,{code:j.invalid_type,expected:B.map,received:o.parsedType}),ee;const r=this._def.keyType,i=this._def.valueType,a=[...o.data.entries()].map(([c,l],d)=>({key:r._parse(new on(o,c,o.path,[d,"key"])),value:i._parse(new on(o,l,o.path,[d,"value"]))}));if(o.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 ee;(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 ee;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}qi.create=(e,t,n)=>new qi({valueType:t,keyType:e,typeName:q.ZodMap,...ce(n)});class co extends ue{_parse(t){const{status:n,ctx:o}=this._processInputParams(t);if(o.parsedType!==B.set)return L(o,{code:j.invalid_type,expected:B.set,received:o.parsedType}),ee;const r=this._def;r.minSize!==null&&o.data.size<r.minSize.value&&(L(o,{code:j.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&o.data.size>r.maxSize.value&&(L(o,{code:j.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());const i=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return ee;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...o.data.values()].map((l,d)=>i._parse(new on(o,l,o.path,d)));return o.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new co({...this._def,minSize:{value:t,message:K.toString(n)}})}max(t,n){return new co({...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)}}co.create=(e,t)=>new co({valueType:e,minSize:null,maxSize:null,typeName:q.ZodSet,...ce(t)});class jo extends ue{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.function)return L(n,{code:j.invalid_type,expected:B.function,received:n.parsedType}),ee;function o(c,l){return Yi({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Zi(),Ho].filter(d=>!!d),issueData:{code:j.invalid_arguments,argumentsError:l}})}function r(c,l){return Yi({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Zi(),Ho].filter(d=>!!d),issueData:{code:j.invalid_return_type,returnTypeError:l}})}const i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Go){const c=this;return ft(async function(...l){const d=new kt([]),u=await c._def.args.parseAsync(l,i).catch(_=>{throw d.addIssue(o(l,_)),d}),f=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(f,i).catch(_=>{throw d.addIssue(r(f,_)),d})})}else{const c=this;return ft(function(...l){const d=c._def.args.safeParse(l,i);if(!d.success)throw new kt([o(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,i);if(!f.success)throw new kt([r(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new jo({...this._def,args:rn.create(t).rest(Jn.create())})}returns(t){return new jo({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,o){return new jo({args:t||rn.create([]).rest(Jn.create()),returns:n||Jn.create(),typeName:q.ZodFunction,...ce(o)})}}class Dr extends ue{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})}}Dr.create=(e,t)=>new Dr({getter:e,typeName:q.ZodLazy,...ce(t)});class Nr extends ue{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return L(n,{received:n.data,code:j.invalid_literal,expected:this._def.value}),ee}return{status:"valid",value:t.data}}get value(){return this._def.value}}Nr.create=(e,t)=>new Nr({value:e,typeName:q.ZodLiteral,...ce(t)});function Wp(e,t){return new jn({values:e,typeName:q.ZodEnum,...ce(t)})}class jn extends ue{constructor(){super(...arguments),hr.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),o=this._def.values;return L(n,{expected:ve.joinValues(o),received:n.parsedType,code:j.invalid_type}),ee}if(Xi(this,hr)||Fp(this,hr,new Set(this._def.values)),!Xi(this,hr).has(t.data)){const n=this._getOrReturnCtx(t),o=this._def.values;return L(n,{received:n.data,code:j.invalid_enum_value,options:o}),ee}return ft(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(o=>!t.includes(o)),{...this._def,...n})}}hr=new WeakMap;jn.create=Wp;class Lr extends ue{constructor(){super(...arguments),mr.set(this,void 0)}_parse(t){const n=ve.getValidEnumValues(this._def.values),o=this._getOrReturnCtx(t);if(o.parsedType!==B.string&&o.parsedType!==B.number){const r=ve.objectValues(n);return L(o,{expected:ve.joinValues(r),received:o.parsedType,code:j.invalid_type}),ee}if(Xi(this,mr)||Fp(this,mr,new Set(ve.getValidEnumValues(this._def.values))),!Xi(this,mr).has(t.data)){const r=ve.objectValues(n);return L(o,{received:o.data,code:j.invalid_enum_value,options:r}),ee}return ft(t.data)}get enum(){return this._def.values}}mr=new WeakMap;Lr.create=(e,t)=>new Lr({values:e,typeName:q.ZodNativeEnum,...ce(t)});class Go extends ue{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.promise&&n.common.async===!1)return L(n,{code:j.invalid_type,expected:B.promise,received:n.parsedType}),ee;const o=n.parsedType===B.promise?n.data:Promise.resolve(n.data);return ft(o.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Go.create=(e,t)=>new Go({type:e,typeName:q.ZodPromise,...ce(t)});class Vt extends ue{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:o}=this._processInputParams(t),r=this._def.effect||null,i={addIssue:a=>{L(o,a),a.fatal?n.abort():n.dirty()},get path(){return o.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const a=r.transform(o.data,i);if(o.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return ee;const l=await this._def.schema._parseAsync({data:c,path:o.path,parent:o});return l.status==="aborted"?ee:l.status==="dirty"||n.value==="dirty"?xo(l.value):l});{if(n.value==="aborted")return ee;const c=this._def.schema._parseSync({data:a,path:o.path,parent:o});return c.status==="aborted"?ee:c.status==="dirty"||n.value==="dirty"?xo(c.value):c}}if(r.type==="refinement"){const a=c=>{const l=r.refinement(c,i);if(o.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(o.common.async===!1){const c=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});return c.status==="aborted"?ee:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then(c=>c.status==="aborted"?ee:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(r.type==="transform")if(o.common.async===!1){const a=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(!so(a))return a;const c=r.transform(a.value,i);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:o.data,path:o.path,parent:o}).then(a=>so(a)?Promise.resolve(r.transform(a.value,i)).then(c=>({status:n.value,value:c})):a);ve.assertNever(r)}}Vt.create=(e,t,n)=>new Vt({schema:e,typeName:q.ZodEffects,effect:t,...ce(n)});Vt.createWithPreprocess=(e,t,n)=>new Vt({schema:t,effect:{type:"preprocess",transform:e},typeName:q.ZodEffects,...ce(n)});class tn extends ue{_parse(t){return this._getType(t)===B.undefined?ft(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}tn.create=(e,t)=>new tn({innerType:e,typeName:q.ZodOptional,...ce(t)});class $n extends ue{_parse(t){return this._getType(t)===B.null?ft(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}$n.create=(e,t)=>new $n({innerType:e,typeName:q.ZodNullable,...ce(t)});class Fr extends ue{_parse(t){const{ctx:n}=this._processInputParams(t);let o=n.data;return n.parsedType===B.undefined&&(o=this._def.defaultValue()),this._def.innerType._parse({data:o,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Fr.create=(e,t)=>new Fr({innerType:e,typeName:q.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});class Ur extends ue{_parse(t){const{ctx:n}=this._processInputParams(t),o={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:o.data,path:o.path,parent:{...o}});return Tr(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new kt(o.common.issues)},input:o.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new kt(o.common.issues)},input:o.data})}}removeCatch(){return this._def.innerType}}Ur.create=(e,t)=>new Ur({innerType:e,typeName:q.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});class es extends ue{_parse(t){if(this._getType(t)!==B.nan){const o=this._getOrReturnCtx(t);return L(o,{code:j.invalid_type,expected:B.nan,received:o.parsedType}),ee}return{status:"valid",value:t.data}}}es.create=e=>new es({typeName:q.ZodNaN,...ce(e)});const ov=Symbol("zod_brand");class rl extends ue{_parse(t){const{ctx:n}=this._processInputParams(t),o=n.data;return this._def.type._parse({data:o,path:n.path,parent:n})}unwrap(){return this._def.type}}class oi extends ue{_parse(t){const{status:n,ctx:o}=this._processInputParams(t);if(o.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:o.data,path:o.path,parent:o});return i.status==="aborted"?ee:i.status==="dirty"?(n.dirty(),xo(i.value)):this._def.out._parseAsync({data:i.value,path:o.path,parent:o})})();{const r=this._def.in._parseSync({data:o.data,path:o.path,parent:o});return r.status==="aborted"?ee:r.status==="dirty"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:o.path,parent:o})}}static create(t,n){return new oi({in:t,out:n,typeName:q.ZodPipeline})}}class Br extends ue{_parse(t){const n=this._def.innerType._parse(t),o=r=>(so(r)&&(r.value=Object.freeze(r.value)),r);return Tr(n)?n.then(r=>o(r)):o(n)}unwrap(){return this._def.innerType}}Br.create=(e,t)=>new Br({innerType:e,typeName:q.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 Gp(e,t={},n){return e?Wo.create().superRefine((o,r)=>{var i,a;const c=e(o);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=Ud(t,o),h=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;r.addIssue({code:"custom",...f,fatal:h})}});if(!c){const l=Ud(t,o),d=(a=(i=l.fatal)!==null&&i!==void 0?i:n)!==null&&a!==void 0?a:!0;r.addIssue({code:"custom",...l,fatal:d})}}):Wo.create()}const rv={object:He.lazycreate};var q;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(q||(q={}));const iv=(e,t={message:`Input not instance of ${e.name}`})=>Gp(n=>n instanceof e,t),zp=Gt.create,Kp=Pn.create,sv=es.create,av=Mn.create,Vp=Cr.create,cv=ao.create,lv=Ji.create,dv=Or.create,uv=Pr.create,fv=Wo.create,pv=Jn.create,hv=gn.create,mv=Qi.create,gv=zt.create,_v=He.create,bv=He.strictCreate,vv=Mr.create,yv=ws.create,wv=jr.create,kv=rn.create,Sv=$r.create,Ev=qi.create,Iv=co.create,Av=jo.create,Rv=Dr.create,xv=Nr.create,Tv=jn.create,Cv=Lr.create,Ov=Go.create,Bd=Vt.create,Pv=tn.create,Mv=$n.create,jv=Vt.createWithPreprocess,$v=oi.create,Dv=()=>zp().optional(),Nv=()=>Kp().optional(),Lv=()=>Vp().optional(),Fv={string:e=>Gt.create({...e,coerce:!0}),number:e=>Pn.create({...e,coerce:!0}),boolean:e=>Cr.create({...e,coerce:!0}),bigint:e=>Mn.create({...e,coerce:!0}),date:e=>ao.create({...e,coerce:!0})},Uv=ee;var s=Object.freeze({__proto__:null,defaultErrorMap:Ho,setErrorMap:jb,getErrorMap:Zi,makeIssue:Yi,EMPTY_PATH:$b,addIssueToContext:L,ParseStatus:ut,INVALID:ee,DIRTY:xo,OK:ft,isAborted:Va,isDirty:Za,isValid:so,isAsync:Tr,get util(){return ve},get objectUtil(){return Ka},ZodParsedType:B,getParsedType:un,ZodType:ue,datetimeRegex:Hp,ZodString:Gt,ZodNumber:Pn,ZodBigInt:Mn,ZodBoolean:Cr,ZodDate:ao,ZodSymbol:Ji,ZodUndefined:Or,ZodNull:Pr,ZodAny:Wo,ZodUnknown:Jn,ZodNever:gn,ZodVoid:Qi,ZodArray:zt,ZodObject:He,ZodUnion:Mr,ZodDiscriminatedUnion:ws,ZodIntersection:jr,ZodTuple:rn,ZodRecord:$r,ZodMap:qi,ZodSet:co,ZodFunction:jo,ZodLazy:Dr,ZodLiteral:Nr,ZodEnum:jn,ZodNativeEnum:Lr,ZodPromise:Go,ZodEffects:Vt,ZodTransformer:Vt,ZodOptional:tn,ZodNullable:$n,ZodDefault:Fr,ZodCatch:Ur,ZodNaN:es,BRAND:ov,ZodBranded:rl,ZodPipeline:oi,ZodReadonly:Br,custom:Gp,Schema:ue,ZodSchema:ue,late:rv,get ZodFirstPartyTypeKind(){return q},coerce:Fv,any:fv,array:gv,bigint:av,boolean:Vp,date:cv,discriminatedUnion:yv,effect:Bd,enum:Tv,function:Av,instanceof:iv,intersection:wv,lazy:Rv,literal:xv,map:Ev,nan:sv,nativeEnum:Cv,never:hv,null:uv,nullable:Mv,number:Kp,object:_v,oboolean:Lv,onumber:Nv,optional:Pv,ostring:Dv,pipeline:$v,preprocess:jv,promise:Ov,record:Sv,set:Iv,strictObject:bv,string:zp,symbol:lv,transformer:Bd,tuple:kv,undefined:dv,union:vv,unknown:pv,void:mv,NEVER:Uv,ZodIssueCode:j,quotelessJson:Mb,ZodError:kt});const Hd=s.enum(["app_start","sign_in","window_focus","surface_open"]),Zp=s.object({id:s.string().min(1),state:s.enum(["active","paused","disabled"])}).passthrough(),Bv=s.object({tenant_id:s.string().min(1),tenant_name:s.string().optional(),eligible:s.boolean(),endpoint:Zp.nullable()}).passthrough(),Hv=s.object({code:s.string(),message:s.string(),details:s.record(s.unknown()).optional(),retry_after_seconds:s.number().optional()}).passthrough(),Wv=s.object({code:s.string().min(1),count:s.number().int().nonnegative(),session:s.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),Gv=s.object({in_force:s.boolean(),notice_pending:s.boolean().catch(!1)}).passthrough().optional().catch(void 0),IM=s.object({capability:s.number(),consent_account_guard:s.boolean().optional(),state:s.enum(["ready","signed_out","unavailable","update_required"]),account_id:s.string().nullable(),tenant_id:s.string().nullable(),surface_state:s.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:s.object({settings:s.boolean(),inbox:s.boolean(),account_door:s.boolean(),onboarding:s.boolean()}),update_required:s.boolean(),local:s.object({enabled:s.boolean(),enrolled:s.boolean().optional().catch(void 0),onboarding:s.string(),session:s.string()}),status:s.object({tenants:s.array(Bv)}).passthrough().nullable(),consent:s.object({version:s.string().min(1).max(128),text:s.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:s.enum(["served","cached","embedded"])}).nullable(),error:Hv.nullable(),state_note:s.string().nullable().optional(),read_only:s.boolean().optional(),trial_ended:s.object({tenant_id:s.string().min(1),trial_ended_at:s.string().min(1)}).passthrough().nullable().optional().catch(null),delivery_hold:Wv,default_on:Gv}).passthrough(),zv=s.object({value:s.string().min(1).max(192),provider:s.string().max(64).optional(),model_id:s.string().max(128).optional()}),Kv=s.object({preferred:s.string().min(1).max(192).nullable().catch(null),models:s.array(s.unknown()).transform(e=>e.flatMap(t=>{const n=zv.safeParse(t);return n.success?[n.data]:[]}))}),Vv=s.object({version:s.string().min(1),consented_at:s.string().min(1),consented_via:s.string().min(1),current:s.boolean()}).passthrough(),AM=s.object({endpoint:Zp.extend({tenant_id:s.string().min(1),label:s.string().optional(),consent:Vv.nullable().optional(),created_at:s.string().optional(),updated_at:s.string().optional()}).nullable(),settings:s.object({tenant_id:s.string().min(1),eligible:s.boolean(),consent_version:s.string().optional(),consent_required:s.boolean()}).passthrough(),default_on:s.boolean().optional().catch(void 0),share_typing:s.boolean().optional().catch(void 0),screening:Kv.optional().catch(void 0)}).passthrough(),Zv=s.object({kind:s.enum(["endpoint","account"]).optional(),endpoint_id:s.string().min(1).optional(),account_id:s.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"),Wd=s.object({direction:s.enum(["send","receive"]),effect:s.enum(["allow","deny"]),target:Zv,id:s.string().optional()}).passthrough(),Gd=s.object({mode:s.enum(["class_default","listed_only"]),allow:s.number(),deny:s.number()}).passthrough(),RM=s.object({allowlist:s.object({tenant_id:s.string().min(1),entries:s.array(Wd)}).passthrough(),view:s.object({tenant_id:s.string().nullable(),entries:s.array(Wd),directions:s.object({send:Gd,receive:Gd}),class_default:s.literal("cos_cos"),cues:s.object({allow_entry_switches_direction_to_listed_only:s.boolean(),listed_only_affects:s.string(),removing_allow_does_not_stop_open_thread:s.boolean(),deny_stops_pair_both_directions:s.boolean()}).passthrough()}).passthrough()}).passthrough(),xM=s.object({onboarding:s.literal("seen")}).passthrough();function Yv(e){return e?.default_on?.in_force===!0}function TM(e,t){const n=Xv(e),o=t?.endpoint?.consent?.version;return n&&o&&n.version===o?n.text:null}function CM(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function OM(e,t){if(!e||!t||Yv(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(o=>o.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 Xv(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const Jv=8,Xa=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],Hr=200,Qv=6*1024,qv=512;function ts(e,t,n){let o=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const r=[];for(const i of n){if(r.length===qv)break;const c=new URLSearchParams({order_ids:i}).toString().length+1;if(o+c>Qv)break;e.append("order_ids",i),r.push(i),o+=c}return r}function ey(e,t,n){return ts(new URLSearchParams(n),t,e)}const PM=3,ty=4096,MM=128,jM=/^[0-9a-f]{32}$/,ny=/^\.+$/,oy=new RegExp("\\p{Cf}","u"),ry=/[/\\:]/,I=s.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),zd=s.string().min(1).max(256).regex(/^[a-zA-Z0-9_-]+(?::[a-zA-Z0-9_-]+)?$/),iy=s.string().min(1).max(128),hi=s.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),mi=s.string().min(1).max(32768),Yp=/^[a-f0-9]{12}$/,F=s.string().regex(Yp),sy=["network-credentials"],ay=e=>Yp.test(e)||sy.includes(e),Ja=s.string().refine(ay,"not a notifications session id"),Xs=s.string().regex(/^[a-f0-9]{12}$/),Js=s.string().min(1).max(128),cy=s.string().min(1).max(4096),tr=s.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),Qs=s.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),gi=s.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),Kd=s.string().regex(/^[a-f0-9]{32}$/),ly=/^(\/|[A-Za-z]:[\\/])/,qs=s.string().min(1).max(4096).regex(ly),Vd=/^[a-f0-9]{32}$/,de=s.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),Zd=s.string().min(1).max(512).nullish(),_o=s.string().regex(/^[A-Za-z0-9_-]{1,128}$/),bo=s.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),dy=/^pp_[0-9a-f]{16}$/,ea=s.string().regex(dy),uy=["credential_finite_share","credential_inheritance"],To=/^sha256:[0-9a-f]{64}$/,Yd={operation:s.enum(uy),requestDigest:s.string().regex(To),disclosureDigest:s.string().regex(To)},nr=s.string().regex(/^la_[0-9a-f]{16}$/),or=s.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),Xd=s.object({data_b64:s.string().min(1).max(1e6),mime_type:s.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:s.string().max(4096).optional()}).strict(),fy=s.object({digest:s.string().regex(/^[0-9a-f]{32}$/),name:s.string().max(1024).optional(),mime_type:s.string().max(255).optional(),bytes:s.number().int().min(0).optional(),path:s.string().max(4096).optional()}).strict(),Jd=2e5,Qd=8,py=256,hy=100,qd=16,my=256,gy=100,_y=200,by=1e6,vy=s.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),ot=s.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),_i=s.object({kind:s.enum(["agent","team"]),name:ot}).strict(),Xp=s.enum(["claude","codex","omp"]),yy=s.record(s.string(),s.array(s.string().min(1).max(512)).max(5e3)),eu={sources:s.array(Xp).max(3).optional(),sessionIds:yy.optional(),all:s.boolean().optional(),includeSubagents:s.boolean().optional(),includeClearedSegments:s.boolean().optional(),includeMemory:s.boolean().optional(),includeInstructions:s.boolean().optional(),maxSessions:s.number().int().min(1).max(5e3).optional()},ta=s.object({provider:s.string().min(1).max(128),model_id:s.string().min(1).max(512),reasoning_effort:s.string().min(1).max(64).nullable(),fast_mode:s.boolean().nullable().optional()}).strict(),tu=s.object({kind:s.enum(["role","specialist"]).optional(),description:s.string().max(8e3).optional(),instructions:s.string().max(8e3).optional(),tools:s.array(s.string().min(1).max(128)).max(256).optional(),effort:s.string().max(64).optional(),delegate:s.boolean().optional(),action_class:s.enum(["reactive","proactive"]).optional()}).strict(),nu=s.object({name:s.string().min(1).max(64).optional(),description:s.string().max(8e3).optional(),manager:ot.optional(),members:s.array(s.object({role:ot,count:s.number().int().min(1).max(16),kind:s.enum(["agent","team"]),tier:s.enum(["lo","med","hi"]).nullable().optional(),effort:vy.nullable().optional()}).strict()).max(128).optional(),instructions:s.string().max(8e3).optional(),project:s.string().max(8e3).optional()}).strict(),wy=s.record(s.array(s.string().max(1024)).max(100)),na=s.array(I).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),ky=s.array(s.object({kind:s.enum(["human","agent"]),account_id:I,endpoint_id:I.optional()}).strict()).max(50).refine(e=>new Set(e.map(t=>`${t.kind}:${t.account_id}:${t.endpoint_id??""}`)).size===e.length,"Duplicate mention"),ou=s.enum(["minutes","hours","days"]);function Sy(e){return!ny.test(e)}const $M=e=>Li.safeParse(e).success,Li=s.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(Sy),ru=s.enum(["str","int","float","bool","list","dict"]),iu=s.string().max(16384),Ey=2e3,su=s.string().min(1).max(Ey),au=s.string().min(1).max(64),Iy=s.string().min(1).max(64),Ay=s.string().min(1).max(64),cu=s.object({is_active:s.boolean().nullish(),one_time:s.boolean().nullish(),start_time_utc:s.string().max(64).nullish(),end_time_utc:s.string().max(64).nullish()}).strict(),Ry=s.object({conversation_length:s.number().int().optional(),detail_length:s.number().int().optional(),max_learnings_history:s.number().int().optional(),hosting:s.string().max(256).optional(),model_name:s.string().max(1024).optional(),auto_save_conversation:s.boolean().optional()}).strict(),Qa=128,lu=2e3,du=8e3,uu=64,fu=64,ks=e=>[...e].length,qa=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,xy=e=>e===9||e===10||e===11||e===12||e===13||e===133,Ty=e=>e<=31||e>=127&&e<=159,Cy=e=>oy.test(String.fromCodePoint(e)),Oy=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,bi=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},Jp=e=>{const t=[...e];let n=0,o=t.length;for(;n<o&&qa(t[n].codePointAt(0)??0);)n++;for(;o>n&&qa(t[o-1].codePointAt(0)??0);)o--;return t.slice(n,o).join("")},Py=e=>{let t="",n=!1;for(const o of e){if(qa(o.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=o}return t};function My(e){const t=Jp(e);if(!t)return"must not be empty";if(ks(t)>Qa)return`must be at most ${Qa} characters`;if(ry.test(t))return'must not contain "/", "\\" or ":"';if(bi(t,Oy))return"must not contain Unicode bidirectional override characters";if(bi(t,xy))return"must not contain whitespace";if(bi(t,Ty))return"must not contain control characters";if(bi(t,Cy))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 DM(e){return Py(Jp(e).normalize("NFKC").toLowerCase())}function jy(e){return e.trim()?ks(e)>lu?`must be at most ${lu} characters`:null:"must not be empty"}function $y(e){return e.trim()?ks(e)>du?`must be at most ${du} characters`:null:"must not be empty"}function Dy(e){if(e.length>fu)return`must hold at most ${fu} items`;for(const t of e)if(!t.trim()||ks(t)>uu)return`must hold items of 1 to ${uu} characters`;return null}const Ny=e=>My(e)===null,Ly=s.string().refine(Ny,{message:"That is not a name the hub can publish."}),Fy=s.string().refine(e=>$y(e)===null,{message:"That instruction body cannot be published."}),Uy=s.string().refine(e=>jy(e)===null,{message:"That description cannot be published."}),By=s.array(s.string()).refine(e=>Dy(e)===null,{message:"That tool list cannot be published."}),oa={requestId:de.optional(),subscribe:s.boolean().optional(),autoPush:s.boolean().optional(),confirmPublicEgress:s.boolean().optional()},pu=s.object({name:Ly,description:Uy,instructions:Fy,kind:s.enum(["role","specialist"]),when_to_use:s.string(),tools:By,effort:s.string(),delegate:s.boolean(),version:s.string(),categories:s.array(s.string()),tags:s.array(s.string())}).partial().strict(),Hy=s.enum(["team","agent"]),Wy=s.string().min(1).max(64),Gy=s.string().min(1).max(256),Qp=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ra=s.string().regex(Qp,{message:"Letters, digits, dot, underscore and dash; no spaces."}),zy=["planning","active","qa","validation","done","paused","archived"],hu=s.enum(zy),vi=s.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),mu=s.array(s.string().min(1).max(24)).max(8),Sn=s.string().min(1).max(64),Ky=1e3,gu=240,_u=80,Vy=256,Zy=100,Yy=200,Xy=/^[a-z0-9][a-z0-9_-]{0,23}$/;function NM(e){return e?Qp.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 LM(e){return Xy.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const yi=s.enum(["agent","team","skill"]),ia=s.string().min(1).max(128).regex(/\S/),bu=s.enum(Xa),Jy=s.object({visible:s.array(bu).max(Xa.length),more:s.array(bu).max(Xa.length)}).strict(),fn=s.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),vu=s.object({selectionToken:s.string().min(1).max(512),reconcileIds:s.array(fn).max(500).optional(),excludedIds:s.array(fn).max(500).optional()}).strict(),Qy=s.object({operationToken:s.string().min(1).max(512),reconcileIds:s.array(fn).max(500).optional()}).strict(),yu=s.union([s.object({throughSeq:s.number().int().min(0).optional(),receipt:s.literal(!0).optional(),reconcileIds:s.array(fn).max(500).optional(),items:s.array(s.object({id:fn,revision:s.number().int().min(1)}).strict()).min(1).max(500)}).strict(),s.object({sessionId:Ja,throughSeq:s.number().int().min(0),observed:s.array(s.object({id:fn,revision:s.number().int().min(1)}).strict()).max(500)}).strict(),s.object({all:s.literal(!0),throughSeq:s.number().int().min(0),observed:s.array(s.object({id:fn,revision:s.number().int().min(1)}).strict()).max(500)}).strict()]),qy={pointer:"pointerdown",key:"keydown",wheel:"wheel"},ew=s.discriminatedUnion("op",[s.object({op:s.literal("capabilities")}).strict(),s.object({op:s.literal("runtimes.list")}).strict(),s.object({op:s.literal("profiles.list")}).strict(),s.object({op:s.literal("profiles.get"),name:ot}).strict(),s.object({op:s.literal("imports.sources")}).strict(),s.object({op:s.literal("imports.sessions"),source:Xp,includeSubagents:s.boolean().optional()}).strict(),s.object({op:s.literal("imports.preview"),...eu}).strict(),s.object({op:s.literal("imports.start"),...eu}).strict(),s.object({op:s.literal("imports.status"),jobId:s.string().min(1).max(128)}).strict(),s.object({op:s.literal("imports.cancel"),jobId:s.string().min(1).max(128)}).strict(),s.object({op:s.literal("profiles.update"),name:ot,requestId:de,fields:tu,expectedDefinitionRevision:Zd.optional()}).strict(),s.object({op:s.literal("profiles.install"),name:ot,requestId:de}).strict(),s.object({op:s.literal("profiles.create"),name:ot,requestId:de,fields:tu.extend({description:s.string().max(8e3),instructions:s.string().min(1).max(8e3)})}).strict(),s.object({op:s.literal("hub.updates")}).strict(),s.object({op:s.literal("hub.skillPull"),requestId:de,hubId:I,hubSource:s.string().min(1).max(2048),visibility:s.enum(["public","org"]),tenantId:I.nullable(),localAlias:ot,subscribe:s.boolean().optional(),autoPush:s.boolean().optional(),confirmPublicEgress:s.boolean().optional(),dryRun:s.boolean().optional(),adoptionStrategy:s.enum(["merge","keep-local","take-hub"]).optional(),allowLlm:s.boolean().optional(),confirm:s.boolean().optional(),adoptionReceipt:s.string().min(16).max(128).optional()}).strict(),s.object({op:s.literal("hub.skillSubscribe"),requestId:de,hubId:I,hubSource:s.string().min(1).max(2048),visibility:s.enum(["public","org"]),tenantId:I.nullable(),localAlias:ot}).strict(),s.object({op:s.literal("hub.skillUnpull"),requestId:de,linkId:s.string().min(1).max(256)}).strict(),s.object({op:s.literal("hub.skillPublish"),requestId:de,dryRun:s.boolean(),sourceSkill:ot,localAlias:ot,visibility:s.enum(["public","org"]),tenantId:I.nullable(),subscribe:s.boolean(),autoPush:s.boolean(),confirmPublicEgress:s.boolean(),previewReceipt:s.string().min(1).max(4096).optional(),confirmPublish:s.literal(!0).optional()}).strict(),s.object({op:s.literal("hub.links"),kind:s.enum(["agent","team","skill"]).optional()}).strict(),s.object({op:s.literal("hub.policy"),requestId:de,linkId:s.string().min(1).max(256),expectedPolicyRevision:s.string().min(1).max(256),subscribe:s.boolean().optional(),autoPush:s.boolean().optional(),confirmPublicEgress:s.boolean().optional()}).strict(),s.object({op:s.literal("hub.check"),requestId:de,kind:yi.optional(),name:ot.optional(),localId:ia.optional()}).strict(),s.object({op:s.literal("hub.apply"),requestId:de,kind:yi.optional(),name:ot.optional(),localId:ia.optional(),prefer:s.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:s.boolean().optional(),dryRun:s.boolean().optional(),resolveSource:s.literal(!0).optional(),hubSource:s.string().min(1).max(2048).optional(),visibility:s.enum(["public","org"]).optional(),tenantId:s.string().min(1).max(128).nullable().optional()}).strict(),s.object({op:s.literal("hub.applyAll"),requestId:de,kind:yi.optional()}).strict(),s.object({op:s.literal("hub.retry"),requestId:de,kind:yi.optional(),name:ot.optional(),localId:ia.optional()}).strict(),s.object({op:s.literal("hub.push"),requestId:de,linkId:s.string().min(1).max(256),direction:s.literal("push"),dryRun:s.boolean(),previewReceipt:s.string().min(1).max(4096).optional(),confirmPublish:s.literal(!0).optional()}).strict(),s.object({op:s.literal("teams.list")}).strict(),s.object({op:s.literal("teams.get"),name:ot}).strict(),s.object({op:s.literal("teams.effective"),name:ot}).strict(),s.object({op:s.literal("teams.update"),name:ot,requestId:de,fields:nu,expectedDefinitionRevision:Zd.optional()}).strict(),s.object({op:s.literal("teams.create"),requestId:de,fields:nu.extend({name:s.string().min(1).max(64)})}).strict(),s.object({op:s.literal("sessions.list"),limit:s.number().int().min(1).max(500).optional(),include_archived:s.boolean().optional(),include_temporary:s.boolean().optional(),include_peers:s.boolean().optional(),scope_kind:Hy.optional(),scope_name:Wy.optional(),cursor:Gy.optional(),with_counts:s.boolean().optional(),sort:s.literal("activity").optional()}).strict(),s.object({op:s.literal("delegated_cleanup_notice.ack")}).strict(),s.object({op:s.literal("sessions.search"),q:s.string().min(1).max(py),limit:s.number().int().min(1).max(500).optional(),include_archived:s.boolean().optional()}).strict(),s.object({op:s.literal("sessions.archive"),sessionId:F,archived:s.boolean()}).strict(),s.object({op:s.literal("sessions.temporary"),sessionId:F,temporary:s.boolean()}).strict(),s.object({op:s.literal("sessions.delete"),sessionId:F,confirmed:s.literal(!0)}).strict(),s.object({op:s.literal("sessions.create"),requestId:de,cwd:s.string().min(1).max(4096).optional(),target:_i.optional(),purpose:s.literal("agents-config").optional(),model:ta.optional(),draftId:F.optional(),peer:_o.optional(),temporary:s.boolean().optional()}).strict(),s.object({op:s.literal("sessions.preview"),requestId:de,cwd:s.string().min(1).max(4096),target:_i.optional(),model:ta.optional()}).strict(),s.object({op:s.literal("sessions.draft"),requestId:de,cwd:s.string().min(1).max(4096),target:_i.optional(),model:ta.optional()}).strict(),s.object({op:s.literal("sessions.get"),sessionId:F,journalOrder:s.boolean().optional(),orderIds:s.array(s.string().min(1).max(128)).max(512).optional(),peerJournalSource:s.boolean().optional()}).strict(),s.object({op:s.literal("sessions.files"),sessionId:F,scope:s.enum(["family","self"]).optional(),kind:s.string().max(256).optional(),q:s.string().max(256).optional(),sort:s.enum(["recent","name","kind","modified","created","size"]).optional(),order:s.enum(["asc","desc"]).optional(),limit:s.number().int().min(1).max(200).optional(),cursor:s.string().max(8192).optional()}).strict(),s.object({op:s.literal("sessions.files.materialise"),sessionId:F,fileId:s.string().regex(/^[a-f0-9]{16}$/)}).strict(),s.object({op:s.literal("sessions.files.download"),sessionId:F,fileId:s.string().regex(/^[a-f0-9]{16}$/)}).strict(),s.object({op:s.literal("sessions.userAttachments"),sessionId:F}).strict(),s.object({op:s.literal("sessions.userAttachments.materialise"),sessionId:F,digest:s.string().regex(/^[a-f0-9]{32}$/)}).strict(),s.object({op:s.literal("sessions.history"),sessionId:F,beforeId:I.optional(),limit:s.number().int().min(1).max(500).optional(),openFrame:s.boolean().optional(),journalOrder:s.boolean().optional(),orderIds:s.array(s.string().min(1).max(128)).max(512).optional(),peerJournalSource:s.boolean().optional(),sourceRead:s.enum(["metadata","payload"]).optional(),expectedJournalGeneration:s.string().min(1).max(128).optional()}).strict(),s.object({op:s.literal("sessions.checkpoints"),sessionId:F}).strict(),s.object({op:s.literal("sessions.checkpoints.warm"),sessionId:F,ids:s.array(I).max(qd).optional(),limit:s.number().int().min(1).max(qd).optional()}).strict(),s.object({op:s.literal("sessions.find"),sessionId:F,q:s.string().min(1).max(my),limit:s.number().int().min(1).max(_y).optional()}).strict(),s.object({op:s.literal("subagents.transcript"),sessionId:F,childId:F,beforeId:I.optional(),entryId:s.string().min(1).max(128).regex(/^[a-zA-Z0-9_:-]+$/).optional(),limit:s.number().int().min(1).max(500).optional()}).strict(),s.object({op:s.literal("sessions.diff"),sessionId:F,callId:zd,start:s.number().int().min(0).max(1e6),offset:s.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),limit:s.number().int().min(1).max(Hr)}).strict(),s.object({op:s.literal("subagents.diff"),sessionId:F,childId:F,callId:zd,start:s.number().int().min(0).max(1e6),offset:s.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),limit:s.number().int().min(1).max(Hr)}).strict(),s.object({op:s.literal("sessions.message"),sessionId:F,requestId:de,text:s.string().max(Jd),images:s.array(Xd).max(Qd).optional(),files:s.array(fy).max(Jv).optional(),mode:s.enum(["prompt","steer"]).optional(),inputMode:s.enum(["typed","dictated","mixed"]).optional(),inputPath:s.string().max(1024).optional()}).strict(),s.object({op:s.literal("sessions.command"),sessionId:F,requestId:de,command:s.string().regex(/^\/?[A-Za-z]+$/).max(64),args:s.string().max(Jd).optional(),images:s.array(Xd).max(Qd).optional()}).strict(),s.object({op:s.literal("sessions.move"),sessionId:F,requestId:de,cwd:s.string().min(1).max(4096)}).strict(),s.object({op:s.literal("settingsIntents.list"),sessionId:F.optional()}).strict(),s.object({op:s.literal("settingsIntents.submit"),sessionId:F,requestId:de,kind:s.enum(["model","effort","fast","cwd"]),value:s.union([s.string().min(1).max(4096),s.boolean()]),effort:s.string().min(1).max(64).optional()}).strict(),s.object({op:s.literal("settingsIntents.dismiss"),sessionId:F,kind:s.enum(["model","effort","fast","cwd"]),generation:s.number().int().nonnegative()}).strict(),s.object({op:s.literal("sessions.profileActionStatus"),sessionId:F,actionId:s.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),receiptId:s.string().min(1).max(160),profileKind:s.enum(["agent","team"]),profileName:s.string().min(1).max(128),toolCallId:s.string().min(1).max(160)}).strict(),s.object({op:s.literal("sessions.answer"),sessionId:F,epoch:I.optional(),requestId:I.optional(),value:s.string().max(32768).optional(),approved:s.boolean().optional(),questionIndex:s.number().int().min(0).optional(),askId:I.optional(),answers:s.record(s.string(),s.array(s.string().max(32768))).optional(),decline:s.boolean().optional(),revise:s.boolean().optional(),dismiss:s.boolean().optional(),reason:s.enum(["answered_in_chat","moot"]).optional()}).strict(),s.object({op:s.literal("sessions.seen"),sessionId:F,completionToken:s.string().uuid()}).strict(),s.object({op:s.literal("attention.seen"),items:s.array(s.object({sessionId:F,completionToken:s.string().uuid()}).strict()).min(1).max(500)}).strict(),s.object({op:s.literal("sessions.notified"),sessionId:F,completionToken:s.string().uuid()}).strict(),s.object({op:s.literal("tags.list")}).strict(),s.object({op:s.literal("tags.replace"),tags:s.array(s.object({id:s.string().optional(),name:s.string()}).strict())}).strict(),s.object({op:s.literal("sessions.tags"),expected_revision:s.string().optional(),sessionId:F,tags:s.array(s.string()),primary:s.string().nullable()}).strict(),s.object({op:s.literal("sessions.pin"),sessionId:F,pinned:s.boolean()}).strict(),s.object({op:s.literal("sessions.watch"),sessionId:F,subscriptionId:s.string().regex(Vd),visible:s.boolean(),canNotify:s.boolean()}).strict(),s.object({op:s.literal("sessions.warm"),sessionId:F}).strict(),s.object({op:s.literal("sessions.interrupt"),sessionId:F,requestId:de}).strict(),s.object({op:s.literal("supplements.cancel"),sessionId:F,job:Xs,anchor:Js}).strict(),s.object({op:s.literal("supplements.restart"),sessionId:F,job:Xs,anchor:Js}).strict(),s.object({op:s.literal("supplements.steer"),sessionId:F,job:Xs,anchor:Js,text:s.string().min(1).max(500)}).strict(),s.object({op:s.literal("sessions.variables.list"),sessionId:F}).strict(),s.object({op:s.literal("sessions.variables.create"),sessionId:F,key:Li,value:iu,type:ru}).strict(),s.object({op:s.literal("sessions.variables.update"),sessionId:F,key:Li,value:iu,type:ru}).strict(),s.object({op:s.literal("sessions.variables.delete"),sessionId:F,key:Li}).strict(),s.object({op:s.literal("sessions.presence"),subscriptionId:s.string().regex(/^[a-f0-9]{1,64}$/),canNotify:s.boolean(),canNotifyKinds:s.array(s.enum(["complete","error"])).max(4),sessionId:s.string().regex(/^([a-f0-9]{12})?$/),window:s.object({exists:s.boolean(),focused:s.boolean(),visible:s.boolean(),minimized:s.boolean()}).strict()}).strict(),s.object({op:s.literal("legacy.models"),provider:s.string().max(128).optional(),sort:s.enum(["id","name","provider","recommended"]).optional(),direction:s.enum(["ascending","descending"]).optional()}).strict(),s.object({op:s.literal("legacy.models.providers")}).strict(),s.object({op:s.literal("auth.probe"),provider:I}).strict(),s.object({op:s.literal("legacy.agent.upload"),agentId:I}).strict(),s.object({op:s.literal("agent.publish"),agentId:I,document:pu.optional(),...oa,visibility:s.literal("org").optional(),tenantId:I.optional()}).strict(),s.object({op:s.literal("agent.republish"),agentId:I,hubAgentId:I,expectedRemoteRevision:s.string().min(1).max(512).optional(),document:pu.optional(),...oa,visibility:s.literal("org").optional(),tenantId:I.optional()}).strict(),s.object({op:s.literal("team.publish"),teamId:I,...oa,visibility:s.literal("org").optional(),tenantId:I.optional()}).strict(),s.object({op:s.literal("team.pull"),teamId:I,tenantId:I.optional()}).strict(),s.object({op:s.literal("agent.nameAvailability"),name:s.string().min(1).max(Qa)}).strict(),s.object({op:s.literal("legacy.agents.list"),page:s.number().int().min(1).optional(),perPage:s.number().int().min(1).max(500).optional(),name:s.string().max(256).optional(),sort:s.string().max(64).optional(),direction:s.enum(["asc","desc"]).optional()}).strict(),s.object({op:s.literal("legacy.agent.get"),agentId:I}).strict(),s.object({op:s.literal("legacy.agent.history"),agentId:I,page:s.number().int().min(1).optional(),perPage:s.number().int().min(1).max(500).optional()}).strict(),s.object({op:s.literal("legacy.jobs.list"),agentId:I.optional(),status:s.string().max(64).optional()}).strict(),s.object({op:s.literal("legacy.job.get"),jobId:I}).strict(),s.object({op:s.literal("legacy.schedules.list"),page:s.number().int().min(1).optional(),perPage:s.number().int().min(1).max(100).optional()}).strict(),s.object({op:s.literal("legacy.agent.schedules.list"),agentId:I,page:s.number().int().min(1).optional(),perPage:s.number().int().min(1).max(100).optional()}).strict(),s.object({op:s.literal("legacy.agent.schedule.create"),agentId:I,schedule:cu.extend({prompt:s.string().max(64e3),interval:s.number().int().min(1),unit:ou})}).strict(),s.object({op:s.literal("legacy.schedule.get"),scheduleId:I}).strict(),s.object({op:s.literal("legacy.schedule.edit"),scheduleId:I,schedule:cu.extend({prompt:s.string().max(64e3).nullish(),interval:s.number().int().min(1).nullish(),unit:ou.nullish()})}).strict(),s.object({op:s.literal("legacy.schedule.remove"),scheduleId:I}).strict(),s.object({op:s.literal("legacy.agent.create"),agent:s.record(s.unknown())}).strict(),s.object({op:s.literal("legacy.agent.update"),agentId:I,update:s.record(s.unknown())}).strict(),s.object({op:s.literal("legacy.agent.delete"),agentId:I}).strict(),s.object({op:s.literal("legacy.agent.conversation.clear"),agentId:I}).strict(),s.object({op:s.literal("legacy.agent.systemPrompt.get"),agentId:I}).strict(),s.object({op:s.literal("legacy.agent.systemPrompt.update"),agentId:I,systemPrompt:s.string().max(by)}).strict(),s.object({op:s.literal("legacy.agent.download"),agentId:I}).strict(),s.object({op:s.literal("legacy.job.cancel"),jobId:I}).strict(),s.object({op:s.literal("commands.list")}).strict(),s.object({op:s.literal("commands.entities"),sessionId:F,command:I,name:s.string().max(128).optional()}).strict(),s.object({op:s.literal("models.catalogue"),live:s.boolean().optional(),scope:s.enum(["usable","all"]).optional()}).strict(),s.object({op:s.literal("usage.get"),provider:I.optional(),live:s.boolean().optional(),refresh:s.boolean().optional()}).strict(),s.object({op:s.literal("usage.reset"),provider:I,credentialRef:iy.optional(),identity:s.string().min(1).max(256).optional(),redeemRequestId:s.string().uuid()}).strict(),s.object({op:s.literal("quota.notice"),provider:I.optional(),model:s.string().min(1).max(200).optional(),refresh:s.boolean().optional()}).strict(),s.object({op:s.literal("analytics.get"),sessionId:F.optional(),sinceMs:s.number().int().nonnegative().optional(),untilMs:s.number().int().nonnegative().optional(),days:s.number().int().min(1).max(366).optional()}).strict(),s.object({op:s.literal("analytics.models"),sessionId:F.optional(),sinceMs:s.number().int().nonnegative().optional(),untilMs:s.number().int().nonnegative().optional(),days:s.number().int().min(1).max(366).optional()}).strict(),s.object({op:s.literal("info.get")}).strict(),s.object({op:s.literal("sessions.report"),sessionId:F,recentLimit:s.number().int().min(0).max(50).optional()}).strict(),s.object({op:s.literal("skills.list"),sessionId:F.optional(),cwd:cy.optional(),name:tr.optional()}).strict(),s.object({op:s.literal("skills.create"),requestId:de,name:tr,copyFrom:tr}).strict(),s.object({op:s.literal("skills.update"),requestId:de,name:tr,expectedFingerprint:s.string().regex(/^[a-f0-9]{64}$/),files:s.array(s.object({path:s.string().min(1).max(240),content:s.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),s.object({op:s.literal("skills.remove"),requestId:de,name:tr,discardLocalChanges:s.boolean()}).strict(),s.object({op:s.literal("sessions.failovers"),sessionId:F}).strict(),s.object({op:s.literal("sessions.credential"),sessionId:F,action:s.enum(["list","store","forget"]),key:hi.optional(),value:mi.optional(),confirmed:s.boolean().optional()}).strict(),s.object({op:s.literal("sessions.fork"),sessionId:F,requestId:de,message:s.string().max(2e5).optional(),boundary:s.enum(["next_safe","at_entry"]).optional(),entryId:s.string().max(128).optional(),autoTag:s.boolean().optional()}).strict(),s.object({op:s.literal("sessions.stop"),requestId:de,targets:s.array(F).min(1).max(100),confirmed:s.literal(!0)}).strict(),s.object({op:s.literal("sessions.aside"),sessionId:F,requestId:de,text:s.string().min(1).max(32768),asideId:de.optional(),subscriptionId:s.string().regex(Vd).optional()}).strict(),s.object({op:s.literal("sessions.adopt"),sessionId:F,requestId:de,asideId:de,confirmed:s.literal(!0)}).strict(),s.object({op:s.literal("sessions.aside.get"),sessionId:F,asideId:de}).strict(),s.object({op:s.literal("sessions.aside.close"),sessionId:F,asideId:de}).strict(),s.object({op:s.literal("wakes.list"),limit:s.number().int().min(1).max(500).optional(),includeDormant:s.boolean().optional()}).strict(),s.object({op:s.literal("wakes.create"),requestId:de,sessionId:F.optional(),cwd:s.string().min(1).max(4096).optional(),target:_i.optional(),message:su,in:s.string().min(1).max(64).optional(),at:s.string().min(1).max(64).optional(),every:s.string().min(1).max(64).optional(),until:s.string().min(1).max(64).optional(),limit:s.number().int().min(1).optional(),title:s.string().min(1).max(200).optional()}).strict(),s.object({op:s.literal("wakes.edit"),sessionId:F,wakeId:au,message:su.optional(),in:s.string().min(1).max(64).optional(),at:s.string().min(1).max(64).optional(),every:s.string().min(1).max(64).optional(),until:s.string().min(1).max(64).optional(),limit:s.number().int().min(1).optional()}).strict(),s.object({op:s.literal("wakes.remove"),sessionId:F,wakeId:au}).strict(),s.object({op:s.literal("monitors.list"),limit:s.number().int().min(1).max(500).optional(),includeDormant:s.boolean().optional()}).strict(),s.object({op:s.literal("monitors.cancel"),sessionId:F,monitorId:Iy}).strict(),s.object({op:s.literal("jobs.cancel"),sessionId:F,jobId:Ay}).strict(),s.object({op:s.literal("mcp.list"),sessionId:F}).strict(),s.object({op:s.literal("mcp.credentials.store"),sessionId:F,name:s.string().min(1).max(256),values:s.record(s.string().min(1).max(128),s.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:s.array(s.string().min(1).max(128)).max(32)}).strict(),s.object({op:s.literal("mcp.control"),sessionId:F,control:s.object({action:s.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:Qs.optional(),scope:s.enum(["global","project"]).optional(),command:s.string().min(1).max(4096).optional(),args:s.array(s.string().max(8192)).max(128).optional(),env:s.record(gi).optional(),url:s.string().max(4096).optional(),headers:s.record(gi).optional(),oauth:s.boolean().optional(),confirmed:s.boolean().optional(),operation_id:Kd.optional()}).strict()}).strict(),s.object({op:s.literal("mcp.catalog"),cwd:qs.optional(),sessionId:F.optional()}).strict(),s.object({op:s.literal("mcp.catalog.control"),cwd:qs.optional(),control:s.object({action:s.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:Qs.optional(),scope:s.enum(["global","project"]).optional(),command:s.string().min(1).max(4096).optional(),args:s.array(s.string().max(8192)).max(128).optional(),env:s.record(gi).optional(),url:s.string().max(4096).optional(),headers:s.record(gi).optional(),confirmed:s.boolean().optional(),operation_id:Kd.optional()}).strict()}).strict(),s.object({op:s.literal("mcp.catalog.credentials"),header:s.string().min(1).max(128).optional(),cwd:qs.optional(),name:Qs,values:s.record(s.string().min(1).max(128),s.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:s.array(s.string().min(1).max(128)).max(32)}).strict(),s.object({op:s.literal("radient.request"),control:s.object({operation:s.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:de.optional(),tenant_id:I.optional(),account_id:I.optional(),agent_id:I.optional(),comment_id:I.optional(),team_id:I.optional(),skill_id:I.optional(),query:s.record(s.union([s.string().max(1024),s.number().int()])).optional(),payload:s.record(s.unknown()).optional(),confirmed:s.boolean().optional()}).strict()}).strict(),s.object({op:s.literal("providers.list")}).strict(),s.object({op:s.literal("accounts.list")}).strict(),s.object({op:s.literal("accounts.remove"),accountId:s.number().int().positive(),confirmed:s.literal(!0)}).strict(),s.object({op:s.literal("tunnel.setup.read"),credentialId:s.number().int().positive().optional()}).strict(),s.object({op:s.literal("tunnel.setup.plan"),credentialId:s.number().int().positive().optional()}).strict(),s.object({op:s.literal("tunnel.setup.run"),credentialId:s.number().int().positive(),acceptMonthlyPrice:s.string().min(1).max(64).optional()}).strict(),s.object({op:s.literal("mobile.doctor")}).strict(),s.object({op:s.literal("auth.start"),provider:I}).strict(),s.object({op:s.literal("auth.status"),id:I}).strict(),s.object({op:s.literal("auth.input"),id:I,promptId:I,value:mi}).strict(),s.object({op:s.literal("auth.cancel"),id:I}).strict(),s.object({op:s.literal("auth.key"),provider:I,value:mi}).strict(),s.object({op:s.literal("auth.logout"),provider:I}).strict(),s.object({op:s.literal("agent_messages.status"),boundary:Hd}).strict(),s.object({op:s.literal("agent_messages.enable"),expected_account_id:I,tenant_id:I,state:s.literal("active"),consent_version:s.string().min(1).max(128),consented_via:s.literal("dialog")}).strict(),s.object({op:s.literal("agent_messages.settings"),tenant_id:I.optional()}).strict(),s.object({op:s.literal("agent_messages.settings.put"),expected_account_id:I,tenant_id:I.optional(),consent_version:s.string().min(1).max(128).optional(),consented_via:s.enum(["dialog","settings"]).optional(),label:s.string().min(1).max(128).optional(),state:s.enum(["active","paused","disabled"])}).strict(),s.object({op:s.literal("agent_messages.onboarding.dismiss")}).strict(),s.object({op:s.literal("agent_messages.allowlist.get"),tenant_id:I.optional()}).strict(),s.object({op:s.literal("agent_messages.allowlist.put"),expected_account_id:I,tenant_id:I.optional(),entries:s.array(s.object({direction:s.enum(["send","receive"]),effect:s.enum(["allow","deny"]),target:s.object({endpoint_id:I.optional(),account_id:I.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(),s.object({op:s.literal("team_bridge.conversations.list"),scope:s.literal("account").optional(),tenant_id:I.optional(),limit:s.number().int().min(1).max(100).optional(),cursor:s.string().min(1).max(512).optional(),before:s.string().min(1).max(64).optional(),status:s.enum(["open","archived"]).optional()}).strict(),s.object({op:s.literal("team_bridge.conversations.get"),conversation_id:I,tenant_id:I.optional()}).strict(),s.object({op:s.literal("team_bridge.conversations.create"),expected_account_id:I.optional(),tenant_id:I.optional(),kind:s.enum(["dm","group","channel"]),name:s.string().min(1).max(128).optional(),topic:s.string().min(1).max(512).optional(),visibility:s.enum(["private","tenant"]).optional(),agent_capable:s.boolean().optional(),members:s.array(s.object({account_id:I,kind:s.enum(["human","agent"]),endpoint_id:I.optional(),display_label:s.string().min(1).max(64)}).strict()).max(500)}).strict(),s.object({op:s.literal("team_bridge.conversations.lifecycle"),expected_account_id:I.optional(),tenant_id:I.optional(),conversation_id:I,action:s.enum(["archive","unarchive","join","leave"])}).strict(),s.object({op:s.literal("team_bridge.conversations.join"),expected_account_id:I.optional(),conversation_id:I,tenant_id:I.optional()}).strict(),s.object({op:s.literal("team_bridge.conversations.leave"),expected_account_id:I.optional(),conversation_id:I,tenant_id:I.optional()}).strict(),s.object({op:s.literal("team_bridge.conversations.notify"),expected_account_id:I.optional(),conversation_id:I,tenant_id:I.optional(),notify:s.enum(["all","mention","mute"])}).strict(),s.object({op:s.literal("team_bridge.conversations.agent_notify"),expected_account_id:I.optional(),conversation_id:I,tenant_id:I.optional(),notify:s.enum(["all","mention","mute"])}).strict(),s.object({op:s.literal("team_bridge.conversations.members.add"),expected_account_id:I.optional(),conversation_id:I,tenant_id:I.optional(),members:s.array(s.object({account_id:I,kind:s.enum(["human","agent"]),endpoint_id:I.optional(),display_label:s.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),s.object({op:s.literal("team_bridge.conversations.members.remove"),expected_account_id:I.optional(),tenant_id:I.optional(),conversation_id:I,account_id:I}).strict(),s.object({op:s.literal("team_bridge.conversations.delete"),expected_account_id:I.optional(),tenant_id:I.optional(),conversation_id:I}).strict(),s.object({op:s.literal("team_bridge.conversations.consent"),expected_account_id:I.optional(),conversation_id:I,account_id:I,decision:s.enum(["accept","decline","withdraw"]),consent_version:s.string().min(1).max(128).optional(),endpoint_id:I.optional(),tenant_id:I.optional()}).strict(),s.object({op:s.literal("team_bridge.owner_audit.conversations"),expected_account_id:I,tenant_id:I,limit:s.number().int().min(1).max(100).optional(),cursor:s.string().min(1).optional()}).strict(),s.object({op:s.literal("team_bridge.owner_audit.messages"),expected_account_id:I,tenant_id:I,conversation_id:I,limit:s.number().int().min(1).max(100).optional(),before_seq:s.number().int().nonnegative().optional()}).strict(),s.object({op:s.literal("team_bridge.owner_audit.replies"),expected_account_id:I,tenant_id:I,conversation_id:I,message_id:I,limit:s.number().int().min(1).max(100).optional(),after_seq:s.number().int().nonnegative().optional(),before_seq:s.number().int().positive().optional(),order:s.enum(["asc","desc"]).optional()}).strict(),s.object({op:s.literal("team_bridge.messages.list"),conversation_id:I,tenant_id:I.optional(),limit:s.number().int().min(1).max(100).optional(),before_seq:s.number().int().nonnegative().optional(),endpoint_id:I.optional()}).strict(),s.object({op:s.literal("team_bridge.typing.get"),conversation_id:I,tenant_id:I}).strict(),s.object({op:s.enum(["team_bridge.typing.set","team_bridge.typing.clear"]),conversation_id:I,tenant_id:I,expected_account_id:I,thread_root_id:I.optional()}).strict(),s.object({op:s.literal("agent_messages.settings.share_typing"),expected_account_id:I,share_typing:s.boolean()}).strict(),s.object({op:s.literal("agent_messages.settings.screening_model"),expected_account_id:I,screening_model:s.string().max(192)}).strict(),s.object({op:s.literal("team_bridge.reactions.toggle"),conversation_id:I,message_id:I,expected_account_id:I,tenant_id:I,emoji:s.string().min(1),active:s.boolean()}).strict(),s.object({op:s.literal("team_bridge.messages.send"),expected_account_id:I.optional(),conversation_id:I,tenant_id:I.optional(),client_ref:I,body:s.string(),agent_label:s.string().min(1).max(64).optional(),thread_root_id:I.optional(),attachment_ids:na.optional(),files:s.array(I).min(1).max(10).refine(e=>new Set(e).size===e.length,"Duplicate file").optional(),mentions:ky.optional()}).strict(),s.object({op:s.literal("team_bridge.messages.replies"),conversation_id:I,message_id:I,expected_account_id:I,tenant_id:I,limit:s.number().int().min(1).max(100).optional(),after_seq:s.number().int().nonnegative().optional(),before_seq:s.number().int().positive().optional(),order:s.enum(["asc","desc"]).optional()}).strict(),s.object({op:s.literal("team_bridge.scheduled.list"),tenant_id:I}).strict(),s.object({op:s.literal("team_bridge.scheduled.create"),tenant_id:I,conversation_id:I,client_ref:I,body:s.string(),send_at:s.string().datetime({offset:!0}),attachment_ids:na.optional(),thread_root_id:I.optional()}).strict(),s.object({op:s.literal("team_bridge.scheduled.update"),tenant_id:I,scheduled_id:I,body:s.string().optional(),send_at:s.string().datetime({offset:!0}).optional(),attachment_ids:na.optional(),expected_version:s.number().int().nonnegative().optional()}).strict(),s.object({op:s.literal("team_bridge.attachments.delete"),tenant_id:I,conversation_id:I,attachment_id:I,expected_account_id:I}).strict(),s.object({op:s.literal("team_bridge.scheduled.cancel"),tenant_id:I,scheduled_id:I}).strict(),s.object({op:s.literal("team_bridge.read"),expected_account_id:I.optional(),conversation_id:I,tenant_id:I.optional(),seq:s.number().int().nonnegative().optional(),muted:s.boolean().optional()}).strict(),s.object({op:s.literal("team_bridge.thread_read"),expected_account_id:I,conversation_id:I,message_id:I,tenant_id:I,seq:s.number().int().nonnegative()}).strict(),s.object({op:s.literal("team_bridge.unread"),scope:s.literal("account").optional(),tenant_id:I.optional()}).strict(),s.object({op:s.literal("team_bridge.directory"),tenant_id:I}).strict(),s.object({op:s.literal("team_bridge.status"),boundary:Hd.optional()}).strict(),s.object({op:s.literal("team_bridge.link_preview.resolve"),url:s.string().min(1).max(ty),index:s.number().int().nonnegative(),expectedAccountId:I}).strict(),s.object({op:s.literal("settings.list")}).strict(),s.object({op:s.literal("settings.edit"),key:hi,value:s.unknown().refine(e=>e!==void 0,"A setting value is required."),base:wy.optional()}).strict(),s.object({op:s.literal("settings.reset"),key:hi}).strict(),s.object({op:s.literal("tts.paths")}).strict(),s.object({op:s.literal("notification_sounds.list")}).strict(),s.object({op:s.literal("notification_sounds.rename"),id:s.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/),name:s.string().min(1).max(200)}).strict(),s.object({op:s.literal("notification_sounds.remove"),id:s.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)}).strict(),s.object({op:s.literal("config.get")}).strict(),s.object({op:s.literal("config.update"),value:Ry}).strict(),s.object({op:s.literal("instructions.get")}).strict(),s.object({op:s.literal("instructions.update"),content:s.string().max(64e3)}).strict(),s.object({op:s.literal("credentials.list")}).strict(),s.object({op:s.literal("credentials.update"),key:hi,value:mi}).strict(),s.object({op:s.literal("peers.list")}).strict(),s.object({op:s.literal("networks.list")}).strict(),s.object({op:s.literal("networks.invite"),networkId:_o,role:s.enum(["read","drive","admin"]),deviceId:_o.optional()}).strict(),s.object({op:s.literal("networks.member.remove"),networkId:_o,deviceId:_o,confirm:s.string().min(1).max(256)}).strict(),s.object({op:s.literal("sessions.transfer"),sessionId:F,to:s.union([s.literal("local"),_o]),keep:s.boolean().optional(),waitS:s.number().min(0).max(300).optional(),requestId:de.optional()}).strict(),s.object({op:s.literal("profileProposals.list"),state:s.enum(["pending","all"]).optional()}).strict(),s.object({op:s.literal("profileProposals.get"),proposalId:ea}).strict(),s.object({op:s.literal("profileProposals.accept"),proposalId:ea,requestId:de,after:s.record(s.string().regex(/^[a-z][a-z0-9_]{0,63}$/),s.unknown()).optional()}).strict(),s.object({op:s.literal("profileProposals.reject"),proposalId:ea,requestId:de,note:s.string().max(2e3).optional()}).strict(),s.object({op:s.literal("approvals.list")}).strict(),s.object({op:s.literal("approvals.approve"),approvalId:bo}).strict(),s.object({op:s.literal("approvals.deny"),approvalId:bo}).strict(),...["approvals.approveOperation","approvals.applyOperation"].map(e=>s.object({op:s.literal(e),approvalId:bo,operation:s.enum(["profile_save","pair_phone"]),requestDigest:s.string().regex(To),disclosureDigest:s.string().regex(To)}).strict()),s.object({op:s.literal("approvals.pairAck"),approvalId:bo,requestDigest:s.string().regex(To),disclosureDigest:s.string().regex(To),code:s.string().min(1).max(32).optional()}).strict(),s.object({op:s.literal("devices.list")}).strict(),s.object({op:s.literal("devices.remove"),deviceId:s.string().regex(/^[A-Za-z0-9]{1,64}$/)}).strict(),s.object({op:s.literal("operator.setup.read")}).strict(),s.object({op:s.literal("operator.setup.run")}).strict(),s.object({op:s.literal("mobile.password")}).strict(),s.object({op:s.literal("approvals.approveCredential"),approvalId:bo,...Yd}).strict(),s.object({op:s.literal("approvals.applyCredential"),approvalId:bo,...Yd}).strict(),s.object({op:s.literal("asks.list")}).strict(),s.object({op:s.literal("projects.list")}).strict(),s.object({op:s.literal("projects.get"),key:Sn}).strict(),s.object({op:s.literal("projects.create"),name:ra,description:s.string().max(gu).optional(),status:hu.optional(),tags:mu.optional()}).strict(),s.object({op:s.literal("projects.update"),key:Sn,fields:s.object({name:ra.optional(),title:s.string().max(80).optional(),owner:s.string().max(80).optional(),team:s.string().max(80).optional(),description:s.string().max(gu).optional(),status:hu.optional(),progress:s.string().max(Ky).optional(),tags:mu.optional(),start_date:vi.optional(),target_date:vi.optional(),completed_at:vi.optional(),estimate:s.number().positive().max(1e3).optional(),estimate_unit:s.enum(["points","days"]).optional()}).strict(),force_done:s.boolean().optional()}).strict(),s.object({op:s.literal("projects.delete"),key:Sn,confirmed_name:ra}).strict(),s.object({op:s.literal("projects.link"),key:Sn,sessionId:F}).strict(),s.object({op:s.literal("projects.unlink"),key:Sn,sessionId:F}).strict(),s.object({op:s.literal("projects.milestone"),key:Sn,name:s.string().min(1).max(_u),targetDate:vi.optional(),completed:s.boolean().optional()}).strict(),s.object({op:s.literal("projects.milestone.remove"),key:Sn,name:s.string().min(1).max(_u)}).strict(),s.object({op:s.literal("projects.request_update"),key:Sn}).strict(),s.object({op:s.literal("projects.for_session"),sessionId:F}).strict(),s.object({op:s.literal("projects.search"),q:s.string().min(1).max(Vy),limit:s.number().int().min(1).max(Yy).optional()}).strict(),s.object({op:s.literal("aida.status")}).strict(),s.object({op:s.literal("aida.control"),action:s.enum(["open","pause","resume","greet","status"])}).strict(),s.object({op:s.literal("code_requests.list"),sessionId:F}).strict(),s.object({op:s.literal("code_requests.refresh"),sessionId:F,keys:s.array(s.string().min(1).max(512)).max(256).optional(),force:s.boolean().optional()}).strict(),s.object({op:s.literal("static.sign"),route:s.enum(["images","videos","audio","html"]),path:s.string().min(1),ttlS:s.number().int().min(1).max(3600).optional()}).strict(),s.object({op:s.literal("library.list"),scope:s.enum(["final","all"]).optional(),q:s.string().max(512).optional(),category:s.string().min(1).max(64).optional(),kind:s.string().min(1).max(64).optional(),origin_group:s.enum(["generated","created","mentioned"]).optional(),origin:s.string().min(1).max(64).optional(),tag:s.string().min(1).max(128).optional(),tag_mode:s.enum(["all","any"]).optional(),highlighted:s.boolean().optional(),organized:s.boolean().optional(),favorite:s.boolean().optional(),session:s.string().min(1).max(12).optional(),session_id:s.string().min(1).max(512).optional(),sort:s.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:s.enum(["asc","desc"]).optional(),limit:s.number().int().min(1).max(200).optional(),cursor:s.string().max(512).optional()}).strict(),s.object({op:s.literal("library.get"),id:nr}).strict(),s.object({op:s.literal("library.update"),id:nr,fields:s.object({name:s.string().max(200).optional(),description:s.string().max(2e3).optional(),favorite:s.boolean().optional(),locked:s.boolean().optional(),archived:s.boolean().optional()}).strict()}).strict(),s.object({op:s.literal("library.tags")}).strict(),s.object({op:s.literal("library.tags.create"),name:s.string().trim().min(1).max(24),category:s.string().min(1).max(64).optional()}).strict(),s.object({op:s.literal("library.tags.update"),id:or,name:s.string().trim().min(1).max(24).optional(),category:s.string().min(1).max(64).optional()}).strict(),s.object({op:s.literal("library.tags.delete"),id:or}).strict(),s.object({op:s.literal("library.tags.merge"),id:or,into:or}).strict(),s.object({op:s.literal("library.tags.assign"),id:nr,tags:s.array(or).max(64),primary:s.string().max(128).optional()}).strict(),s.object({op:s.literal("library.chat.link"),id:nr,sessionId:F}).strict(),s.object({op:s.literal("library.chat.clear"),id:nr}).strict(),s.object({op:s.literal("library.librarian"),action:s.enum(["status","open","pause","resume","run"]).optional()}).strict(),s.object({op:s.literal("sidebar_layout.get")}).strict(),s.object({op:s.literal("sidebar_layout.set"),layout:Jy}).strict(),s.object({op:s.literal("notifications.list"),preview:s.literal(!0).optional(),includeAskReads:s.boolean().optional(),countSessionIds:s.array(F).max(50).optional(),includeSessionCounts:s.literal(!0).optional(),kind:s.enum(["all","asks","updates"]).optional(),bulkPriority:s.enum(["any","high","normal_up"]).optional(),state:s.enum(["unread","all","dismissed"]).optional(),source:s.enum(["notify","ask"]).optional(),priority:s.enum(["high","normal","low"]).optional(),sessionId:Ja.optional(),throughSeq:s.number().int().min(0).optional(),cursor:s.string().min(1).max(64).optional(),limit:s.number().int().min(1).max(100).optional()}).strict(),s.object({op:s.literal("notifications.get"),id:fn}).strict(),s.object({op:s.literal("notifications.count")}).strict(),s.object({op:s.literal("notifications.read"),verb:s.enum(["read","unread","undo"]),target:s.union([yu,vu,Qy])}).strict(),s.object({op:s.literal("notifications.dismiss"),verb:s.enum(["dismiss","undismiss"]),target:s.union([yu,vu])}).strict(),s.object({op:s.literal("notifications.seen"),items:s.array(s.object({id:fn,revision:s.number().int().min(1),anchorId:s.string().min(1).max(256),visibleSinceMs:s.number().int().min(0)}).strict()).min(1).max(50),evidence:s.object({sessionId:Ja,inputKind:s.enum(["pointer","key","wheel"]),inputAtMs:s.number().int().min(0),visibleSinceMs:s.number().int().min(0)}).strict()}).strict()]);ew.superRefine((e,t)=>{if(e.op==="usage.reset"&&!e.credentialRef&&!e.identity&&t.addIssue({code:s.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:s.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:s.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:s.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(o=>n.includes(o)))&&t.addIssue({code:s.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:s.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:s.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:s.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:s.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:s.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,o=e.localId!==void 0,r=e.op!=="hub.check";if(n&&o||r&&!n&&!o||o&&e.kind===void 0){t.addIssue({code:s.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:s.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:s.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:s.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:s.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:s.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:s.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:s.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:s.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:s.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:s.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:s.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:s.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:s.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:s.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:s.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:s.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:s.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:s.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:s.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:s.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:s.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const We={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed",serverUpdating:"transient.server-updating"},qp="service is preparing a safe reload; retry shortly",eh="serve_reloading";function tw(e,t){if(e!==503||t===null||typeof t!="object")return!1;const n=t.detail;return n===qp?!0:n!==null&&typeof n=="object"&&n.code===eh}function nw(e){return e!==null&&typeof e=="object"&&e.updating===!0}function ow(e){return e!==null&&typeof e=="object"&&e.update_stalled===!0}const rw={runtimeUnreachable:"runtime_unreachable"},Ss="runtime_busy",th="runtime_retiring";s.object({data:s.object({aside_id:s.string().optional(),status:s.union([s.enum(["adopted","queued"]),s.string()]).optional()}).passthrough()}).passthrough();const nh=s.object({name:s.string(),description:s.string().nullish(),source:s.string().nullish(),link_id:s.string().nullish(),editable:s.boolean().nullish(),installed:s.boolean().nullish(),fingerprint:s.string().nullish(),form:s.string().nullish()}).passthrough(),iw=s.object({path:s.string(),size:s.number().nullish(),preview:s.string().nullish(),preview_truncated:s.boolean().nullish()}).passthrough(),sw=nh.extend({body:s.string().nullish(),body_in_detail:s.boolean().nullish(),body_length:s.number().nullish(),body_bytes:s.number().nullish(),body_truncated:s.boolean().nullish(),files:s.array(iw).nullish(),files_total:s.number().nullish(),files_truncated:s.boolean().nullish(),publish_budget:s.object({limit:s.number(),total:s.number()}).passthrough().nullish()}).passthrough(),FM=s.object({skills:s.array(nh),scope:s.string().nullish(),detail:s.string().nullish(),skill_detail:sw.nullish(),warning_count:s.number().nullish(),version:s.string().nullish()}).passthrough(),UM=s.object({reset:s.object({outcome:s.union([s.enum(["reset","already_redeemed","no_credit","nothing_to_reset","failed","refused"]),s.string()]),windows_reset:s.number().int().nonnegative(),detail:s.string().default(""),refused:s.boolean()}).passthrough(),usage:s.object({reports:s.array(s.record(s.unknown())),source:s.string(),fetched_at:s.number()}).passthrough().nullish()}).passthrough(),BM="aside_adopt_refused",aw=["session_closed","open_tool_batch","turn_running"];function HM(e){if(typeof e!="object"||e===null)return;const t=e.reason;return aw.find(n=>n===t)}const cw={[We.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[We.refused]:"ui.common.errors.desktop_refusal.refused",[We.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[We.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed",[We.serverUpdating]:"ui.common.errors.desktop_refusal.server_updating"},ec={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 Es(e){return e!==void 0&&Object.values(We).includes(e)}function lw(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return We.refused;if(t===503)return We.planeClosed}}const WM=s.object({step:s.string(),blocked_on:s.string(),configured:s.boolean(),ready:s.boolean(),verified:s.boolean(),url:s.string().nullable(),credential_id:s.number().int().positive().nullable(),identity_label:s.string().nullable(),credential_choices:s.array(s.object({id:s.number().int().positive(),identity_label:s.string().nullable().optional()}).passthrough()).default([]),quote:s.object({monthly_price_usd:s.string().nullable(),positive_balance:s.boolean(),eligible:s.boolean(),account_valid:s.boolean()}).passthrough().nullable(),receipts:s.array(s.object({step:s.string(),ok:s.boolean(),text:s.string()})).default([]),remedy:s.object({kind:s.string(),text:s.string(),command:s.string().nullable().optional(),url:s.string().nullable().optional()}).nullable(),source:s.string(),in_progress:s.boolean().default(!1),progress:s.array(s.string()).default([]),active_credential_id:s.number().int().positive().nullable().default(null),billing_outcome:s.string().optional(),reservation_outcome:s.string().optional(),failure_stage:s.string().optional(),transport:s.string().optional()}).passthrough();function GM(e){return e.transport!=="relay"?!1:e.blocked_on==="cloudflared"||e.remedy?.kind==="install_cloudflared"}const zM=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),dw=88e4,uw=11e5,fw=2e4,pw=9e4,hw=new Set(["analytics.get","analytics.models","sessions.report"]),mw=new Set(["usage.get"]),gw=new Set(["networks.list","peers.list"]),_w=new Set(["usage.reset"]),bw=new Set(["sessions.files.download"]),vw=new Set([...hw,...mw,...gw,..._w,...bw]),yw=90,ww=30,kw=300,Sw=10,oh=15,Ew=1e4;function Iw(e){const n=e.to==="local"||e.keep?kw:ww,o=Math.max(0,e.waitS??0);return(yw+n+Sw+oh)*1e3+o*1e3}const Aw=18e4,sa=Aw+15e3,Rw=120,xw=135e3,Tw=93e4,rh=(Rw+30+oh)*1e3,Cw=6e4,Ow=5*rh,Pw=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function Mw(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 rh;case"hub.check":return Cw;case"hub.applyAll":return Ow;default:return null}}function jw(e){if(typeof e!="string"&&e.op==="sessions.transfer")return Iw(e)+Ew;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential"||typeof e!="string"&&e.op==="approvals.approveOperation"&&e.operation==="pair_phone"||t==="devices.remove"||t==="operator.setup.run")return sa;if(t==="tunnel.setup.run")return Tw;if(t==="tunnel.setup.plan")return xw;const n=Mw(t);return n!==null?n:vw.has(t)?pw:fw}const $w=5e3;function ih(e){return jw(e)+$w}const il="deadline_exceeded",sh="foreground_required",ah="View these completions in the foreground before marking them read.",Dw=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","profileProposals.list","profileProposals.get","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","mobile.doctor","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","sessions.diff","subagents.diff","teams.effective","teams.get","teams.list","tunnel.setup.plan","tunnel.setup.read","devices.list","operator.setup.read","mobile.password","usage.get"]),Nw=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Lw(e,t){const n=Math.round(t/1e3),o=il;return e==="sessions.transfer"?{code:o,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:o,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.`}:Pw.has(e)?{code:o,message:"This is taking longer than expected. It may still finish; the mark will update."}:Dw.has(e)?{code:o,message:Nw.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:o,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 KM=dw,VM=uw;s.object({state:s.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:s.string(),kind:s.enum(["balance","subscription","radient","none"]),model_free:s.boolean(),title:s.string(),body:s.string(),actions:s.array(s.object({id:s.enum(["open_url","resend_verification","refresh"]),label:s.string(),url:s.string().nullable().optional()})),resets_at_ms:s.number().int().nullable().optional(),checked_at_ms:s.number().int(),age_ms:s.number().int().nullable().optional(),source:s.enum(["cached","live"])});function Fw(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function wu(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 aa(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 ca(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 ku(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 rr(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 Uw(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"profileProposals.list":return{path:`/v1/desktop/profile-proposals?state=${e.state??"pending"}`,method:"GET"};case"profileProposals.get":return{path:`/v1/desktop/profile-proposals/${encodeURIComponent(e.proposalId)}`,method:"GET"};case"profileProposals.accept":return{path:`/v1/desktop/profile-proposals/${encodeURIComponent(e.proposalId)}/accept`,method:"POST",body:{request_id:e.requestId,...e.after?{after:e.after}:{}}};case"profileProposals.reject":return{path:`/v1/desktop/profile-proposals/${encodeURIComponent(e.proposalId)}/reject`,method:"POST",body:{request_id:e.requestId,...e.note?{note:e.note}:{}}};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.pairAck":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/pair-ack`,method:"POST",body:{request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest,...e.code!==void 0?{code:e.code}:{}}};case"devices.list":return{path:"/v1/desktop/devices",method:"GET"};case"devices.remove":return{path:`/v1/desktop/devices/${encodeURIComponent(e.deviceId)}`,method:"DELETE"};case"mobile.password":return{path:"/v1/desktop/mobile/password",method:"GET"};case"operator.setup.read":return{path:"/v1/desktop/operator/setup",method:"GET"};case"operator.setup.run":return{path:"/v1/desktop/operator/setup",method:"POST",body:{}};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:ku(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:ku(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),e.include_temporary&&t.set("include_temporary","true"),{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??hy)});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.temporary":return{path:`/v1/desktop/sessions/${e.sessionId}/temporary`,method:"POST",body:{temporary:e.temporary}};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}:{},...e.temporary?{temporary:!0}:{}}};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"),ts(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 o=e[n];o!==void 0&&t.set(n,o)}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.files.download":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files/${encodeURIComponent(e.fileId)}/download`,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"),t.set("diff_bindings","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),ts(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??gy)});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.diff":case"subagents.diff":{const t=new URLSearchParams({start:String(e.start),offset:String(e.offset??0),limit:String(e.limit)}),n=encodeURIComponent(e.callId);return{path:`/v1/desktop/sessions/${e.op==="subagents.diff"?`${e.sessionId}/children/${e.childId}`:e.sessionId}/tool-calls/${n}/diff?${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"settingsIntents.list":return{path:e.sessionId?`/v1/desktop/settings-intents?session_id=${e.sessionId}`:"/v1/desktop/settings-intents",method:"GET"};case"settingsIntents.submit":return{path:`/v1/desktop/sessions/${e.sessionId}/settings-intents`,method:"POST",body:{request_id:e.requestId,kind:e.kind,value:e.value,...e.effort!==void 0?{effort:e.effort}:{}}};case"settingsIntents.dismiss":return{path:`/v1/desktop/sessions/${e.sessionId}/settings-intents/${e.kind}?generation=${e.generation}`,method:"DELETE"};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":{ca(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??{},...aa(e)}}}case"agent.republish":{ca(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??{},...aa(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{ca(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:aa(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,...Fw(e),message:e.message,...wu(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...wu(e)}};case"wakes.remove":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"DELETE"};case"monitors.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/monitors?${t}`:"/v1/desktop/monitors",method:"GET"}}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"mobile.doctor":return{path:"/v1/desktop/mobile/doctor",method:"GET"};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"?"":rr(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${rr(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)}${rr(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)}${rr(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.typing.get":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/typing${wi(e.tenant_id)}`,method:"GET"};case"team_bridge.typing.set":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/typing`,method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,...e.thread_root_id?{thread_root_id:e.thread_root_id}:{}}};case"team_bridge.typing.clear":{const t=new URLSearchParams({tenant_id:e.tenant_id,expected_account_id:e.expected_account_id});return e.thread_root_id&&t.set("thread_root_id",e.thread_root_id),{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/typing?${t}`,method:"DELETE"}}case"agent_messages.settings.share_typing":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,share_typing:e.share_typing}};case"agent_messages.settings.screening_model":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,screening_model:e.screening_model}};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}${rr(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.for_session":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/projects`,method:"GET"};case"projects.search":return{path:`/v1/desktop/projects/search?${new URLSearchParams({q:e.q,limit:String(e.limit??Zy)})}`,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"),e.includeSessionCounts&&t.set("include_session_counts","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,...Bw(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:qy[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function Bw(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 ZM=64,YM=64*1024*1024,XM="superseded_completion_token",JM="store_busy",Hw="session_is_remote",Ww="owner_build_behind";function QM(e,t,n){if(!e||typeof e!="object")return!1;const o=e;return o.unseen===!1&&o.conversation_id===`session/${t}`&&o.completion_token===n}function Co(e,t,n){return!t||t.conversation_id!==`session/${n}`||!Array.isArray(t.revision)||t.revision.length!==2||!t.revision.every(o=>Number.isSafeInteger(o)&&o>=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 Gw(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const qM=e=>typeof e?.goal_status=="string",ej=e=>(e?.goal??"").trim().length>0;function zw(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function Kw(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 kr={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 Vw(e){return e?e===kr.notPaired?"notPaired":e===kr.serverDown?"serverDown":e===kr.frameBudget?"frameTooLarge":"lost":"lost"}const Zw=/^[a-f0-9]{12}$/,Yw=/^[a-zA-Z0-9_-]{1,128}$/,Xw=()=>performance.timeOrigin+performance.now();function Jw(e){e&&(e.rendererEntryEpochMs=Xw())}function sl(e,t){e&&(e.delivery=t,e.deliveryAt=performance.now())}function Qw(e,t,n,o){const r=a=>a===void 0?"-":a.toFixed(3),i=(a,c)=>a===void 0||c===void 0?void 0:a-c;return["[snapshot-receipt]",`openToken=${t??"-"}`,`session=${Zw.test(e.sessionId)?e.sessionId:"?"}`,`streamId=${Yw.test(e.streamId)?e.streamId:"?"}`,"kind=snapshot",`chars=${e.chars}`,`mainRecordEpochMs=${r(e.mainRecordEpochMs)}`,`mainFoldMs=${r(e.mainFoldMs)}`,`mainObserverMs=${r(e.mainObserverMs)}`,`mainEmitMs=${r(e.mainEmitMs)}`,`mainSendEpochMs=${r(e.mainSendEpochMs)}`,`ipcApproxMs=${r(i(e.preloadReceiptEpochMs,e.mainSendEpochMs))}`,`preloadReceiptEpochMs=${r(e.preloadReceiptEpochMs)}`,`preloadReadyMs=${r(e.preloadReadyMs)}`,`bridgeApproxMs=${r(i(e.rendererEntryEpochMs,e.preloadReceiptEpochMs===void 0||e.preloadReadyMs===void 0?void 0:e.preloadReceiptEpochMs+e.preloadReadyMs))}`,`rendererEntryEpochMs=${r(e.rendererEntryEpochMs)}`,`delivery=${e.delivery??"-"}`,`bufferMs=${r(i(e.deliveryAt,e.bufferedAt))}`,`deliveryToParseMs=${r(i(n,e.deliveryAt))}`,`parseMs=${r(o-n)}`].join(" ")}const Su=e=>{let t;const n=new Set,o=(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(_=>_(t,h))}},r=()=>t,c={setState:o,getState:r,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d))},l=t=e(o,r,c);return c},qw=e=>e?Su(e):Su,e0=e=>e;function t0(e,t=e0){const n=Sd.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return Sd.useDebugValue(n),n}const Eu=e=>{const t=qw(e),n=o=>t0(t,o);return Object.assign(n,t),n},ri=e=>e?Eu(e):Eu;function ch(e,t){let n;try{n=e()}catch{return}return{getItem:r=>{var i;const a=l=>l===null?null:JSON.parse(l,void 0),c=(i=n.getItem(r))!=null?i:null;return c instanceof Promise?c.then(a):a(c)},setItem:(r,i)=>n.setItem(r,JSON.stringify(i,void 0)),removeItem:r=>n.removeItem(r)}}const tc=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(o){return tc(o)(n)},catch(o){return this}}}catch(n){return{then(o){return this},catch(o){return tc(o)(n)}}}},n0=(e,t)=>(n,o,r)=>{let i={storage:ch(()=>localStorage),partialize:v=>v,version:0,merge:(v,b)=>({...b,...v}),...t},a=!1;const c=new Set,l=new Set;let d=i.storage;if(!d)return e((...v)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...v)},o,r);const u=()=>{const v=i.partialize({...o()});return d.setItem(i.name,{state:v,version:i.version})},f=r.setState;r.setState=(v,b)=>{f(v,b),u()};const h=e((...v)=>{n(...v),u()},o,r);r.getInitialState=()=>h;let _;const y=()=>{var v,b;if(!d)return;a=!1,c.forEach(A=>{var k;return A((k=o())!=null?k:h)});const p=((b=i.onRehydrateStorage)==null?void 0:b.call(i,(v=o())!=null?v:h))||void 0;return tc(d.getItem.bind(d))(i.name).then(A=>{if(A)if(typeof A.version=="number"&&A.version!==i.version){if(i.migrate){const k=i.migrate(A.state,A.version);return k instanceof Promise?k.then(M=>[!0,M]):[!0,k]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,A.state];return[!1,void 0]}).then(A=>{var k;const[M,P]=A;if(_=i.merge(P,(k=o())!=null?k:h),n(_,!0),M)return u()}).then(()=>{p?.(_,void 0),_=o(),a=!0,l.forEach(A=>A(_))}).catch(A=>{p?.(void 0,A)})};return r.persist={setOptions:v=>{i={...i,...v},v.storage&&(d=v.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>y(),hasHydrated:()=>a,onHydrate:v=>(c.add(v),()=>{c.delete(v)}),onFinishHydration:v=>(l.add(v),()=>{l.delete(v)})},i.skipHydration||y(),_||h},Is=n0,o0=(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 r0(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.message!="string"||t.message.trim()==="")return null;const n=(o,r)=>typeof o=="number"&&Number.isFinite(o)?o:r;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 lh=ri()(Is(e=>({notice:null,receive:t=>e(n=>o0(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:ch(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function Qn(e){return g(cw[e])}let nc=null;function i0(e){if(e===null){nc=null;return}nc={openFrame:e.openFrame===!0,journalOrder:e.journalOrder===!0,peerJournalSource:e.peerJournalSource===!0}}function dh(){return nc}const Iu=()=>g("ui.common.errors.desktop_backend_offline"),s0=()=>g("ui.common.errors.desktop_backend_compatibility");async function uh(e){if(window.api?.desktop)try{return await a0(window.api.desktop.request(e),e)}catch(n){throw n instanceof Ae?n:p0(n)?new _n(ah,sh):new Ae(null,Iu(),n)}let t;try{t=await fetch("/__desktop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(n){throw new Ae(null,Iu(),n)}if(!t.ok)throw new Ae(t.status,s0());return t.json()}function a0(e,t){const n=ih(t);let o;return Promise.race([e,new Promise((r,i)=>{o=setTimeout(()=>{const a=Lw(t.op,n);i(new Ae(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(o))}const fh="This server did not answer the request for its desktop controls.",c0=()=>g("ui.common.errors.desktop_refusal_placeholder");class Ae extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,o,r,i,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=o,this.code=r,this.retryAfterMs=i,this.detail=a}}class _n extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function al(e){return e instanceof Ae||e instanceof _n?e.code===We.serverUpdating?!0:e instanceof Ae&&nw(e.detail):!1}function tj(e){return e instanceof Ae&&ow(e.detail)}function ns(e,t){return al(e)?Qn(We.serverUpdating):e instanceof Ae||e instanceof _n?Es(e.code)?Qn(e.code):e.message===fh?c0():e.message:t}function l0(e,t,n,o){return o===eh&&t===503?We.serverUpdating:typeof o=="string"?o:n===qp&&t===503?We.serverUpdating:n===ec.noCredential?We.noCredential:n===ec.transportFailed?We.transportFailed:lw(Uw(e).path,t)}async function Ge(e){const t=await uh(e),n=t.body;if(t.status<200||t.status>=300){const o=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 Ae(t.status,o??fh,void 0,l0(e,t.status,o,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"&&d0(n?.result),n?.result}function d0(e){if(typeof e!="object"||e===null)return;const t=r0(e.delegated_cleanup_notice);t&&lh.getState().receive(t)}async function u0(){try{await Ge({op:"delegated_cleanup_notice.ack"})}catch{}}async function nj(){lh.getState().dismiss(),await u0()}function f0(e){return e instanceof Ae&&e.code===il}function oj(e){if(!(e instanceof Ae))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===Ww:e.code===Hw}function rj(e){return e instanceof _n&&e.code===sh}function p0(e){return e instanceof Error&&e.message.includes(ah)}async function ij(e){const t=await uh(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function sj(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await Ge({op:"auth.status",id:e});if(!n.auth_url)throw new Error("This sign-in is no longer waiting for a browser.");const o=new URL(n.auth_url);if(o.username||o.password||o.protocol!=="https:"&&!(o.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(o.hostname)))throw new Error("The provider returned an invalid sign-in address.");window.open(o.href,"_blank","noopener,noreferrer")}function h0(e,t,n){const o=y0(e);return o.record?(n?.("adopted"),Au(e.sessionId,"adopted","none",oc(e),null),S0(o.record,t)):(Kt&&pn(),n?.("requested"),Au(e.sessionId,"requested",o.refusal,oc(e),o.held),ph(e,t))}const m0=6e4,g0=512;function oc(e){return{openFrame:e.openFrame===!0,journalOrder:e.journalOrder===!0,peerJournalSource:e.peerJournalSource===!0}}let Kt=null,qn=null;function pn(){qn!==null&&(clearTimeout(qn),qn=null);const e=Kt;Kt=null,e&&(e.live=null,e.buffered=[],e.disposeTransport())}function _0(){return Kt?.sessionId??null}function b0(e){!e||Kt?.sessionId!==e||pn()}function v0(e,t){if(!e||Kt?.sessionId===e)return;pn();const n=dh(),o={openFrame:n?.openFrame===!0,journalOrder:n?.journalOrder===!0,peerJournalSource:n?.peerJournalSource===!0&&t?.remoteOwned===!0};let r=!1;const i={sessionId:e,negotiation:o,buffered:[],live:null,ended:!1,disposeTransport:()=>{}};if(i.disposeTransport=ph({sessionId:e,...o.openFrame?{openFrame:!0}:{},...o.journalOrder?{journalOrder:!0}:{},...o.peerJournalSource?{peerJournalSource:!0}:{}},c=>{if(i.live){sl(c.receipt,"live"),i.live(c);return}if(c.kind==="error"||c.kind==="end"){i.ended=!0,r=!0,pn();return}if(i.buffered.length>=g0){r=!0,pn();return}c.receipt&&(c.receipt.bufferedAt=performance.now()),i.buffered.push(c)}),r){i.disposeTransport();return}Kt=i;const a=setTimeout(()=>{Kt===i&&pn()},m0);typeof a.unref=="function"&&a.unref(),qn=a}function y0(e){const t=Kt;if(!t)return{record:null,refusal:"none",held:null};if(t.ended)return pn(),{record:null,refusal:"ended",held:t.negotiation};if(t.sessionId!==e.sessionId)return{record:null,refusal:"other-session",held:null};const n=oc(e);return e.epoch!==void 0||e.afterSeq!==void 0||(e.orderIds?.length??0)>0?(pn(),{record:null,refusal:"resuming",held:t.negotiation}):n.openFrame!==t.negotiation.openFrame||n.journalOrder!==t.negotiation.journalOrder||n.peerJournalSource!==t.negotiation.peerJournalSource?(pn(),{record:null,refusal:"negotiation",held:t.negotiation}):{record:t,refusal:null,held:t.negotiation}}const w0=/^[A-Za-z0-9_-]{1,80}$/,k0="[stream-prewarm]";function Au(e,t,n,o,r){if(t==="requested"&&n==="none")return;const i=w0.test(e)?e:"?",a=l=>[l.openFrame?"1":"0",l.journalOrder?"1":"0",l.peerJournalSource?"1":"0"].join(","),c=[k0,`session=${i}`,`decision=${t}`];t==="requested"&&(c.push(`why=${n}`,`asked=${a(o)}`),r&&c.push(`prewarm=${a(r)}`),n==="negotiation"&&c.push(`caps=${dh()?"recorded":"absent"}`)),console.warn(c.join(" "))}function S0(e,t){const n=e.buffered;e.buffered=[],e.live=t,qn!==null&&(clearTimeout(qn),qn=null),Kt===e&&(Kt=null);let o=!1;return queueMicrotask(()=>{if(!o)for(const r of n)sl(r.receipt,"replay"),t(r)}),()=>{o||(o=!0,e.live=null,e.disposeTransport())}}function ph(e,t){const n=window.api?.desktop?.stream;if(n){const i=n.subscribe(e,a=>{const c=a.receipt?{...a,receipt:{...a.receipt}}:a;Jw(c.receipt),sl(c.receipt,"direct"),t(c)});return()=>i.dispose()}const o=new URLSearchParams({session:e.sessionId});e.epoch&&o.set("epoch",e.epoch),e.afterSeq!==void 0&&o.set("after_seq",String(e.afterSeq)),o.set("frontend_replace","1"),e.openFrame===!0&&(o.set("open_frame","1"),o.set("diff_bindings","1")),e.journalOrder===!0&&(o.set("journal_order","1"),e.peerJournalSource===!0&&o.set("peer_journal_source","1"),ts(o,"/__desktop/stream",e.orderIds??[]));const r=new EventSource(`/__desktop/stream?${o}`);return r.onmessage=i=>{t({kind:"data",data:i.data})},r.onerror=()=>{r.readyState===EventSource.CLOSED&&(t({kind:"error",detail:kr.ended}),r.close())},()=>{r.close(),t({kind:"end"})}}async function aj(e,t){const n=window.api?.desktop?.media;if(n)return n(e,t);const o=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}),r=o.headers.get("content-type")??"";if(!o.ok){let i="The media request failed.",a,c;if(r.includes("application/json"))try{const l=await o.json();tw(o.status,l)&&(a=We.serverUpdating);const d=l?.detail;if(typeof d=="string")i=d;else if(typeof d=="object"&&d!==null){const u=d;typeof u.text=="string"&&u.text.trim()?i=u.text:typeof u.message=="string"&&u.message.trim()&&(i=u.message),typeof u.code=="string"&&a===void 0&&(a=u.code);const f=d.params;typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}}catch{}return{status:o.status,kind:"error",detail:i,code:a!==void 0&&Es(a)?a:i===ec.noCredential?We.noCredential:void 0,...e.op==="notification_sounds.upload"&&a!==void 0?{refusal:{code:a.slice(0,64),...c?{params:c}:{}}}:{}}}return r.includes("application/json")?{status:o.status,kind:"json",body:await o.json()}:{status:o.status,kind:"bytes",mimeType:r||"application/octet-stream",data:new Uint8Array(await o.arrayBuffer())}}function cj(e){return e.kind==="error"?Es(e.code)?new _n(Qn(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function E0(e){if(al(e))return"updating";if(f0(e))return"deadline";const t=e instanceof Ae?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const hh={updating:"",unreachable:"",deadline:"",unauthorized:"",get outdated(){return g("ui.common.connection.backend.remedy_outdated")},unknown:""},Fi={get updating(){return Qn(We.serverUpdating)},get unreachable(){return g("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return g("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return g("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return g("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function I0(e,t){const n=E0(t);return[e,Fi[n],hh[n]].filter(Boolean).join(" ")}const rc={get successor(){return g("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return g("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return g("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return g("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return g("ui.common.connection.backend.pairing_unpaired")}},A0={get successor(){return g("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return g("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return g("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return g("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return g("ui.common.connection.backend.pane_unpaired")}};function lj(e,t){return e!=="unpaired"?null:A0[t??"unpaired"]}function dj(e,t){return e!=="unpaired"?null:rc[t??"unpaired"]}function uj(e){const{kind:t,unpaired:n,answered:o,cause:r=null,servedByThisApp:i=!1}=e;return r==="pre-handshake"?i:r!==null||n?!1:o?i:t==="outdated"}function fj(e){const{kind:t,unpaired:n,missing:o,answered:r,cause:i=null}=e;if(i!==null)return rc[i];if(!r){if(t==="updating")return Fi.updating;if(t==="unreachable")return g("ui.common.connection.backend.compatibility_unreachable",{diagnosis:Fi.unreachable});if(t==="unauthorized")return g("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return g("ui.common.connection.backend.compatibility_deadline",{diagnosis:Fi.deadline});if(t==="outdated")return g("ui.common.connection.backend.compatibility_outdated",{remedy:hh.outdated})}return n?rc.unpaired:r?g("ui.common.connection.backend.compatibility_missing",{features:o.join(", ")}):g("ui.common.connection.backend.compatibility_unknown")}const R0=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function pj(e,t=null){return t!==null||!e?!0:R0.filter(o=>(e.features?.[o]??0)<1).length>0||e.desktop_available!==!0}function x0(e,t){return t instanceof Ae&&t.status===null?!1:e<1}function hj(e,t){return t instanceof Ae&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const T0={get successor(){return g("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return g("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return g("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return g("ui.common.connection.backend.card_credential_refused")},get unpaired(){return g("ui.common.connection.backend.card_unpaired")}};function mj(e,t,n){return e===null?{sentence:I0(t,n),remedy:!0}:{sentence:T0[e],remedy:Np(e)}}const mh={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]},C0=3e4,O0=15e3;function P0(e){return e?.desktop_available===!0}function gj(){const{client:e,provided:t}=Pb();return Dp({enabled:t,queryKey:mh.capabilities,queryFn:async()=>{try{const n=await Ge({op:"capabilities"});return i0(j0(n)),n}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>P0(n.state.data)?C0:O0,refetchIntervalInBackground:!0},e)}function M0(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function la(e,t,n=1){return M0(e,t,n)==="enabled"}function j0(e){return{openFrame:la(e,"open_frame"),journalOrder:la(e,"journal_order"),peerJournalSource:la(e,"peer_journal_source")}}function _j(e){return Dp({queryKey:mh.providers,queryFn:()=>Ge({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:x0})}let As=!1,os=!1;const rs=[];function bj(){typeof window>"u"||!window.__loDevDriver?.armed||(As=!0,os=!1,rs.length=0)}function $0(){return As}function D0(e){if(As)try{if(rs.length>=256){os=!0;return}rs.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{os=!0}}function vj(){return{armed:As,fault:os,receipts:rs.map(e=>({...e}))}}const ir=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function gh(e,t){const n=new Set((t.removed??[]).map(String)),o=e.filter(a=>{const c=ir(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=ir(a);if(c===null){o.push(a);continue}const l=o.findIndex(d=>ir(d)===c);l===-1?o.push(a):o[l]=a}if(!t.order)return o;const r=new Map;for(const a of o){const c=ir(a);c!==null&&r.set(c,a)}const i=[];for(const a of t.order){const c=String(a),l=r.get(c);l&&(i.push(l),r.delete(c))}for(const a of o){const c=ir(a);c!==null&&r.has(c)?(i.push(a),r.delete(c)):c===null&&i.push(a)}return i}const ic=e=>({revision:xt(e),demand:e.orderDemand}),eo=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function zo(e,t,n,o,r,i={}){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(o&&t.journal_order_state==="ready"&&r&&a.orderNeedsReconcile&&a.orderDemand===r.demand&&(a={...a,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),c!==a.journalGeneration&&!o)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},i.peer===!0)){const h=(a.orderRevision??0)+1,_=new Map;for(const y of a.records){const v=y.sourceEntryId??(y.kind==="tool"||y.kind==="supplement"?null:y.id);typeof v=="string"&&v.length>0&&v.length<=128&&_.set(v,h)}l={...l,..._.size>0?{journalBodyOwed:_}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(h,_,y)=>{if(!eo(y))return;const v=d.get(h);v&&v.seq>=y||(d===u&&(d=new Map(d)),d.set(h,{entryId:_,seq:y}))};for(const[h,_]of Object.entries(t.journal_ordinals??{}))f(h,h,_);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 cl(e,t){if(!e.journalMode||typeof t.id!="string"||!Array.isArray(t.tool_calls))return e;let n=e.journalCallOwners??new Map,o=e.journalCallSlots??new Map;const r=n,i=o;return t.tool_calls.forEach((a,c)=>{!a||typeof a.id!="string"||(n.get(a.id)!==t.id&&(n===r&&(n=new Map(n)),n.set(a.id,t.id)),o.get(a.id)!==c&&(o===i&&(o=new Map(o)),o.set(a.id,c)))}),n===r&&o===i?e:{...e,journalCallOwners:n,journalCallSlots:o}}function _h(e,t){const n=new Set(e.map(i=>i.id));let o=!1,r;for(let i=0;i<e.length;i++){const a=e[i];if(a.kind==="user"&&a.provisional===!0){r=a;continue}if(a.sourcePrecedes!==void 0){if(a.sourceAdmissionAnchor!==void 0){const{sourceAdmissionAnchor:c,...l}=a;e[i]=l,o=!0}r=e[i];continue}!t(a)&&r&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[i]={...a,sourceAdmissionAnchor:r.id},o=!0),r=e[i]}return o}function bh(e,t,n,o,r){const i=[],a=new Set;let c=e,l;for(;c!==void 0;){if(r.has(c.id)){l=r.get(c.id);break}if(n(c)){l=o(c);break}if(c.kind==="user"&&c.provisional===!0||a.has(c.id))break;a.add(c.id),i.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of i)r.set(d,l);return l}const N0=Number.MAX_SAFE_INTEGER;function L0(e,t){const n=new Map,o=new Map,r=new Map;for(const i of e){if(i.sourcePrecedes===void 0)continue;const a=t(i);if(a!==void 0)o.set(i.sourcePrecedes,a);else{const c=o.get(i.sourcePrecedes);c!==void 0&&n.set(i.id,{seq:c,slot:N0})}}for(let i=e.length-1;i>=0;i--){const a=e[i];if(a.sourcePrecedes===void 0)continue;const c=t(a);if(c!==void 0)r.set(a.sourcePrecedes,c);else if(!n.has(a.id)){const l=r.get(a.sourcePrecedes);l!==void 0&&n.set(a.id,{seq:l,slot:-1})}}return n}function vh(e,t){return{floor:F0(e,t),position:new Map(e.map((n,o)=>[n.id,o])),page:L0(e,t)}}function yh(e,t,n,o){if(o===void 0||e.sourcePrecedes===void 0)return;const r=o.page.get(e.id);if(r!==void 0)return r;const i=new Set;let a=1,c=t.get(e.sourcePrecedes);for(;c!==void 0&&!i.has(c.id);){i.add(c.id);const l=n(c);if(l!==void 0)return{seq:l,slot:-a};const d=o.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 o.floor===void 0?void 0:{seq:o.floor,slot:-a}}function wh(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:o}=n,r=new Set;let i=1,a=t.get(e.sourcePrecedes);for(;a!==void 0&&!r.has(a.id);){if(a.sourcePrecedes===void 0){const c=o.get(a.id);return c===void 0?void 0:{slot:c,depth:i}}r.add(a.id),i+=1,a=t.get(a.sourcePrecedes)}}function F0(e,t){let n;for(const o of e){if(o.sourcePrecedes!==void 0)continue;const r=t(o);r!==void 0&&(n===void 0||r<n)&&(n=r)}return n}function kh(e,t){const n=new Map;return o=>{if(!o)return;const r=t(o);if(r===void 0)return;const i=[],a=new Set;let c=o,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),i.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of i)n.set(d,l);return l?r:void 0}}function is(e,t){const n=e.journalCallOwners,o=e.journalCallSlots;if(!n||!o)return t;const r=new Map;t.forEach((a,c)=>{if(a.kind!=="tool")return;const l=n.get(a.toolCallId);if(l===void 0||!o.has(a.toolCallId))return;const d=r.get(l);d?d.push(c):r.set(l,[c])});let i=t;for(const a of r.values()){if(a.length<2)continue;const c=a.map(l=>t[l]).sort((l,d)=>(o.get(l.toolCallId)??0)-(o.get(d.toolCallId)??0));c.every((l,d)=>l===t[a[d]])||(i===t&&(i=t.slice()),a.forEach((l,d)=>{i[l]=c[d]}))}return i}function Sh(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return U0(e,t);const n=e.journalGeneration,o=e.journalPositions;let r=!1,i=!1;const a=t.map(v=>{v.sourcePrecedes!==void 0&&(i=!0);let p=[o?.get(v.sourceEntryId??v.id),o?.get(v.id)].filter(M=>M!==void 0).sort((M,P)=>P.seq-M.seq)[0];if(v.journalGeneration===n&&eo(v.journalSeq)&&(!p||v.journalSeq>p.seq)&&(p={entryId:v.sourceEntryId??v.id,seq:v.journalSeq}),!p||!n||!(v.kind==="user"&&(v.provisional===!0||v.local===!0))&&v.sourceEntryId===p.entryId&&v.journalSeq===p.seq&&v.journalGeneration===n)return v;r=!0;let k={...v,sourceEntryId:p.entryId,journalSeq:p.seq,journalGeneration:n};if(k.kind==="user"){const{provisional:M,local:P,...W}=k;k=W}return k});_h(a,v=>v.journalGeneration===n&&eo(v.journalSeq))&&(r=!0);const l=new Map,d=new Map(a.map(v=>[v.id,v])),u=kh(d,v=>v!==void 0&&v.journalGeneration===n&&eo(v.journalSeq)?v.journalSeq:void 0),f=v=>u(v)!==void 0,h=i?vh(a,u):void 0,_=(v,b)=>{const p=u(v);if(v.kind==="user"&&v.provisional===!0&&p===void 0)return[1,0,0,0,b];const A=v.kind==="supplement"?v.anchor:v.kind==="tool"?e.journalCallOwners?.get(v.toolCallId)??e.argsByCall.get(v.toolCallId)?.anchorId:void 0,k=typeof A=="string"?u(d.get(A)):void 0,M=k===void 0&&p===void 0?yh(v,d,u,h):void 0,P=p===void 0&&M===void 0?bh(v,d,f,u,l):void 0,W=k??p??M?.seq??P;if(W===void 0){const R=wh(v,d,h);return[1,R?.slot??b,R?-R.depth:0,0,b]}return[0,W,k!==void 0?1:p!==void 0?0:M!==void 0?M.slot:2,p??Number.MAX_SAFE_INTEGER,b]},y=a.map((v,b)=>({record:v,index:b,rank:_(v,b)}));return y.sort((v,b)=>{for(let p=0;p<v.rank.length;p++){const A=v.rank[p]-b.rank[p];if(A)return A}return 0}),!r&&y.every((v,b)=>v.index===b)?is(e,t):is(e,y.map(v=>v.record))}function U0(e,t){const n=e.journalGeneration,o=e.journalPositions,r=new Map;let i=!1;for(const p of t){p.sourcePrecedes!==void 0&&(i=!0);let k=[o?.get(p.sourceEntryId??p.id),o?.get(p.id)].filter(M=>M!==void 0).sort((M,P)=>P.seq-M.seq)[0];p.journalGeneration===n&&eo(p.journalSeq)&&(!k||p.journalSeq>k.seq)&&(k={entryId:p.sourceEntryId??p.id,seq:p.journalSeq}),k&&r.set(p.id,k)}const a=p=>p===void 0?void 0:r.get(p.id)??o?.get(p.sourceEntryId??p.id)??o?.get(p.id);let c=!1;const l=t.slice();_h(l,p=>p.journalGeneration===n&&eo(p.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(p=>[p.id,p])),h=kh(f,p=>a(p)?.seq),_=p=>h(p)!==void 0,y=i?vh(l,h):void 0,v=(p,A)=>{const k=h(p);if(p.kind==="user"&&p.provisional===!0&&k===void 0)return[1,0,0,0,A];const M=p.kind==="supplement"?p.anchor:p.kind==="tool"?e.journalCallOwners?.get(p.toolCallId)??e.argsByCall.get(p.toolCallId)?.anchorId:void 0,P=typeof M=="string"?h(f.get(M)):void 0,W=P===void 0&&k===void 0?yh(p,f,h,y):void 0,R=k===void 0&&W===void 0?bh(p,f,_,h,u):void 0,m=P??k??W?.seq??R;if(m===void 0){const w=wh(p,f,y);return[1,w?.slot??A,w?-w.depth:0,0,A]}return[0,m,P!==void 0?1:k!==void 0?0:W!==void 0?W.slot:2,k??Number.MAX_SAFE_INTEGER,A]},b=l.map((p,A)=>({record:p,index:A,rank:v(p,A)}));return b.sort((p,A)=>{for(let k=0;k<p.rank.length;k++){const M=p.rank[k]-A.rank[k];if(M)return M}return 0}),!c&&b.every((p,A)=>p.index===A)?is(e,t):is(e,b.map(p=>p.record))}function Jt(e){const t=e.records.filter(r=>r.kind==="user"&&r.provisional===!0),n=e.records.filter(r=>r.journalGeneration!==e.journalGeneration||!eo(r.journalSeq)),o=[...t,...n].map(r=>r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id));if(o.push(...ll(e)),e.journalPositions?.has(e.oldestId??"")||o.push(e.oldestId),e.journalSourceVoid?.size)for(let r=o.length-1;r>=0;r--){const i=o[r];typeof i=="string"&&e.journalSourceVoid.has(i)&&o.splice(r,1)}return[...new Set(o.filter(r=>typeof r=="string"&&r.length>0&&r.length<=128))]}function ll(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const o of e.records){const r=o.sourceEntryId??(o.kind==="tool"||o.kind==="supplement"?null:o.id);typeof r=="string"&&r.length>0&&r.length<=128&&t.add(r)}const n=[];for(const o of e.journalBodyOwed.keys())o.length<1||o.length>128||t.has(o)&&(e.journalSourceVoid?.has(o)||n.push(o));return n}function Eh(e,t){const n=e.journalPositions;return Jt(e).filter(o=>!n?.has(o)&&!t?.has(o))}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},o=(c,l)=>l==="payload"?ll(c):l==="lookup"?Eh(c):Jt(c);let r=e.getTranscript().journalGeneration,i=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=ic(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",h=ey(o(c,f).filter(b=>!n(f).has(b)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),_=await e.read(h,f);if(!e.isCurrent()||xt(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(_,d,l),!e.isCurrent())return{kind:"stale"};const y=e.getTranscript(),v=e.page(_);if(v.journal_order_state==="ready"&&v.journal_generation===y.journalGeneration){v.journal_generation!==r&&(t.clear(),r=v.journal_generation);for(const A of h)n(f).add(A);if(y.orderNeedsReconcile){if(y.orderDemand===l.demand||i===1)return{kind:"waiting"};i++,t.clear();continue}if(f==="payload"){const A=(v.source_retry_ids??[]).filter(k=>typeof k=="string"&&k.length>0&&k.length<=128);if(A.length>0&&h.length>1&&a===0){a++;for(const k of A)n("payload").delete(k);continue}}const b=e.sweep?.(y,n);if(b?.kind==="none")return{kind:"complete",transcript:y};const p=b?.kind??"authority";if(o(y,p).some(A=>!n(p).has(A)))continue;return{kind:"complete",transcript:y}}if(!y.orderNeedsReconcile||y.orderDemand===l.demand||i===1)return{kind:"waiting"};i++,t.clear()}}function Ft(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const r=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof r=="string"&&r?r:e.id}function da(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function Ru(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function yj(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 i of t){if(!i.settled||typeof i.run_key!="string"||i.run_key.length===0)continue;const a=da(i.action_count);if(a===null)continue;const c={actions:a,workedSeconds:Ru(i.worked_seconds),failed:da(i.failed_count)??0,complete:i.complete!==!1,openingUserId:typeof i.opening_user_id=="string"&&i.opening_user_id.length>0?i.opening_user_id:null,closingAnswerId:typeof i.closing_answer_id=="string"&&i.closing_answer_id.length>0?i.closing_answer_id:null,crossSessionActions:da(i.cross_session_action_count),crossSessionWorkedSeconds:Ru(i.cross_session_worked_seconds)};n.set(i.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 o=new Set;for(const i of e.entries)o.add(Ft(i));const r=e.entries[e.entries.length-1];return{runs:n,page:{ids:o,newestKey:r?Ft(r):null}}}function H0(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(i=>i.opening_user_id===n.id))return null;const r=Math.round((n.ts??0)*1e3);return r>0?{id:n.id,tsMs:r}:null}function W0(e,t,n){const o=H0(e),r=e?.entries;if(o===null||!r||r.length===0)return!1;const i=Math.round((r[r.length-1].ts??0)*1e3);if(!(i>o.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>o.tsMs)||!(c<i)))return!1;return!0}const G0=new Set(["completed","done","failed","cancelled","interrupted"]);function z0(e,t){const n=new Set;for(const r of t)r.kind==="custom"&&r.jobId&&n.add(r.jobId);const o=[];for(const r of e){const i=r.id==null?"":String(r.id);!i||n.has(i)||G0.has(String(r.status??""))&&o.push(i)}return o}function K0(e,t,n,o){let r=t,i=!1;for(const a of e){const c=a.changes??{};Array.isArray(c.jobs)?r=c.jobs:a.job_deltas&&(r=gh(r,a.job_deltas));const l=c.history_cursor;typeof l=="string"&&l!==""&&!o(l)&&(i=!0)}return i?z0(r,n):[]}const dl=new Set,Dn="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",ul=new RegExp(`[${Dn}]`),V0=new RegExp(`[${Dn}]+`),wj=new RegExp(`[${Dn}]+`,"g"),Z0=new RegExp(`^[${Dn}]+|[${Dn}]+$`,"g"),Y0=new RegExp(`^[${Dn}]+`),kj=new RegExp(`[^${Dn}]`);function nn(e){return e.replace(Z0,"")}function Wr(e){return e.replace(Y0,"")}function Ih(e,t){return t===0||ul.test(e[t-1])}function Ah(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&Ih(e,n)&&t.push(n);return t}function fl(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const o=e.lastIndexOf(`
|
|
2
|
+
`,n-1)+1,r=e.indexOf(`
|
|
3
|
+
`,n),i=r===-1?e.length:r;let a=e.slice(o,i);return a.endsWith("\r")&&(a=a.slice(0,-1)),{line:a,lineStart:o,column:n-o}}function X0(e,t){if(t.size===0)return null;for(const n of Ah(e)){const o=e.slice(n+1),r=o.indexOf(" ");if(r!==-1&&t.has(o.slice(0,r).toLowerCase()))return n}return null}function pl(e,t,n){const o=X0(e,n);let r=null;for(const i of Ah(e)){if(i===o)return t>i?i:r;i<=t&&(r=i)}return r}function J0(e,t=null,n=dl){const{line:o,lineStart:r,column:i}=fl(e,t),a=pl(o,i,n);if(a===null)return null;let c=a+1;for(;c<o.length&&!ul.test(o[c]);)c++;return i>c?null:{start:r+a,query:o.slice(a+1,c),end:r+c}}function Sj(e,t=null,n=dl){const{line:o,lineStart:r,column:i}=fl(e,t),a=pl(o,i,n);return a===null?null:{start:r+a,end:r+o.length}}function Q0(e,t,n=null,o=dl){const{line:r,lineStart:i,column:a}=fl(e,n),c=o.size>0?o:new Set(t.map(_=>_.toLowerCase())),l=pl(r,a,c);if(l===null)return null;const d=r.slice(l+1),u=d.indexOf(" ");if(u===-1)return null;const f=d.slice(0,u);if(!t.some(_=>_.toLowerCase()===f.toLowerCase()))return null;const h=l+1+f.length;return a<=h?null:{value:d.slice(u+1),start:i+h+1,end:i+r.length,tokenStart:i+l}}function xu(e,t){return nn(e.slice(0,t))===""}function Ej(e,t,n,o){const r=Q0(e,o,t,n);if(r!==null&&xu(e,r.tokenStart))return"argument";const i=J0(e,t,n);return i!==null&&xu(e,i.start)?"command":null}function Ij(e,t,n,o){let r=t,i=n;const a=c=>c>=0&&c<e.length&&`
|
|
4
|
+
`.includes(e[c]);return o===""?r>0&&a(r-1)?r-=1:a(i)&&(i+=1):r===0&&a(i)&&(i+=1),{text:`${e.slice(0,r)}${o}${e.slice(i)}`,caret:r+o.length}}const q0=1e3,ek=900,tk=40,Rh=3;function nk(e,t){let n=0,o=-2,r=0;for(const i of e){const a=t.indexOf(i,r);if(a<0)return 0;n+=a===o+1?2:1,o=a,r=a+1}return n<=0?0:Math.max(1,Math.min(tk,n))}function xh(e,t){const n=e.toLowerCase(),o=t.toLowerCase();return n?n===o?q0:o.startsWith(n)?ek:nk(n,o):0}function ok(e){const n=nn(e).split(V0).pop()??"";return n.startsWith("/")?n.slice(1):n}function rk(e,t){const n=ok(e),o=[];return t.forEach((r,i)=>{let a=0,c=r.name;for(const l of[r.name,...r.aliases]){const d=xh(n,l);d>a&&(a=d,c=l)}a>0&&o.push({score:a,index:i,name:c,command:r})}),o.sort((r,i)=>i.score-r.score||r.index-i.index),o.map(r=>({name:r.name,command:r.command}))}function Aj(e,t){if(!e)return t.map(i=>({name:i.name,command:i}));const n=rk(`/${e}`,t);if(e.length>=Rh)return n;const o=e.toLowerCase(),r=n.filter(({name:i})=>i.toLowerCase().startsWith(o));return r.length>0?r:n}function Tu(e,t){if(!e)return t.map(o=>({name:o.name,choice:o}));const n=[];return t.forEach((o,r)=>{const i=Math.max(0,...[o.name,...o.aliases??[]].map(a=>xh(e,a)));i>0&&n.push({score:i,order:r,choice:o})}),n.sort((o,r)=>r.score-o.score||o.order-r.order),n.map(o=>({name:o.choice.name,choice:o.choice}))}const Cu=/^-+/;function Rj(e,t,n,o,r){if(r)return!0;const i=nn(e).toLowerCase(),a=nn(t).toLowerCase();return i===a||i.length>0&&i.replace(Cu,"")===a.replace(Cu,"")?!0:!o&&n<=1}const ik=new RegExp("\\p{Ll}","u");function Th(e){for(const t of e)if(ik.test(t))return!0;return!1}function xj(e,t,n){if(n){if(!e)return t.map(a=>({name:a.name,choice:a}));const o=Tu(e,t);if(e.length>=Rh)return o;const r=e.toLowerCase(),i=o.filter(a=>a.name.toLowerCase().startsWith(r));return i.length>0?i:o}return Th(e)?Tu(e,t).filter(o=>o.name.startsWith(e)):[]}const sk=/<skill name="([^"]*)" invocation="([^"]*)">/,ak=/[A-Za-z0-9]/,ck=/[A-Za-z0-9._-]/,lk=/[._-]/;function dk(e,t){if(t>=e.length||!ak.test(e[t]))return t;let n=t+1;for(;n<e.length&&ck.test(e[n]);)n++;return n}function uk(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!Ih(e,n)){n+=1;continue}const o=dk(e,n+1);o>n+1&&t.push({start:n,end:o,name:e.slice(n+1,o)}),n+=Math.max(o-n,1)}return t}function fk(e,t,n,o,r,i){let a=n;for(;;){const c=e.slice(t+1,a);if(o.has(c))return{end:a,name:c};if(i||Th(c)){const l=r.get(c.toLowerCase());if(l!==void 0)return{end:a,name:l}}if(a>t+2&&lk.test(e[a-1])){a-=1;continue}return null}}function pk(e,t,n={}){return Ch(e,t,n.skipSpans??[],!0)}function Tj(e,t,n={}){return Ch(e,t,n.skipSpans??[],!1)}function Ch(e,t,n,o){const r=new Set(t),i=new Map;for(const l of t)i.has(l.toLowerCase())||i.set(l.toLowerCase(),l);const a=[],c=new Set;for(const l of uk(e)){if(n.some(([f,h])=>f<=l.start&&l.start<h))continue;const d=Wr(e.slice(0,l.start))==="",u=fk(e,l.start,l.end,r,i,d);u===null||o&&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 Oo="<operator-skills>",ss="</operator-skills>",gr=`
|
|
5
|
+
|
|
6
|
+
`,Oh="The user invoked the following skills directly. Follow them for this request. Their reference files, if any, are listed at the end of each body and are read with `skill://<name>/<path>`.",hl="",hk=Oo.replace("<",`<${hl}`),mk=ss.replace("<",`<${hl}`),gk=`<${hl}skill name=`,_k=/^<skill name="([^"]*)">/;function bk(e){return e.replace(/<\/operator-skills>/g,mk).replace(/<operator-skills>/g,hk).replace(/<skill name="/g,gk)}function Cj(e){const t=e.map(({name:n,body:o})=>`<skill name="${n}">
|
|
7
|
+
${bk(o)}
|
|
8
|
+
</skill>`);return Oo+gr+Oh+gr+t.join(gr)+gr+ss}function ml(e){const t=[],n=Oo+gr+Oh;let o=0;for(;;){const r=e.indexOf(n,o);if(r===-1)return t;const i=e.indexOf(ss,r+n.length),a=e.indexOf(Oo,r+Oo.length);if(i===-1||a!==-1&&a<i){o=r+Oo.length;continue}const c=i+ss.length;t.push([r,c]),o=c}}function vk(e){const t=[];for(const[n,o]of ml(e)){let r=0;for(const i of e.slice(n,o).split(`
|
|
9
|
+
`)){if(r>0){i.startsWith("</skill>")&&(r-=1);continue}const a=_k.exec(i);a!==null&&(t.push(a[1]),r=1)}}return t}function Oj(e,t){const n=ml(e),o=pk(e,t,{skipSpans:n});if(o.length===0)return[];const r=new Set(vk(e));return o.filter(i=>!r.has(i.name))}const Ou=new RegExp(`[${Dn}]+$`);function Ph(e){const t=ml(e);if(t.length===0)return e;const n=[];let o=0;for(const[i,a]of[...t].sort((c,l)=>c[0]-l[0])){if(a<=o)continue;const c=Math.max(i,o);n.push(e.slice(o,c).replace(Ou,"")),o=a}n.push(e.slice(o).replace(Ou,""));let r="";for(const i of n)i&&(r&&!ul.test(i[0])&&(r+=" "),r+=i);return r}function Pj(e){if(!e||nn(e)==="")return!1;let t=Wr(e);if(t.startsWith("---")){const n=t.slice(3),o=n.indexOf(`
|
|
10
|
+
---`);o!==-1&&(t=n.slice(o+4))}return nn(t)!==""}function yk(e){return e.replace(/ /g,`
|
|
11
|
+
`).replace(/>/g,">").replace(/</g,"<").replace(/"/g,'"').replace(/&/g,"&")}const nt=[];for(let e=0;e<256;++e)nt.push((e+256).toString(16).slice(1));function wk(e,t=0){return(nt[e[t+0]]+nt[e[t+1]]+nt[e[t+2]]+nt[e[t+3]]+"-"+nt[e[t+4]]+nt[e[t+5]]+"-"+nt[e[t+6]]+nt[e[t+7]]+"-"+nt[e[t+8]]+nt[e[t+9]]+"-"+nt[e[t+10]]+nt[e[t+11]]+nt[e[t+12]]+nt[e[t+13]]+nt[e[t+14]]+nt[e[t+15]]).toLowerCase()}let ua;const kk=new Uint8Array(16);function Sk(){if(!ua){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ua=crypto.getRandomValues.bind(crypto)}return ua(kk)}const Ek=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Pu={randomUUID:Ek};function Ik(e,t,n){if(Pu.randomUUID&&!e)return Pu.randomUUID();e=e||{};const o=e.random??e.rng?.()??Sk();if(o.length<16)throw new Error("Random bytes length must be >= 16");return o[6]=o[6]&15|64,o[8]=o[8]&63|128,wk(o)}const Mh=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,sc=e=>{let t=e;for(;;){const n=Mh.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},Mu=e=>{const t=[];let n=e;for(;;){const o=Mh.exec(n);if(o===null)break;t.push({id:Ik(),text:o[1]}),n=n.slice(o[0].length)}return{replies:t,remainingContent:n.trim()}};function Rs(e){return gl(e)?.skill}const Ak=/^\s/,Rk=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,xk=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function Tk(e){const t=Wr(e);if(!t.startsWith("---"))return null;const o=t.slice(3).indexOf(`
|
|
12
|
+
---`);return o===-1?null:e.length-t.length+3+o+4}function Ck(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function ju(e,t){const n=[];for(let o=1;o<e.length;o+=1){const r=e[o];if(t==='"'&&r==="\\"&&o+1<e.length){n.push(r,e[o+1]),o+=1;continue}if(r!==t){n.push(r);continue}if(t==="'"&&e[o+1]==="'"){n.push(r,r),o+=1;continue}const i=e.slice(o+1).trim();if(i!==""&&!i.startsWith("#"))return null;const a=n.join(""),c=t==="'"?a.replace(/''/g,"'"):Ck(a);return c===""?null:c}return null}function Ok(e){const t=e.split(`
|
|
13
|
+
`);for(const[n,o]of t.entries()){if(!o.startsWith("description:"))continue;const r=o.slice(12).trim(),i=r!==""&&Rk.test(r),a=[];r!==""&&!i&&a.push(r);for(let u=n+1;u<t.length;u+=1){const f=t[u];if(f.trim()!==""){if(!Ak.test(f))break;a.push(f.trim())}}if(a.length===0)return null;const c=a.join(" ");if(i)return c.trim()===""?null:c.trim();if(c.startsWith('"'))return ju(c,'"');if(c.startsWith("'"))return ju(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function gl(e){const{prefix:t,rest:n}=sc(e),o=n.slice(0,n.length-Wr(n).length),r=Wr(n),i=xk.exec(r);if(i===null)return null;const a=sk.exec(r.slice(i[0].length));if(a===null||a.index!==0||a[1]!==i[1])return null;const c=i[0].length+a[0].length,l=r.indexOf("</skill>",c);if(l===-1)return null;const d=r.slice(c,l),u=Tk(d),f=u===null?null:Ok(d.slice(0,u)),h=a[1],_=yk(a[2]);return{text:t+o+_,skill:{name:h,token:`$${h}`,request:nn(r.slice(l+8)),purpose:f,body:nn(u===null?d:d.slice(u))}}}function Mj(e){const t=gl(e);if(t!==null)return t.text;const n=Ph(e);return n===e?e:nn(n)}function Pk(e){const t=gl(e);if(t===null){const o=Ph(e);if(o===e)return null;const{prefix:r}=sc(e);return{replies:Mu(e).replies,text:o.slice(r.length).trimStart()}}const{prefix:n}=sc(e);return{replies:Mu(e).replies,text:t.text.slice(n.length).trimStart()}}function jj(e){return Pk(e)?.text??e}const Mk=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"]]),jk=/\blabel=(['"])(.*?)\1/,$k=/\bjob=(['"])(.*?)\1/,Dk=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function ac(e){const t=typeof e.text=="string"?e.text:"",n=Dk.exec(t);let o=n?.[2];const r=o?.indexOf(`
|
|
14
|
+
|
|
15
|
+
`)??-1,a=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&r>=0?Mk.get((o??"").slice(0,r)):void 0;n?.[1]==="parent-message"&&a&&(o=(o??"").slice(r+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:o?.trim()?o:t,envelope:t,direction:c,label:Ko(e.label??(n&&jk.exec(n[0].split(`
|
|
16
|
+
`,1)[0])?.[2])),jobId:Ko(e.job_id??(n&&$k.exec(n[0].split(`
|
|
17
|
+
`,1)[0])?.[2])),sender:Fh(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 $j(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 Nk(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 Dj(e){return Nk(e)!==null}const jh=/\s+/,Lk=/[\\/]+$/,Fk=/[\\/]/,$h=`
|
|
18
|
+
|
|
19
|
+
`,Uk=" — cancel with wake(",Bk=120,Dh=/(?:\u001b[\]PX^_]|[\u009d\u0090\u0098\u009e\u009f])(?:(?!\u0007|\u001b\\|\u009c)[\s\S])*(?:\u0007|\u001b\\|\u009c|$)|(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]|(?:\u001b\[|\u009b)[0-?]*[ -/]*$|\u001b[ -/]+[0-~]|\u001b[@-Z\\-_]|\u001b$|[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g,Hk=new RegExp("\\p{Cf}","gu"),Wk=4096;function Ko(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(Dh,"").replace(Hk,"").split(jh).filter(Boolean).join(" ").slice(0,Bk)}const Nj={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function Nh(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(Lk,"");if(t){const n=t.split(Fk).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function Lh(e){const{name:t,quoted:n}=Nh(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function Gk(e){const{name:t,quoted:n}=Nh(e),o=[];return e.pid&&o.push(`pid ${e.pid}`),e.modelLabel&&o.push(e.modelLabel),t?[n?`"${t}"`:t,...o].join(" · "):o.length>0?o.join(" · "):"another session"}function Lj(e,t){return t.trim()?!0:Gk(e)!==Lh(e)}function zk(e){for(const t of e.slice(0,Wk).split(`
|
|
20
|
+
`)){const n=Ko(t);if(n)return n}return""}function Fj(e,t){const n=Lh(e),o=zk(t);return o?`${n} · ${o}`:n}function fa(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const Kk=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,Vk=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,Zk=/^<peer-session-message[^>]*>/,Yk=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function Fh(e){const t=String(e.text??e.detail??""),n=Kk.exec(t.trim()),o={};if(n)for(const d of n[1].matchAll(Yk))o[d[1]]=d[2]??d[3]??d[4]??"";const r=n?n[2]:"",a=(String(e.body??"").trim()||r||(n?"":t.trim().replace(Zk,""))).replace(Vk,"").trim(),c=e.sender??{},l=(d,u)=>Ko(d)||Ko(u);return{body:a,sender:{pid:l(c.pid,o.from_pid),conversationName:l(c.conversation_name,o.conversation),cwd:l(c.cwd,void 0),sessionId:l(c.session_id,void 0),modelLabel:l(c.model_label,o.model)}}}function Xk(e){return!!e.wake_catchup}function Jk(e){return e.hidden===!0}function Uj(e){let t=e.split($h)[0]??"";t=t.split(jh).filter(Boolean).join(" "),t=t.split(Uk)[0];const n="(alarm) ";for(;t.startsWith(n);)t=t.slice(n.length);const o="Scheduled wake ";return t.startsWith(o)&&(t=t.slice(o.length)),t.trim()}function Bj(e){const t=e.indexOf($h);return t===-1?"":e.slice(t+2).trim()}const ki=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},sr=e=>typeof e=="string"?Ko(e):"";function Qk(e){const t=ki(e.bridge_receipt),n=t.v===1,o=ki(n?t.sender:e.sender),r=n?ki(t.conversation):{},i=n?t.attachment_count:void 0;return{sender:{name:sr(o.name),...o.kind==="human"||o.kind==="agent"?{kind:o.kind}:{},...sr(o.organization)?{organization:sr(o.organization)}:{}},conversation:{...r.kind==="dm"||r.kind==="group"||r.kind==="channel"?{kind:r.kind}:{},...sr(r.label)?{label:sr(r.label)}:{}},...typeof i=="number"&&Number.isSafeInteger(i)&&i>=0?{attachmentCount:i}:{}}}const qk=new Set(["channel_post","channel_create","channel_history","channel_thread","react","shared_history"]),eS=new Set(["channel_post","dm","send","reply"]),tS=new Set(["take_up","ack","send","reply","channels","channel_create","channel_post","channel_history","react","channel_thread","directory","dm","shared_conversations","shared_history"]),nS=/^(?:bcv|bcmsg|acc|ep)_/i,oS=/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]|\x9b[0-?]*[ -/]*[@-~]/g,rS=/[\x00-\x08\x0e-\x1f\x7f-\x9f]/g,Uh=new RegExp("(?![\\u200c\\u200d])\\p{Cf}","gu");function Hj(e){return e.replace(Uh,"")}const iS=/[\t\n\r\v\f ]+/,sS=/\r\n|\r|\n/,aS=/^bcv_\S+$/,cS=200;function Gr(e){return typeof e!="string"?null:e.replace(oS,"").replace(rS,"").replace(Uh,"").split(iS).filter(Boolean).join(" ").slice(0,cS)||null}function Zn(e){const t=Gr(e);return t&&!nS.test(t)?t:null}const lS=/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d{1,9}[.)]\s+)+/u,dS=/!?\[([^\]]*)\]\([^)]*\)/gu,uS=/\*\*|__|~~|`+/gu,fS=/(?<![\p{L}\p{N}_*])[*_](?=[^\s*_])|(?<=[^\s*_])[*_](?![\p{L}\p{N}_*])/gu,pS=/^[-=*_~`#> ]*$/;function hS(e){return e.replace(lS,"").replace(dS,"$1").replace(uS,"").replace(fS,"")}function pa(e){if(typeof e!="string")return null;for(const t of e.split(sS)){const n=Gr(hS(t));if(n&&!pS.test(n))return n}return null}const bn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function Bh(e){if(typeof e!="string")return null;try{return JSON.parse(e)}catch{}const t=e.indexOf(`
|
|
21
|
+
|
|
22
|
+
`);if(t<0)return null;try{return JSON.parse(e.slice(t+2))}catch{return null}}function mS(e,t,n){if(e==="react")return t.remove===!0?"react-remove":"react";if(e==="ack"){const o=t.state||n?.state;if(o==="working")return"ack-working";if(o==="done")return"ack-done"}return e}function Hh(e){return qk.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function Wh(e,t,n){const o=Zn(n?.conversation_label);if(o)return o;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=bn(Bh(n?.content)),c=Zn(a?.name);if(c)return c}if(e==="channel_create"){const a=Zn(t.name);if(a)return a}const r=Hh(e);if(r!=="person"&&r!=="dm")return null;const i=bn(t.to);return Zn(i?.name)}function gS(e,t,n){const o=Hh(e);return o==="none"||o==="message"||o==="directory"?{kind:o,label:null}:{kind:o,label:Wh(e,t,n)}}function _S(e){if(Array.isArray(e))return e.length;const t=bn(e);if(!t)return null;for(const n of["conversations","items","data"])if(Array.isArray(t[n]))return t[n].length;return null}function bS(e,t){if(!t)return null;const n=Bh(t.content),o=bn(n);if(e==="channel_history"||e==="shared_history")return Array.isArray(o?.messages)?o.messages.length:null;if(e==="channel_thread"){if(!o)return null;const r=bn(o.root)?1:0,i=Array.isArray(o.replies)?o.replies.length:null;return i===null&&r===0?null:r+(i??0)}return e==="directory"?typeof o?.count=="number"&&Number.isInteger(o.count)?o.count:Array.isArray(t.members)?t.members.length:null:e==="channels"||e==="shared_conversations"?_S(n):null}function vS(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=Gr(t.code);if(t.ok===!0){if(t.destination_type==="peer_inbox")return{outcome:"inbox_only",code:null};const o=t.recipient_state;return e==="dm"&&typeof o=="string"&&o!==""&&o!=="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 xs(e,t){const n=e??{},o=Gr(n.op)??"",r=bn(t),i=tS.has(o),a=eS.has(o)||o==="take_up"?pa(n.body)??pa(n.text)??pa(r?.text):null;return{op:o,action:mS(o,n,r),target:i?gS(o,n,r):{kind:"none",label:null},preview:a,count:i&&r?.ok===!0?bS(o,r):null,emoji:o==="react"?Gr(n.emoji):null,...i?vS(o,r):{outcome:null,code:null}}}function Gh(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&aS.test(n.trim()))return n.trim();return null}const yS=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"]),zh=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return yS.has(t)?t:"unknown"},wS={channel_post:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function cc(e){return wS[zh(e)]()}function Kh(e,t=null){const{kind:n}=e.target,o=e.target.label??Zn(t);return o?n==="channel"&&!o.startsWith("#")?`#${o}`:o:e.op==="shared_history"?"":n==="channel"?g("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?g("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?g("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?g("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function lc(e,t,n,o){const r=Gh(t,o),i=!e.target.label&&r&&n?n(r):null,a=Kh(e,i),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?a:g("ui.chat.canonical.tool_row.bridge.summary.messages",{target:a,count:e.count}).trim();switch(zh(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?g("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?"":g("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":g("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 kS(e){return e.outcome==="refused"?e.code?g("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):g("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?g("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):g("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const SS=["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 Vh(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const o=bn(t);if(!o)return n??null;const{_images:r,...i}=o;return n&&IS(n,i)?n:i}function ES(e){const t=bn(e);if(!t)return null;const n=t.destination_type==="conversation_dm"?"dm":t.state==="created"?"channel_create":"channel_post";return Wh(n,{},t)}function Zh(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:bn(t)?ES(t):n??null}function IS(e,t){const n=Object.keys(e);return n.length!==Object.keys(t).length?!1:n.every(o=>e[o]===t[o]||typeof e[o]=="object"&&JSON.stringify(e[o])===JSON.stringify(t[o]))}const AS={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"},RS=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function $u(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function Wj(e,t){const n=e.args??{},o=e.details??null,r=xs(n,o),i=r.target.label===null&&e.label&&r.target.kind!=="none"&&r.target.kind!=="message"&&r.target.kind!=="directory"?{...r,target:{...r.target,label:e.label}}:r,a=Gh(n,o),c=!i.target.label&&a&&t?t(a):null,l=Kh(i,c),d=i.outcome==="refused"||i.outcome==="failed",u=e.failed||d?cc(i.action).failed:null,f=u??cc(i.action).settled,h=lc({...i,preview:null,emoji:null},n,t,o),_=i.target.label??Zn(c)??g("ui.chat.canonical.tool_row.bridge.fallback.teammate"),y=i.op==="dm"?g("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:_}):h?g("ui.chat.canonical.tool_row.bridge.detail.headline.target",{verb:f,target:h}):f,v=[n.body,n.text,o?.text].find(S=>typeof S=="string"&&S.trim()!==""),b=typeof o?.seq=="number"?o.seq:null,p=$u(o?.error),A=(i.target.kind==="channel"||i.target.kind==="dm")&&l?l:g("ui.chat.canonical.tool_row.bridge.fallback.conversation"),k=p?p.replace(RS,(S,T)=>T.toLowerCase()==="bcv"?A:"…"):null,M=i.outcome==="refused"||i.outcome==="failed"?k&&i.code?g(i.outcome==="refused"?"ui.chat.canonical.tool_row.bridge.detail.outcome.refused":"ui.chat.canonical.tool_row.bridge.detail.outcome.failed",{code:i.code,error:k}):k:i.outcome==="unconfirmed"?k:o?.ok===!0&&b!==null?g("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:b}):null,P=[],W=new Set,R=(S,T)=>{const N=$u(T);N===null||W.has(S)||(W.add(S),P.push({key:S,value:N}))};for(const S of SS)R(S,o?.[S]);p&&p!==k&&R("error",p);for(const[S,T]of Object.entries(AS))R(T,n[S]);const m=typeof o?.content=="string"&&o.content||e.output||null,w=m&&m.trim()===p?null:m;return{tokens:i,summary:lc(i,n,t,o),failedVerb:u,failureWord:kS(i),headline:y,body:v??null,outcome:M,internals:P,raw:w}}const xS=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),TS=new Set(["true","yes","y","t","on","1"]),CS={hub:{steps:e=>{const t=$o(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=$o(e);return t!==null&&t>0?`· ${qh(t/1e3)}`:""}}};function $o(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 Du="mcp__",OS=/^\/(?:Users|home)\/[^/]+\//,PS=/\s+/;function MS(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(OS,"~/")}function wt(e){return typeof e=="string"?MS(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function jS(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function $S(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(PS).filter(Boolean).join(" ")||"?"}function DS(e){return[jS(e),wt($S(e))||"?",wt(e.message)].filter(Boolean).join(" · ")}const NS=new Set(["delivered","mailbox","unconfirmed","failed"]);function LS(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:o}=xs({op:n},t);return o==="inbox_only"?"inbox_only":o==="awaiting_acceptance"?"awaiting_acceptance":o==="unconfirmed"?"unconfirmed":null}function FS(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return LS(e);const n=e.delivery;if(!n||typeof n!="object")return null;const o=n.state;return typeof o=="string"&&NS.has(o)?o:null}function Yh(e,t,n){return!e||typeof e!="object"?t??null:FS(e,n)}function US(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 BS=["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 HS(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 o=e[n],r=t[n];if(!(!!o&&typeof o=="object")||!(!!r&&typeof r=="object")){if(o!==r)return!1;continue}const c=o,l=r;if(c.message!==l.message||c.timestamp!==l.timestamp)return!1}return!0}const WS=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function GS(e,t){return e===t?!0:!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,o)=>{const r=t[o];return!n||typeof n!="object"||!r||typeof r!="object"?n===r:WS.every(i=>i==="cost"?n.cost?.basis===r.cost?.basis:n[i]===r[i])})}function zS(e,t){for(const n of BS){const o=e[n],r=t[n];if(n==="artifacts"){if(!GS(o,r))return!1;continue}if(n==="cost"){const i=a=>a&&typeof a=="object"?a.basis:void 0;if(i(o)!==i(r))return!1;continue}if(n==="log_lines"){if(!HS(o,r))return!1;continue}if(o!==r)return!1}return!0}function Xh(e,t){const n=US(e);return n?t&&zS(n,t)?t:n:t??null}const KS={mailbox:"ui.chat.trace.send.delivery.mailbox.word",unconfirmed:"ui.chat.trace.send.delivery.unconfirmed.word",failed:"ui.chat.trace.send.delivery.failed.word"},VS={mailbox:"ui.chat.trace.send.delivery.mailbox.title",unconfirmed:"ui.chat.trace.send.delivery.unconfirmed.title"},ZS={mailbox:"ui.chat.trace.send.delivery.mailbox.note",unconfirmed:"ui.chat.trace.send.delivery.unconfirmed.note",failed:"ui.chat.trace.send.delivery.failed.note"},YS={mailbox:"ui.chat.trace.send.delivery.mailbox.label",unconfirmed:"ui.chat.trace.send.delivery.unconfirmed.label"};function Jh(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const Ts=e=>e?g(e):null,ii=e=>e.trim().toLowerCase()==="bridge";function Gj(e,t=""){return e?e==="inbox_only"?g("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?g("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&ii(t)?g("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):Ts(KS[e]):null}function zj(e,t){return e==="inbox_only"?g("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?g("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&ii(t)?g("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function Kj(e,t=""){if(e)return e==="inbox_only"?g("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?g("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&ii(t)?g("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):Ts(VS[e])??void 0}function Vj(e,t=""){return e?e==="inbox_only"?g("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?g("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&ii(t)?g("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):Ts(YS[e]):null}function Zj(e,t=""){return e?e==="inbox_only"?g("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?g("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&ii(t)?g("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):Ts(ZS[e]):null}function Yj(e){return Jh(e)?"partial":null}function Xj(e){return e==="failed"?g("ui.chat.trace.send.delivery.failed.verb"):null}function Jj(e,t){return e!==!0?!1:!Jh(t)}function Nu(e){const t=$o(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:wt(e.session)||wt(e.target)||"?"}function XS(e){const t=wt(e.query);if(t){const a=$o(e.steps);return a!==null&&Number.isInteger(a)&&a>=0?`search ${t} · ${a} around`:`search ${t}`}const n=$o(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const o=$o(e.head);if(o!==null&&Number.isInteger(o)&&o>=0)return`first ${o}`;if(e.digest===!0)return"digest";const r=wt(e.before_id);if(r)return`before ${r}`;const i=wt(e.around_id);return i?`around ${i}`:""}function JS(e){const t=tE(e);if(t==="spawn"){const n=wt(e.visibility)||"workstream",o=wt(e.name)||wt(e.prompt);return[n,o].filter(Boolean).join(" · ")}if(t==="stop"||t==="resume"||t==="info")return Nu(e);if(t==="peek")return[Nu(e),XS(e)].filter(Boolean).join(" · ");if(t==="list"){const n=[];e.include_stored===!0&&n.push("stored");const o=wt(e.query);return o&&n.push(o),n.join(" · ")}return null}function Qj(e,t,n,o){const r=e.trim();if(r.toLowerCase()==="bridge")return lc(xs(t,n),t,o,n);if(!t)return r;if(r==="send")return DS(t)||r;if(r.toLowerCase()==="sessions"){const c=JS(t);if(c!==null)return c||r}const i=nE(r)?Object.entries(t).filter(([c])=>!em.has(c)):Object.entries(t);let a=i.filter(([c])=>xS.has(c)).map(([,c])=>wt(c)).filter(Boolean);if(a.length===0){const c=CS[r.toLowerCase()];a=i.map(([l,d])=>c?.[l]?.(d)||wt(d)).filter(Boolean)}return a.slice(0,2).join(" ")||r}function Qh(e){const t=e.trim();if(!t.toLowerCase().startsWith(Du))return t;const n=t.slice(Du.length),o=n.indexOf("_");return o<=0?n||t:n.slice(o+1)||n}function QS(e,t){return e===t||e===Qh(t)}const qS=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,eE="… ";function qj(e,t=!1){if(!e||t)return null;for(const n of e.split(`
|
|
23
|
+
`)){const o=n.trim();if(o&&!qS.test(o))return`${eE}${o.slice(0,160)}`}return null}function qh(e){const t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;if(t<3600){const r=Math.floor(t/60),i=t%60;return i===0?`${r}m`:`${r}m${i}s`}if(t<86400){const r=Math.floor(t/3600),i=Math.floor(t%3600/60);return i===0?`${r}h`:`${r}h${i}m`}const n=Math.floor(t/86400);if(n>99)return"100d+";const o=Math.floor(t%86400/3600);return o===0?`${n}d`:`${n}d${o}h`}function e$(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`:qh(t)}function Lu(e){const t=e*10,n=Math.floor(t),o=t-n;return((o>.5?n+1:o<.5||n%2===0?n:n+1)/10).toFixed(1)}function t$(e){const t={minimumFractionDigits:1,maximumFractionDigits:1};return e<1024?wr(e,"B",{maximumFractionDigits:0}):e<1024*1024?wr(Number(Lu(e/1024)),"KB",t):wr(Number(Lu(e/(1024*1024))),"MB",t)}function dc(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const Fu={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 n$(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Fu,t)?Fu[t]:"plain"}function tE(e){if(!e)return"";for(const t of em){const n=e[t];if(typeof n=="string"&&n.trim()){const o=n.trim().toLowerCase(),r=e.remove,i=r===!0||r===1||typeof r=="string"&&TS.has(r.toLowerCase());return o==="milestone"&&i?"milestone-remove":t==="op"&&(o==="react"||o==="ack")?xs(e).action:o}}return""}const em=new Set(["op","action","method"]),nE=e=>Object.prototype.hasOwnProperty.call(tm,e.trim().toLowerCase()),Uu=({settled:e,running:t})=>({settled:g(e),running:g(t)}),oE={bash:{settled:"ui.chat.canonical.tool_row.verb.ran.settled",running:"ui.chat.canonical.tool_row.verb.ran.running"},eval:{settled:"ui.chat.canonical.tool_row.verb.ran_python.settled",running:"ui.chat.canonical.tool_row.verb.ran_python.running"},read:{settled:"ui.chat.canonical.tool_row.verb.read.settled",running:"ui.chat.canonical.tool_row.verb.read.running"},write:{settled:"ui.chat.canonical.tool_row.verb.wrote.settled",running:"ui.chat.canonical.tool_row.verb.wrote.running"},edit:{settled:"ui.chat.canonical.tool_row.verb.edited.settled",running:"ui.chat.canonical.tool_row.verb.edited.running"},glob:{settled:"ui.chat.canonical.tool_row.verb.listed.settled",running:"ui.chat.canonical.tool_row.verb.listed.running"},grep:{settled:"ui.chat.canonical.tool_row.verb.searched.settled",running:"ui.chat.canonical.tool_row.verb.searched.running"},web_search:{settled:"ui.chat.canonical.tool_row.verb.searched_the_web.settled",running:"ui.chat.canonical.tool_row.verb.searched_the_web.running"},web_fetch:{settled:"ui.chat.canonical.tool_row.verb.fetched.settled",running:"ui.chat.canonical.tool_row.verb.fetched.running"},web_read:{settled:"ui.chat.canonical.tool_row.verb.read.settled",running:"ui.chat.canonical.tool_row.verb.read.running"},browser:{settled:"ui.chat.canonical.tool_row.verb.browsed.settled",running:"ui.chat.canonical.tool_row.verb.browsed.running"},list_variables:{settled:"ui.chat.canonical.tool_row.verb.listed_variables.settled",running:"ui.chat.canonical.tool_row.verb.listed_variables.running"},read_variable:{settled:"ui.chat.canonical.tool_row.verb.read_variable.settled",running:"ui.chat.canonical.tool_row.verb.read_variable.running"},ask:{settled:"ui.chat.canonical.tool_row.verb.asked.settled",running:"ui.chat.canonical.tool_row.verb.asked.running"},send:{settled:"ui.chat.canonical.tool_row.verb.sent.settled",running:"ui.chat.canonical.tool_row.verb.sent.running"},wait:{settled:"ui.chat.canonical.tool_row.verb.waited_for_jobs.settled",running:"ui.chat.canonical.tool_row.verb.waited_for_jobs.running"},team_delete:{settled:"ui.chat.canonical.tool_row.verb.deleted_team.settled",running:"ui.chat.canonical.tool_row.verb.deleted_team.running"},project_delete:{settled:"ui.chat.canonical.tool_row.verb.deleted_project.settled",running:"ui.chat.canonical.tool_row.verb.deleted_project.running"},peer:{settled:"ui.chat.canonical.tool_row.verb.received.settled",running:"ui.chat.canonical.tool_row.verb.received.running"},task:{settled:"ui.chat.canonical.tool_row.verb.delegated.settled",running:"ui.chat.canonical.tool_row.verb.delegated.running"}},tm={agent:{list:{settled:"ui.chat.canonical.tool_row.verb.listed_agents.settled",running:"ui.chat.canonical.tool_row.verb.listed_agents.running"},show:{settled:"ui.chat.canonical.tool_row.verb.viewed_agent.settled",running:"ui.chat.canonical.tool_row.verb.viewed_agent.running"},search:{settled:"ui.chat.canonical.tool_row.verb.searched_agents.settled",running:"ui.chat.canonical.tool_row.verb.searched_agents.running"},install:{settled:"ui.chat.canonical.tool_row.verb.installed_agent.settled",running:"ui.chat.canonical.tool_row.verb.installed_agent.running"},reset:{settled:"ui.chat.canonical.tool_row.verb.reset_agent.settled",running:"ui.chat.canonical.tool_row.verb.reset_agent.running"},create:{settled:"ui.chat.canonical.tool_row.verb.created_agent.settled",running:"ui.chat.canonical.tool_row.verb.created_agent.running"},update:{settled:"ui.chat.canonical.tool_row.verb.updated_agent.settled",running:"ui.chat.canonical.tool_row.verb.updated_agent.running"},sync:{settled:"ui.chat.canonical.tool_row.verb.synced_agents.settled",running:"ui.chat.canonical.tool_row.verb.synced_agents.running"}},team:{list:{settled:"ui.chat.canonical.tool_row.verb.listed_teams.settled",running:"ui.chat.canonical.tool_row.verb.listed_teams.running"},show:{settled:"ui.chat.canonical.tool_row.verb.viewed_team.settled",running:"ui.chat.canonical.tool_row.verb.viewed_team.running"},create:{settled:"ui.chat.canonical.tool_row.verb.created_team.settled",running:"ui.chat.canonical.tool_row.verb.created_team.running"},update:{settled:"ui.chat.canonical.tool_row.verb.updated_team.settled",running:"ui.chat.canonical.tool_row.verb.updated_team.running"}},hub:{list:{settled:"ui.chat.canonical.tool_row.verb.listed_subagents.settled",running:"ui.chat.canonical.tool_row.verb.listed_subagents.running"},peek:{settled:"ui.chat.canonical.tool_row.verb.peeked_at.settled",running:"ui.chat.canonical.tool_row.verb.peeked_at.running"},send:{settled:"ui.chat.canonical.tool_row.verb.messaged.settled",running:"ui.chat.canonical.tool_row.verb.messaged.running"},ask:{settled:"ui.chat.canonical.tool_row.verb.asked.settled",running:"ui.chat.canonical.tool_row.verb.asked.running"},steer:{settled:"ui.chat.canonical.tool_row.verb.steered.settled",running:"ui.chat.canonical.tool_row.verb.steered.running"},pause:{settled:"ui.chat.canonical.tool_row.verb.paused.settled",running:"ui.chat.canonical.tool_row.verb.paused.running"},cancel:{settled:"ui.chat.canonical.tool_row.verb.cancelled.settled",running:"ui.chat.canonical.tool_row.verb.cancelled.running"},resume:{settled:"ui.chat.canonical.tool_row.verb.resumed.settled",running:"ui.chat.canonical.tool_row.verb.resumed.running"}},secret:{store:{settled:"ui.chat.canonical.tool_row.verb.stored_secret.settled",running:"ui.chat.canonical.tool_row.verb.stored_secret.running"},retrieve:{settled:"ui.chat.canonical.tool_row.verb.retrieved_secret.settled",running:"ui.chat.canonical.tool_row.verb.retrieved_secret.running"},list:{settled:"ui.chat.canonical.tool_row.verb.listed_secrets.settled",running:"ui.chat.canonical.tool_row.verb.listed_secrets.running"},describe:{settled:"ui.chat.canonical.tool_row.verb.described_secret.settled",running:"ui.chat.canonical.tool_row.verb.described_secret.running"},update:{settled:"ui.chat.canonical.tool_row.verb.updated_secret.settled",running:"ui.chat.canonical.tool_row.verb.updated_secret.running"},delete:{settled:"ui.chat.canonical.tool_row.verb.deleted_secret.settled",running:"ui.chat.canonical.tool_row.verb.deleted_secret.running"}},project:{list:{settled:"ui.chat.canonical.tool_row.verb.listed_projects.settled",running:"ui.chat.canonical.tool_row.verb.listed_projects.running"},show:{settled:"ui.chat.canonical.tool_row.verb.viewed_project.settled",running:"ui.chat.canonical.tool_row.verb.viewed_project.running"},create:{settled:"ui.chat.canonical.tool_row.verb.created_project.settled",running:"ui.chat.canonical.tool_row.verb.created_project.running"},update:{settled:"ui.chat.canonical.tool_row.verb.updated_project.settled",running:"ui.chat.canonical.tool_row.verb.updated_project.running"},link:{settled:"ui.chat.canonical.tool_row.verb.linked_session_to.settled",running:"ui.chat.canonical.tool_row.verb.linked_session_to.running"},unlink:{settled:"ui.chat.canonical.tool_row.verb.unlinked_session_from.settled",running:"ui.chat.canonical.tool_row.verb.unlinked_session_from.running"},milestone:{settled:"ui.chat.canonical.tool_row.verb.updated_milestone.settled",running:"ui.chat.canonical.tool_row.verb.updated_milestone.running"},"milestone-remove":{settled:"ui.chat.canonical.tool_row.verb.removed_milestone.settled",running:"ui.chat.canonical.tool_row.verb.removed_milestone.running"}},todo:{view:{settled:"ui.chat.canonical.tool_row.verb.read_todos.settled",running:"ui.chat.canonical.tool_row.verb.read_todos.running"},init:{settled:"ui.chat.canonical.tool_row.verb.updated_todos.settled",running:"ui.chat.canonical.tool_row.verb.updated_todos.running"},add:{settled:"ui.chat.canonical.tool_row.verb.updated_todos.settled",running:"ui.chat.canonical.tool_row.verb.updated_todos.running"},done:{settled:"ui.chat.canonical.tool_row.verb.updated_todos.settled",running:"ui.chat.canonical.tool_row.verb.updated_todos.running"},block:{settled:"ui.chat.canonical.tool_row.verb.updated_todos.settled",running:"ui.chat.canonical.tool_row.verb.updated_todos.running"},drop:{settled:"ui.chat.canonical.tool_row.verb.updated_todos.settled",running:"ui.chat.canonical.tool_row.verb.updated_todos.running"}},wake:{create:{settled:"ui.chat.canonical.tool_row.verb.scheduled.settled",running:"ui.chat.canonical.tool_row.verb.scheduled.running"},list:{settled:"ui.chat.canonical.tool_row.verb.listed_wakes.settled",running:"ui.chat.canonical.tool_row.verb.listed_wakes.running"},cancel:{settled:"ui.chat.canonical.tool_row.verb.cancelled_wake.settled",running:"ui.chat.canonical.tool_row.verb.cancelled_wake.running"}},jobs:{list:{settled:"ui.chat.canonical.tool_row.verb.listed_jobs.settled",running:"ui.chat.canonical.tool_row.verb.listed_jobs.running"},peek:{settled:"ui.chat.canonical.tool_row.verb.peeked_at.settled",running:"ui.chat.canonical.tool_row.verb.peeked_at.running"},cancel:{settled:"ui.chat.canonical.tool_row.verb.cancelled_job.settled",running:"ui.chat.canonical.tool_row.verb.cancelled_job.running"}},network:{status:{settled:"ui.chat.canonical.tool_row.verb.checked_network_status.settled",running:"ui.chat.canonical.tool_row.verb.checked_network_status.running"},ls:{settled:"ui.chat.canonical.tool_row.verb.listed_networks.settled",running:"ui.chat.canonical.tool_row.verb.listed_networks.running"},show:{settled:"ui.chat.canonical.tool_row.verb.viewed_network.settled",running:"ui.chat.canonical.tool_row.verb.viewed_network.running"},peers:{settled:"ui.chat.canonical.tool_row.verb.listed_network_peers.settled",running:"ui.chat.canonical.tool_row.verb.listed_network_peers.running"},log:{settled:"ui.chat.canonical.tool_row.verb.read_network_log.settled",running:"ui.chat.canonical.tool_row.verb.read_network_log.running"},doctor:{settled:"ui.chat.canonical.tool_row.verb.diagnosed_network.settled",running:"ui.chat.canonical.tool_row.verb.diagnosed_network.running"},init:{settled:"ui.chat.canonical.tool_row.verb.created_network.settled",running:"ui.chat.canonical.tool_row.verb.created_network.running"},invite:{settled:"ui.chat.canonical.tool_row.verb.invited_device.settled",running:"ui.chat.canonical.tool_row.verb.invited_device.running"},join:{settled:"ui.chat.canonical.tool_row.verb.joined_network.settled",running:"ui.chat.canonical.tool_row.verb.joined_network.running"},member_rm:{settled:"ui.chat.canonical.tool_row.verb.removed_device.settled",running:"ui.chat.canonical.tool_row.verb.removed_device.running"},disconnect:{settled:"ui.chat.canonical.tool_row.verb.left_network.settled",running:"ui.chat.canonical.tool_row.verb.left_network.running"},panic:{settled:"ui.chat.canonical.tool_row.verb.raised_panic.settled",running:"ui.chat.canonical.tool_row.verb.raised_panic.running"}},console:{list:{settled:"ui.chat.canonical.tool_row.verb.listed_consoles.settled",running:"ui.chat.canonical.tool_row.verb.listed_consoles.running"},create:{settled:"ui.chat.canonical.tool_row.verb.opened_console.settled",running:"ui.chat.canonical.tool_row.verb.opened_console.running"},status:{settled:"ui.chat.canonical.tool_row.verb.checked_console.settled",running:"ui.chat.canonical.tool_row.verb.checked_console.running"},read:{settled:"ui.chat.canonical.tool_row.verb.read_console.settled",running:"ui.chat.canonical.tool_row.verb.read_console.running"},screenshot:{settled:"ui.chat.canonical.tool_row.verb.captured_console.settled",running:"ui.chat.canonical.tool_row.verb.captured_console.running"},input:{settled:"ui.chat.canonical.tool_row.verb.typed_in_console.settled",running:"ui.chat.canonical.tool_row.verb.typed_in_console.running"},keys:{settled:"ui.chat.canonical.tool_row.verb.sent_keys.settled",running:"ui.chat.canonical.tool_row.verb.sent_keys.running"},resize:{settled:"ui.chat.canonical.tool_row.verb.resized_console.settled",running:"ui.chat.canonical.tool_row.verb.resized_console.running"},secure:{settled:"ui.chat.canonical.tool_row.verb.updated_secure_input.settled",running:"ui.chat.canonical.tool_row.verb.updated_secure_input.running"},close:{settled:"ui.chat.canonical.tool_row.verb.closed_console.settled",running:"ui.chat.canonical.tool_row.verb.closed_console.running"}},lsp:{definitions:{settled:"ui.chat.canonical.tool_row.verb.found_definition.settled",running:"ui.chat.canonical.tool_row.verb.found_definition.running"},references:{settled:"ui.chat.canonical.tool_row.verb.found_references.settled",running:"ui.chat.canonical.tool_row.verb.found_references.running"},symbols:{settled:"ui.chat.canonical.tool_row.verb.listed_symbols.settled",running:"ui.chat.canonical.tool_row.verb.listed_symbols.running"},rename_preview:{settled:"ui.chat.canonical.tool_row.verb.previewed_rename.settled",running:"ui.chat.canonical.tool_row.verb.previewed_rename.running"}},sessions:{list:{settled:"ui.chat.canonical.tool_row.verb.listed_sessions.settled",running:"ui.chat.canonical.tool_row.verb.listed_sessions.running"},info:{settled:"ui.chat.canonical.tool_row.verb.viewed_session.settled",running:"ui.chat.canonical.tool_row.verb.viewed_session.running"},spawn:{settled:"ui.chat.canonical.tool_row.verb.spawned_session.settled",running:"ui.chat.canonical.tool_row.verb.spawned_session.running"},resume:{settled:"ui.chat.canonical.tool_row.verb.resumed_session.settled",running:"ui.chat.canonical.tool_row.verb.resumed_session.running"},stop:{settled:"ui.chat.canonical.tool_row.verb.stopped_session.settled",running:"ui.chat.canonical.tool_row.verb.stopped_session.running"},peek:{settled:"ui.chat.canonical.tool_row.verb.peeked_at_session.settled",running:"ui.chat.canonical.tool_row.verb.peeked_at_session.running"}}};function rE(e,t){const n=e.trim().toLowerCase(),o=(t??"").trim().toLowerCase();if(n==="bridge"){const{settled:a,running:c}=cc(o);return{settled:a,running:c,named:!0}}const r=o?tm[n]?.[o]:void 0;if(r)return{...Uu(r),named:!0};const i=oE[n];return i?{...Uu(i),named:!0}:{settled:g("ui.chat.canonical.tool_row.generic_verb.settled"),running:g("ui.chat.canonical.tool_row.generic_verb.running"),named:!1}}function o$(e,t,n,o,r="",i=null){const a=rE(e,r),c=QS(t,e)?n??"":t;return{verb:o?a.running:i??a.settled,object:a.named?c:[Qh(e),c].filter(Boolean).join(" ")}}const iE=new Set(["write","edit"]);function nm(e){return iE.has(e.trim().toLowerCase())}function r$(e){return nm(e.toolName)&&e.diff!==null&&!e.isError}function i$(e){return nm(e.toolName)&&!e.isError&&(e.diff===null||e.diff.length===0)&&e.diffFull!==null&&e.diffFull!==void 0}function om(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(o=>typeof o=="string");return n.length?n:null}function sE(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 rm(e,t){return e===null||sE(e,t)?t:e}function im(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:dc(n.added),removed:dc(n.removed)}}function sm(e,t){return!e||typeof e!="object"?t:dc(e.diff_truncated_rows)}function aE(e){return e.length>=2&&Do(e[0])==="---"&&Do(e[1])==="+++"?e.slice(2):e.slice()}const cE=/\s+$/;function Do(e){return e.replace(cE,"")}function am(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const Bu=40,lE="[output withheld: credential redaction requires a complete bounded diff]";function dE(e){return e.length===0||Do(e[0])!==lE?!1:e.slice(1).every(t=>Do(t)===""||Do(t)==="…")}function s$(e,t={}){const n=aE(e);if(dE(n))return{lines:[],hidden:0,expandable:!1,withheld:!0};const o=n.length>Bu,r=t.expanded?n:n.slice(0,Bu);return{lines:r.map(i=>{const a=Do(i);return{text:a,marker:a.slice(0,1),kind:am(a)}}),hidden:n.length-r.length,expandable:o,withheld:!1}}function a$(e){return g("ui.chat.canonical.tool_row.diff.more",{count:e})}function c$(){return g("ui.chat.canonical.tool_row.diff.show_less")}function l$(e){return g("ui.chat.canonical.tool_row.diff.truncated",{count:e})}function d$(){return g("ui.chat.canonical.tool_row.diff.withheld")}const uc=/\s+$/u,uE=new Set(["oversized","withheld","unavailable"]);function cm(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;if(t.v!==1)return{state:"unavailable"};if(t.state==="archived"){const n=t.rows;return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0?{state:"archived",rows:n}:{state:"unavailable"}}return typeof t.state=="string"&&uE.has(t.state)?{state:t.state}:{state:"unavailable"}}function lm(e,t){return!e||typeof e!="object"?t:cm(e.diff_full)}const zr="tool_call_diff_binding_v1",fE=new Set(["custom_type","details"]),pE=new Set(["v","session_id","outer_call_id","call_id","tool","diff_full"]),hE=new Set(["v","state","rows","digest"]),mE=256;function Hu(e){return typeof e=="string"&&e.length>0&&e.length<=mE&&e.trim()===e}function ha(e,t){return Object.keys(e).every(n=>t.has(n))}function _l(e,t){if(!t||!e||typeof e!="object"||Array.isArray(e))return null;const n=e;if(n.custom_type!==zr||!ha(n,fE))return null;const o=n.details;if(!o||typeof o!="object"||Array.isArray(o))return null;const r=o;if(!ha(r,pE)||r.v!==1||r.session_id!==t)return null;const i=r.outer_call_id,a=r.call_id;if(!Hu(i)||!Hu(a)||!a.startsWith(`${i}:`)||a.length===i.length+1)return null;const c=r.tool;if(c!=="write"&&c!=="edit")return null;const l=r.diff_full;if(!l||typeof l!="object"||Array.isArray(l))return null;const d=l;if(!ha(d,hE)||d.v!==1||typeof d.state!="string"||!d.state||"rows"in d&&!(typeof d.rows=="number"&&Number.isSafeInteger(d.rows)&&d.rows>=0)||"digest"in d&&typeof d.digest!="string")return null;const u=cm(d);return u?{callId:a,outerCallId:i,tool:c,descriptor:u}:null}const bl=new WeakSet;function gE(e){return!!e&&typeof e=="object"&&bl.has(e)}function dm(e){return e.type==="custom"&&!!e.payload&&typeof e.payload=="object"&&e.payload.custom_type===zr}function _E(e,t){let n=0;for(const o of e)dm(o)&&_l(o.payload,t)!==null&&(bl.add(o.payload),n+=1);return n}function u$(e,t){const n=[];for(const o of e){if(!dm(o))continue;const r=_l(o.payload,t);r&&n.push({payload:o.payload,binding:r})}return n}function f$(e,t){return t===null||t==="not_found"?!1:(bl.add(e),!0)}const bE=new Set(["archived","oversized","withheld","unavailable","evicted","not_recorded","inline"]);function vE(e,t){return e.start!==t.start?e.start-t.start:e.offset-t.offset}function yE(e){return e.nextStart===null||e.nextOffset===null?null:{start:e.nextStart,offset:e.nextOffset}}function vo(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:null}function p$(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e;if(typeof n.state!="string"||!bE.has(n.state))return null;const o=vo(n.start),r=vo(n.total_rows);if(o===null||r===null||!Array.isArray(n.rows)||!n.rows.every(_=>typeof _=="string"))return null;const i=n.rows;if(i.length>Hr||o+i.length>r&&i.length>0)return null;const a=n.offset===void 0?0:vo(n.offset);if(a===null)return null;const c=n.next_start??null,l=n.next_offset===void 0&&c!==null?0:n.next_offset??null;let d=null,u=null;if((c!==null||l!==null)&&(d=vo(c),u=vo(l),d===null||u===null||d>r))return null;if(n.state==="archived"){if(t&&(o!==t.start||a!==t.offset)||a>0&&i.length===0)return null;if(d===null){if(o+i.length!==r)return null}else if(u===0){if(i.length===0||d!==o+i.length)return null}else if(i.length===0||d!==o+i.length-1||i.length===1&&u<=a)return null}else if(d!==null)return null;const f=typeof n.hunk_header=="string"?n.hunk_header:null,h=Array.isArray(n.clipped_rows)?n.clipped_rows.filter(_=>vo(_)!==null&&_>=o&&_<o+i.length):[];return{state:n.state,start:o,offset:a,totalRows:r,rows:i,hunkHeader:f,nextStart:d,nextOffset:u,clippedRows:h}}function h$(e){const t=e.start===0&&e.offset===0?wE(e.rows):0,n=new Set(e.clippedRows),o=e.rows.length-1,r=e.rows.slice(t).map((c,l)=>{const d=l+t,u=e.start+d,f=d===o&&(e.nextOffset??0)>0,h=f?c:c.replace(uc,"");return{index:u,text:h,kind:am(h),clipped:n.has(u),continued:d===0&&e.offset>0,continues:f}}),i=r[0],a=e.hunkHeader&&i&&i.kind!=="hunk"?e.hunkHeader:null;return{lines:r,hunkHeader:a}}function m$(e){return Math.max(0,e-Hr)}function g$(e){return Math.max(0,e-Hr)}function wE(e){return e[0]?.replace(uc,"")==="---"&&e[1]?.replace(uc,"")==="+++"?2:0}function _$(e,t){const n=Math.max(e.start,t)-t+1,o=e.start+e.rows.length-t;return{first:n,last:o,total:Math.max(0,e.totalRows-t)}}function b$(e,t){const n=yE(e);if(n&&vE(n,t)<=0)return e;const o=t.start-e.start;return o<=0?e:{...e,rows:e.rows.slice(0,o),nextStart:t.start,nextOffset:0,clippedRows:e.clippedRows.filter(r=>r<t.start)}}function v$(e){return g("ui.chat.canonical.tool_row.diff.full.view",{count:e})}function y$(){return g("ui.chat.canonical.tool_row.diff.full.back")}function w$(e,t,n){return g("ui.chat.canonical.tool_row.diff.full.range",{first:e,last:t,total:n})}function k$(){return g("ui.chat.canonical.tool_row.diff.full.nav")}function S$(){return g("ui.chat.canonical.tool_row.diff.full.first")}function E$(){return g("ui.chat.canonical.tool_row.diff.full.prev")}function I$(){return g("ui.chat.canonical.tool_row.diff.full.next")}function A$(){return g("ui.chat.canonical.tool_row.diff.full.last")}function R$(){return g("ui.chat.canonical.tool_row.diff.full.loading")}function x$(){return g("ui.chat.canonical.tool_row.diff.full.error")}function T$(){return g("ui.chat.canonical.tool_row.diff.full.retry")}function C$(){return g("ui.chat.canonical.tool_row.diff.full.empty")}function O$(e){return g("ui.chat.canonical.tool_row.diff.full.clipped",{count:e})}function P$(){return g("ui.chat.canonical.tool_row.diff.full.clipped_row")}function M$(){return g("ui.chat.canonical.tool_row.diff.full.continued")}function j$(){return g("ui.chat.canonical.tool_row.diff.full.continues")}function $$(e){switch(e){case"oversized":return g("ui.chat.canonical.tool_row.diff.full.oversized");case"withheld":return g("ui.chat.canonical.tool_row.diff.full.withheld");case"unavailable":return g("ui.chat.canonical.tool_row.diff.full.unavailable");case"evicted":return g("ui.chat.canonical.tool_row.diff.full.evicted");case"not_recorded":return g("ui.chat.canonical.tool_row.diff.full.not_recorded");case"inline":return g("ui.chat.canonical.tool_row.diff.full.inline");case"not_found":return g("ui.chat.canonical.tool_row.diff.full.not_found")}}const um="profile_save",kE="profile_revert",vl=["agent","team"],SE=["create","update","revert"],EE={agent:["label","description","tags","categories","model","instructions"],team:["label","description","manager","members","aliases","instructions","project"]},fc=s.string().max(1e5),In=e=>s.string().max(e),xn=s.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/),Kr=s.string().regex(/^sha256:[0-9a-f]{64}$/),Wu=s.union([s.string().max(1e5),s.array(s.string().max(512)).max(128),s.array(s.record(s.string(),s.unknown())).max(64),s.null()]);s.object({id:xn,name:s.string().min(1).max(128),label:In(256),description:In(16e3),tags:s.array(In(512)).max(128),categories:s.array(In(128)).max(32),model:In(512).nullable(),instructions:fc}).strict();s.object({id:xn,name:s.string().min(1).max(128),label:In(256),description:In(16e3),manager:s.string().min(1).max(128),members:s.array(s.object({role:s.string().min(1).max(128),count:s.number().int().min(1).max(16).optional(),kind:s.enum(["agent","team"]).optional(),tier:s.enum(["lo","med","hi"]).nullable().optional(),effort:s.string().max(64).nullable().optional(),saver:s.boolean().nullable().optional()}).strict()).max(64),aliases:s.array(In(128)).max(32),instructions:fc,project:fc}).strict();const fm=s.object({version:s.literal(1),operation:s.literal(um),approval_id:s.string().min(1).max(64),profile_kind:s.enum(vl),scope:s.literal("global"),profile_operation:s.enum(SE),target_id:xn,profile_name:s.string().min(1).max(128),session_id:xn,tool_call_id:xn,receipt_id:xn,changed_fields:s.array(s.string().max(64)).max(32),before:s.record(s.string(),Wu).nullable(),after:s.record(s.string(),Wu),base_commitment:Kr,after_commitment:Kr,expires_at:s.number().finite(),signing_principal:s.string().min(1).max(160)}).strict(),IE=s.object({action:s.string().min(1).max(64),operation:s.literal(um),request_digest:Kr,assurance:s.string().max(64).optional(),unproven_human:s.boolean().optional(),disclosure:fm.nullable().optional(),disclosure_digest:Kr.optional(),signable_here:s.boolean(),refusal:s.string().max(64).optional(),refusal_message:s.string().max(2e3).optional(),apply_outcome:s.object({code:s.string().max(64),retryable:s.boolean(),reason:s.string().max(2e3),remedy:s.string().max(2e3)}).strict().nullable().optional(),upgrade:s.object({available:s.boolean(),helper:s.string().max(64)}).strict().optional()}).strict(),AE=["queued","applied","proposed"],RE=s.object({status:s.enum(AE),proposal_id:s.string().regex(/^pp_[a-f0-9]{16}$/).optional(),approval_id:s.string().min(1).max(64).optional(),request_digest:Kr.optional(),expires_at:s.number().finite().optional(),receipt_id:xn.optional(),profile_kind:s.enum(vl),profile_name:s.string().min(1).max(128),scope:s.literal("global"),fields:s.array(s.string().max(64)).max(32).optional(),diff:s.array(s.string().max(2e3)).max(64).optional(),profile_action:s.unknown().optional(),revert:s.unknown().optional()}).strict(),xE=s.object({kind:s.string().max(64).optional(),name:s.string().min(1).max(128),scope:s.literal("global"),fields:s.array(s.string().max(64)).max(32).optional(),diff:s.array(s.string().max(2e3)).max(64).optional(),backup_id:s.string().max(160).optional(),revision:s.string().max(200).optional(),authorized_by:s.string().max(160).optional(),class:s.string().max(64).optional(),profile_action:s.unknown().optional(),revert:s.unknown().optional()}).strict();function TE(e){const t=xE.safeParse(e);return t.success?t.data:null}const pm=s.object({schema:s.literal(1),kind:s.literal(kE),action_id:s.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),label:s.string().min(1).max(64),profile_kind:s.enum(vl),profile_name:s.string().min(1).max(128),receipt_id:xn}).strict();function CE(e){const t=typeof e.role=="string"?e.role:"";if(!t)return"";const n=typeof e.count=="number"?e.count:1,o=e.kind==="team"?"team":"agent",r=typeof e.tier=="string"?e.tier:"",i=typeof e.effort=="string"?e.effort:"",a=e.saver===!0?"saver":e.saver===!1?"saver off":"",c=[o==="team"?"team":"",r,i,a].filter(d=>d!==""),l=n>1?` x${n}`:"";return c.length?`${t}${l} (${c.join(", ")})`:`${t}${l}`}function OE(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:typeof t=="object"&&t!==null?CE(t):"").filter(t=>t!=="").join(", "):""}function Gu(e,t){return e===null?{presence:"absent",text:""}:Object.prototype.hasOwnProperty.call(e,t)?e[t]===null?{presence:"unset",text:""}:{presence:"set",text:OE(e[t])}:{presence:"absent",text:""}}function D$(e){const t=EE[e.profile_kind],n=[];for(const o of e.changed_fields){if(!t.includes(o))continue;const r=Gu(e.before,o),i=Gu(e.after,o);if(r.presence==="set"&&i.presence==="set"){if(r.text===i.text)continue}else if(r.presence===i.presence&&r.presence==="absent")continue;n.push({field:o,before:r,after:i})}return n}function N$(e){const t=pm.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 PE(e){const t=fm.safeParse(e);return t.success?t.data:null}function L$(e){const t=IE.safeParse(e);return t.success?t.data:null}function No(e){const t=RE.safeParse(e);return t.success?t.data:null}function ME(e){const t=pm.safeParse(e);return t.success?t.data:null}const jE=new Set(["agent","team"]),$E=1048576;function yl(e,t){if(!jE.has(e)||!t||typeof t!="object"||Array.isArray(t))return null;try{const n=JSON.stringify(t);if(new TextEncoder().encode(n).byteLength>$E)return null}catch{return null}return!TE(t)&&!No(t)&&!PE(t)?null:t}function hm(e,t,n){return yl(e,t)??Xh(t,n)}const DE=`Continue working toward this goal:
|
|
25
|
+
|
|
26
|
+
`,NE=`
|
|
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.`,LE=`Work toward this goal:
|
|
29
|
+
|
|
30
|
+
{goal}
|
|
31
|
+
|
|
32
|
+
Make concrete progress with the tools available, then briefly state what advanced and what remains. If the goal is already fully met, say so plainly.`,[FE="",UE=""]=LE.split("{goal}"),BE="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.",HE="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.",WE="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 mm(e){const t=e.trim();return t===BE||t===HE||t===WE||t.startsWith(DE)&&t.endsWith(NE)||t.startsWith(FE.trim())&&t.endsWith(UE.trim())}const GE=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function zE(e,t){const n=t?.match(GE)?.[0]??null;if(!e||typeof e!="object")return n;const o=e,r=o.cost_usd,i=o.billing_basis;if(typeof r!="number"||!Number.isFinite(r)||r<0)return n;if(i!=="billed"&&i!=="estimated")return null;const a=Number(r.toFixed(4));return`Cost ${a===0&&r>0?"<$0.0001":`$${a}`} (${i}).`}const Si=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function KE(e){if(!Si(e)||e.material!=="music"||!Array.isArray(e.tracks))return;const t=Array.isArray(e.artifacts)?e.artifacts.filter(Si):[];return{...typeof e.job=="string"&&e.job.length>0?{job:e.job}:{},attribution:typeof e.attribution=="string"?e.attribution:"",tracks:e.tracks.filter(Si).filter(n=>typeof n.id=="string"&&n.id.length>0).map(n=>({id:n.id,title:typeof n.title=="string"?n.title:"",variantIndex:typeof n.variant_index=="number"?n.variant_index:0,error:typeof n.error_type=="string"||typeof n.registration_error=="string",cost:Si(n.cost)?n.cost:null,images:t.filter(o=>o.track_id===n.id&&typeof o.digest=="string"&&/^[a-f0-9]{32}$/.test(o.digest)).map(o=>({id:`music:${n.id}:${o.artifact_id}:${o.role}`,attachment:o.digest,data:null,mimeType:typeof o.content_type=="string"?o.content_type:"audio/mpeg",kind:"audio",...typeof o.name=="string"?{name:o.name}:{},...typeof o.size_bytes=="number"?{sizeBytes:o.size_bytes}:{},...typeof o.duration_s=="number"?{durationS:o.duration_s}:{}}))}))}}function Cs(e){switch(e.id){case"interrupted":return g("ui.chat.canonical.notice.interrupted");case"stopped_with_error":return g("ui.chat.canonical.notice.stopped_with_error");case"compaction_not_run":return e.sentence.includes(":")?g("ui.chat.canonical.notice.compaction_not_run_after_colon",{detail:e.sentence}):g("ui.chat.canonical.notice.compaction_not_run",{detail:e.sentence})}}function F$(e){return e.copy?Cs(e.copy):e.text}function So(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}const VE=32,ZE=32*1024,YE=256*1024;function XE(e,t,n=[]){const o=new Map(e.filter(_=>_.type==="message").map(_=>[_.id,_])),r=new Map,i=new Map,a=new Map,c=new Set(n.filter(_=>_.conflict).map(_=>_.entry.payload.target));for(const _ of[...n.map(y=>y.entry),...e]){if(_.type!=="prune"||!So(_.payload))continue;const{target:y,replacement:v}=_.payload;if(typeof y!="string"||!Number.isFinite(_.ts)||!So(v)||v.kind!=="message"||v.role!=="tool"||!Array.isArray(v.content)||!So(v.provider_payload)||Object.keys(v).some(W=>!["kind","role","content","tool_call_id","tool_name","provider_payload"].includes(W))||v.content.length===0||v.content.some(W=>!So(W)||typeof W.text!="string"||W.text.length>1e5||W.type!==void 0&&W.type!=="text"))continue;const b=v.tool_name;if(typeof b!="string"||typeof v.tool_call_id!="string"||v.tool_call_id.length===0)continue;const p=yl(b,v.provider_payload.details),A=No(p),k=ME(A?.profile_action);if(!A||A.status!=="applied"||A.profile_kind!==b||!k||k.receipt_id!==A.receipt_id||k.profile_kind!==A.profile_kind||k.profile_name!==A.profile_name)continue;const M=a.get(y),P=c.has(y)||!!(M&&JSON.stringify(M.entry.payload.replacement)!==JSON.stringify(v));a.set(y,{entry:M?.entry??_,...P||M?.conflict?{conflict:!0}:{}})}const l=[];let d=2;const u=_=>{if(new TextEncoder().encode(JSON.stringify(_.entry)).length>ZE)return;const y=new TextEncoder().encode(JSON.stringify(_)).length+(l.length?1:0);l.length<VE&&d+y<=YE&&(l.push(_),d+=y)};for(const _ of a.values()){const{entry:y}=_,{target:v,replacement:b}=y.payload,p=b.tool_name,A=No(b.provider_payload.details);if(!A)continue;const k=o.get(v),M=k?void 0:t.find(N=>N.kind==="tool"&&N.sourceEntryId===v);if(_.conflict||!k&&(!M||M.kind!=="tool")){u(_);continue}const P=k?.payload,W=P&&So(P.provider_payload)?P.provider_payload.details:M?.kind==="tool"?M.details:null,R=No(W),m=P?.tool_call_id??(M?.kind==="tool"?M.toolCallId:null),w=P?.tool_name??(M?.kind==="tool"?M.toolName:null),S=k?.ts??(M?M.ts/1e3:0);if(k&&(P?.role!=="tool"||k.type!=="message")||!R||w!==p||m!==b.tool_call_id||y.ts<S||!R.receipt_id||!R.approval_id||!R.request_digest||R.receipt_id!==A.receipt_id||R.approval_id!==A.approval_id||R.request_digest!==A.request_digest||R.profile_kind!==A.profile_kind||R.profile_name!==A.profile_name||R.scope!==A.scope)continue;const T=k?{...k,payload:b}:{id:v,type:"message",ts:S,payload:b,...M?.journalSeq!==void 0?{journal_seq:M.journalSeq}:{}};k?r.set(v,T):i.set(y.id,T)}const f=e.map(_=>r.get(_.id)??i.get(_.id)??_);for(const[_,y]of i)e.some(v=>v.id===_)||f.push(y);const h=n.length===l.length&&l.every((_,y)=>_.entry===n[y].entry&&_.conflict===n[y].conflict);return{entries:f,pending:h?n:l}}function JE(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||!So(e.payload.provider_payload))return!1;const n=No(e.payload.provider_payload.details),o=No(t.details);return!!(n?.status==="queued"&&o?.status==="applied"&&n.receipt_id&&n.receipt_id===o.receipt_id&&n.approval_id&&n.approval_id===o.approval_id&&n.request_digest&&n.request_digest===o.request_digest&&n.profile_kind===o.profile_kind&&n.profile_name===o.profile_name&&n.scope===o.scope)}function gm(e){return e}const pc="supplement_v1",QE="superseded",as=120,wl=480,qE=20,U$=500,eI=10,tI=["outside","sensitive","missing","too-large"];function _m(e,t){const n=[];let o=0;if(Array.isArray(e))for(const i of e.slice(0,eI)){if(!i||typeof i!="object")continue;const a=i,c=a.reason;if(!tI.includes(c)){o+=1;continue}n.push({name:typeof a.name=="string"?a.name:"",reason:c})}const r=typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;return{withheld:n,withheldMore:r+o}}function kl(e){return`supplement:${e}`}function nI(e){const t=e.payload??{};if(String(t.custom_type??"")!==pc)return null;const n=t.details??{},o=typeof n.anchor=="string"?n.anchor:"";return o?kl(o):null}function cs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function oI(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.path=="string"?t.path:"",o=typeof t.name=="string"?t.name:"";return!n&&!o?null:{path:n,name:o,kind:typeof t.kind=="string"?t.kind:"",sizeBytes:cs(t.size_bytes)??0,mtime:cs(t.mtime)??0,why:typeof t.why=="string"?t.why:"",...t.pinned===!0?{pinned:!0}:{}}}function bm(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const o=oI(n);o&&t.push(o)}return t}function rI(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!wm(n))return null;const o=cs(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:o===null?as:Math.min(wl,Math.max(as,Math.round(o)))}}function vm(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const o=rI(n);o&&t.push(o)}return t}function iI(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return wm(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:cs(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 ym(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const o=iI(n);o&&t.push(o)}return t}const sI=/^[a-f0-9]{32}$/,aI=/\s+/;function wm(e){return typeof e=="string"&&sI.test(e)}const cI={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function zu(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 B$(e,t){const n=e.state;if(e.error===QE||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 o;if(n==="failed")o="failed_retry";else if(n==="cancelled")o="cancelled_retry";else if(n==="decided"||n==="queued"||n==="running"||n==="cancelling")o=t?"preparing":"cancelled_retry";else return"nothing";return e.files.length?cI[o]??o:o}const H$="Preparing highlights…",W$="Highlights cancelled",G$="Couldn't prepare highlights",z$="Adjust…",K$="Cancel",V$="Retry",lI=64,dI={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 Z$(e){return typeof e=="string"&&e?dI[e]??"":""}function ma(e){return typeof e!="string"?"":e.replace(Dh,"").split(aI).filter(Boolean).join(" ")}function Y$(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function uI(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return wr(Math.trunc(e),"B",{maximumFractionDigits:0});const t=[["KB",1024],["MB",1024**2],["GB",1024**3]];for(const[n,o]of t)if(e<o*1024||n==="GB"){const r=e/o;return wr(r,n,{maximumFractionDigits:1})}return""}function X$(e){const t=ma(e.name)||ma(e.path),n=ma(e.path);return{name:t,path:n===t?"":n,size:uI(e.sizeBytes)}}function ga(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function J$(e,t,n=e){return t?`Hide ${ga(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${ga(e,"graphic")}`:`Show ${ga(e,"graphic")}`}function Q$(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const fI="supplement",pI=1,hI=["ready","resize","error","pong"],mI=["resize","error","pong"],gI=64,Sl=300,q$=5e3,eD=2e4;function tD(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==fI||n.v!==pI)return null;const o=n.t;if(typeof o!="string"||!hI.includes(o))return null;const r=o;if(mI.includes(r)&&(!t||t.length>gI||n.n!==t))return null;if(r==="error"){const i=n.msg;if(typeof i!="string"||i.length>Sl)return null}if(r==="resize"){const i=n.h;if(typeof i!="number"||!Number.isFinite(i)||i<0)return null}return{lo:"supplement",v:1,t:r,...typeof n.n=="string"?{n:n.n}:{},...typeof n.h=="number"?{h:n.h}:{},...typeof n.msg=="string"?{msg:n.msg}:{}}}function nD(){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 _I=["--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"],bI=120;function vI(e=typeof document>"u"?null:document.documentElement){if(!e||typeof getComputedStyle!="function")return{mode:"dark",vars:{}};const t=getComputedStyle(e),n={};for(const r of _I){const i=t.getPropertyValue(r).trim();i&&(n[r]=i.slice(0,bI))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function oD(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(vI()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function rD(e){return`data:text/html;base64,${yI(e)}`}function yI(e){const t=wI(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let o="";for(let r=0;r<t.length;r+=3){const i=t[r]??0,a=t[r+1]??0,c=t[r+2]??0;o+=n[i>>2],o+=n[(i&3)<<4|a>>4],o+=r+1<t.length?n[(a&15)<<2|c>>6]:"=",o+=r+2<t.length?n[c&63]:"="}return o}function wI(e){const t=[];for(const n of e){const o=n.codePointAt(0)??0;o<=127?t.push(o):o<=2047?t.push(192|o>>6,128|o&63):o<=65535?t.push(224|o>>12,128|o>>6&63,128|o&63):t.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|o&63)}return t}function iD(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function kI(e){return Math.min(wl,Math.max(as,e.heightHint))}function SI(e){return Math.min(wl,Math.max(as,e))}function sD(e,t,n){let o=0;const r=[];for(let i=0;i<e.length;i+=1){const a=e[i],c=n?.get(a.attachment),l=c!==void 0?SI(c):kI(a);if(i>0&&(!r.every(u=>n?.get(u.attachment)!==void 0)||o+l>t))break;o+=l,r.push(a)}return{visible:r,hidden:e.slice(r.length)}}const EI=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,km=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,II=/kind=(auth|quota)\b/,AI=/kind=(transient|timeout)\b/;function Sm(e){const t=a=>typeof a=="string"&&EI.test(a)&&!a.includes("://")?a:"",n=t(e.model),o=Array.isArray(e.attempts)?e.attempts.map(t).filter(Boolean).slice(0,8):void 0,r=Array.isArray(e.detail)?e.detail.filter(a=>typeof a=="string"&&(km.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,i=typeof e.cause=="string"?e.cause.slice(0,lI):"";return{...n?{model:n}:{},...o?{attempts:o}:{},...r?{detail:r}:{},...i?{cause:i}:{}}}function aD(e){if(!km.exec(e))return"";const n=e.split(" "),o=n[1].replace(":",""),r=n[3].slice(7),i=n[4].slice(5);return`Attempt ${o}: ${i}${r==="None"?"":` (HTTP ${r})`}`}function cD(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return II.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":AI.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 RI(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return Em(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:bm(e.files),..."withheld"in e||"withheld_more"in e?_m(e.withheld,e.withheld_more):{}}:{},...n==="done"?{components:vm(e.components),sounds:ym(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Sl)}:{},...Sm(e),live:!Im(n)}:null}function xI(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!Em(n))return null;const o=typeof e.files_more=="number"&&Number.isInteger(e.files_more)&&e.files_more>=0?e.files_more:0,r=Array.isArray(e.more)?e.more.filter(a=>typeof a=="string").slice(0,qE):[];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:bm(e.files),filesMore:o,more:r,components:vm(e.components),sounds:ym(e.sounds),..._m(e.withheld,e.withheld_more),...Sm(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Sl)}:{}}}function Ku(e,t,n){const o=xI(t);if(!o)return null;const r=n&&n.kind==="supplement"&&n.anchor===o.anchor?n:null;return Am(r,o,e)}function Em(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Im(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function TI(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,o)=>{const r=t[o];return n.path===r.path&&n.name===r.name&&n.kind===r.kind&&n.sizeBytes===r.sizeBytes&&n.mtime===r.mtime&&n.why===r.why&&(n.pinned??!1)===(r.pinned??!1)})}function CI(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,o)=>{const r=t[o];return n.attachment===r.attachment&&n.title===r.title&&n.source===r.source&&n.mime===r.mime&&n.heightHint===r.heightHint})}function OI(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,o)=>{const r=t[o];return n.attachment===r.attachment&&n.mime===r.mime&&n.title===r.title&&n.durationS===r.durationS&&n.origin===r.origin&&(n.path??"")===(r.path??"")&&(n.pinned??!1)===(r.pinned??!1)})}function PI(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,o)=>n.name===t[o].name&&n.reason===t[o].reason)}function Am(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&zu(t.state)<zu(e.state)))return null;const o=!e||t.version>e.version,r=t.files!==void 0?t.files:e?.files??[],i=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??(o?"":e?.error??""),h=t.cause??(o?"":e?.cause??""),_=t.dismissed??(o?!1:e?.dismissed??!1),y=t.live!==void 0?t.live===!0?!0:Im(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:kl(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:TI(r,e?.files??[])?e?.files??[]:r,filesMore:d,more:MI(u,e?.more??[])?e?.more??[]:u,components:CI(i,e?.components??[])?e?.components??[]:i,sounds:OI(a,e?.sounds??[])?e?.sounds??[]:a,withheld:PI(c,e?.withheld??[])?e?.withheld??[]:c,withheldMore:l,error:f,cause:h,model:t.model??(o?"":e?.model??""),attempts:t.attempts??(o?[]:e?.attempts??[]),detail:t.detail??(o?[]:e?.detail??[]),dismissed:_,live:y}}function MI(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,o)=>n===t[o])}const lD=e=>e.kind===void 0||e.kind==="image",Ut={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function Rm(e){return e==="skipped"||e==="aborted"}function Vu(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Zu(e,t,n,o){return Vu(n.args)??(o?.kind==="tool"?o.args:null)??Vu(e.argsByCall.get(t)?.arguments)}function xm(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function Tm(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 Ei(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Qt(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!xm(n)&&Tm(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Xn(e,t,n){const o=e?.content;if(!Array.isArray(o))return n?.length?n:Lo;const r=[];for(const i of o){const a=Tm(i);if(i.type==="document"||a===null&&!xm(i))continue;const c={id:`${t}:${r.length}`,data:typeof i.data=="string"&&i.data?i.data:null,attachment:typeof i.attachment=="string"&&i.attachment?i.attachment:null,mimeType:typeof i.content_type=="string"&&i.content_type||typeof i.mime_type=="string"&&i.mime_type||"image/png"};a!==null&&(c.kind=a,c.width=Ei(i.width),c.height=Ei(i.height),c.sizeBytes=Ei(i.size_bytes),c.durationS=Ei(i.duration_s),c.name=typeof i.name=="string"&&i.name?i.name:null,c.sourceUrl=typeof i.source_url=="string"&&i.source_url?i.source_url:null),r.push(c)}return r.length===0?Lo:n&&El(n,r)?n:r}const Lo=[],hc=[];function Cm(e,t,n){const o=e?.content;if(!Array.isArray(o))return n?.length?n:hc;const r=[];for(const i of o){const a=typeof i.filename=="string"&&typeof i.mime_type=="string"&&typeof i.attachment=="string"&&i.type===void 0;i.type!=="document"&&!a||r.push({id:`${t}:doc:${r.length}`,attachment:typeof i.attachment=="string"&&i.attachment?i.attachment:null,filename:typeof i.filename=="string"&&i.filename?i.filename:i.name??"Attached file",mimeType:i.mime_type??"application/octet-stream",path:typeof i.path=="string"&&i.path?i.path:null,storedPath:typeof i.stored_path=="string"&&i.stored_path?i.stored_path:null,bytes:typeof i.bytes=="number"?i.bytes:0,...i.injection?{injection:i.injection}:{}})}return r.length===0?n?.length?n:hc:n&&jI(n,r)?n:r}function jI(e,t){return e.length!==t.length?!1:e.every((n,o)=>{const r=t[o];return n.id===r.id&&n.attachment===r.attachment&&n.filename===r.filename&&n.mimeType===r.mimeType&&n.path===r.path&&n.storedPath===r.storedPath&&n.bytes===r.bytes&&n.injection===r.injection})}function Yu(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 Om(e,t,n){if(t.length===0)return e;if(e.length===0||El(e,t))return t;const o=Yu(e),r=Yu(t);return o!==r?o>r?e:t:n==="incoming"?e:t}function $I(e,t){return Om(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 St(e){const t=new Map;return e.forEach((n,o)=>t.set(n.id,o)),t}function DI(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const vn=new Set;function Il(e){return e.kind==="user"&&e.provisional===!0}function Pm(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,o)=>{Il(n)&&o<t&&(t=o)}),t}function Vr(e,t=vn,n){if(n?.journalMode)return Sh(n,e).map(gm);const o=e.map((a,c)=>({record:a,position:c})),r=Pm(e),i=a=>Il(a.record)||a.position>r&&!t.has(a.record.id);return o.sort((a,c)=>{const l=i(a),d=i(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 NI(e,t,n){if(!n||t<=0)return vn;let o=null;for(const r of e){if(!Il(r)||!(t>r.ts))continue;let i=!1,a=!1;for(const c of e)if(c.ts>r.ts?i=!0:c.ts<r.ts&&Tl(c)&&(a=!0),i&&a)break;i&&a&&(o??=new Set,o.add(r.id))}return o??vn}function LI(e){const{provisional:t,...n}=e;return n}function mc(e,t){const n=e,o=t,r=Object.keys(n);if(r.length!==Object.keys(o).length)return!1;for(const i of r)if(n[i]!==o[i]){if(i==="images"){const a=n[i],c=o[i];if(Array.isArray(a)&&Array.isArray(c)&&El(a,c))continue}if(i==="frame"){const a=n[i],c=o[i];if(a!==void 0&&c!==void 0&&a.epoch===c.epoch&&a.seq===c.seq)continue}if(i==="skill"){const a=n[i],c=o[i];if(a!==void 0&&c!==void 0&&FI(a,c))continue}return!1}return!0}function FI(e,t){return e.name===t.name&&e.token===t.token&&e.request===t.request&&e.purpose===t.purpose&&e.body===t.body}function De(e,t){const n=e.index.get(t.id);if(n!==void 0){const i=e.records[n];if(mc(i,t))return e;const a=e.records.slice();if(a[n]=e.journalMode?{...t,...i.sourceEntryId?{sourceEntryId:t.sourceEntryId??i.sourceEntryId}:{},...i.sourceAdmissionAnchor&&!t.sourceAdmissionAnchor?{sourceAdmissionAnchor:i.sourceAdmissionAnchor}:{},...i.sourcePrecedes&&!t.sourcePrecedes?{sourcePrecedes:i.sourcePrecedes}:{},...i.journalGeneration?{journalGeneration:t.journalGeneration??i.journalGeneration,journalSeq:t.journalSeq??i.journalSeq}:{}}:t,!e.journalMode)return{...e,records:a};const c=Vr(a,vn,e);return{...e,records:c,index:St(c)}}const o=e.journalMode?Vr([...e.records,t],vn,e):[...e.records,t],r=St(o);return{...e,records:o,index:r}}function Al(e,t){if(!e.records.some(t))return e;const n=e.records.filter(o=>!t(o));return{...e,records:n,index:St(n)}}function _a(e,t){const n=`tool:${t}`,o=e.index.get(n);if(o===void 0)return e;const r=e.records[o];return r.kind==="tool"&&(r.phase==="composing"||r.phase==="queued")?Al(e,i=>i.id===n):e}function UI(e,t,n){const o=e.index.get(`tool:${t}`);if(o===void 0)return e;const r=e.records[o];if(!(r.kind==="tool"&&(r.phase==="composing"||r.phase==="queued")))return e;const i=e.records.slice();return i[o]=n,{...e,records:i,index:St(i)}}const BI=new Set(["frontend_state_checkpoint_v1","music_job_v1","session_state","hub_communication","wake_schedule","prune"]);function Mm(e){const t=e.trim()||"compaction did not run",n={id:"compaction_not_run",sentence:t};return{text:Cs(n),copy:n,level:t.startsWith("compaction failed")?"error":"warning"}}function HI(e,t){const n=sf(e),o=sf(t);return n===o?`Context compacted to ${o} tokens`:`Context compacted, ${n} to ${o} tokens`}const jm="Context compacted",WI=12e4;function $m(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 o=new Set,r=new Set,i=new Map,a=(d,u)=>{o.add(u.id),r.add(d.id),i.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=>!o.has(f.id)&&f.before===d.before);u&&a(d,u)}const l=[];for(const d of c)if(!r.has(d.id))for(const u of n){if(u.before!==void 0)continue;const f=Math.abs(u.ts-d.ts);f>WI||l.push({live:d,durable:u,distance:f})}l.sort((d,u)=>d.distance-u.distance);for(const{live:d,durable:u}of l)r.has(d.id)||o.has(u.id)||a(d,u);return r.size===0?e:e.filter(d=>!r.has(d.id)).map(d=>{const u=i.get(d.id);return u===void 0||d.kind!=="compaction"&&d.kind!=="notice"||u===d.text?d:{...d,text:u}})}function GI(e){const t=$m(e.records);return t===e.records?e:{...e,records:t,index:St(t)}}const zI="peer_message",KI="ask_response",VI="ask_timeout",Dm="Completed — runtime retired/disposed",Nm="Retired for an update — a turn was in flight and was cut; its earlier output is kept",ZI="wake_prompt",YI="session_mcp_unavailable",XI=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),JI=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,Xu=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,QI=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."]),Lm=/^\[[^\]]{1,32}\]\s*/,ls="Reason:",qI=/[\n;,(]| [—–] /,eA=/^\d+\.$/,tA=/[A-Z]/,nA=/\s/,Sr=160;function Ui(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",...aA(t,n)};let o;return e===YI?o=oA(t):XI.has(e)?o=iA(t.trim().replace(Lm,"")):o=cA(t),{level:"info",category:null,provider:null,...o}}function oA(e){const t=e.trim().replace(Lm,"").split(`
|
|
33
|
+
`).map(c=>c.trim()),n=t[0]??"",o=t[1]?.startsWith(ls)?t[1]:null,r=t.slice(o?2:1).filter(Boolean).join(`
|
|
34
|
+
`),i=(o?`${n} ${o}`:n).trim();if(i.length<=Sr)return{headline:i,detail:r||null};const a=o===null?null:rA(o);if(a!==null){const c=(f,h)=>`${ls} ${[f,h].filter(Boolean).join(" ")}`,l=f=>[f,r].filter(Boolean).join(`
|
|
35
|
+
`)||null,d=`${n} ${c(a.leading,a.clause)}`;if(d.length<=Sr)return{headline:d,detail:l(a.rest)};const u=`${n} ${c("",a.clause)}`;if(u.length<=Sr)return{headline:u,detail:l([a.leading,a.rest].filter(Boolean).join(" "))}}return{headline:Um(i),detail:[o,r].filter(Boolean).join(`
|
|
36
|
+
`)||null}}function rA(e){const t=e.startsWith(ls)?e.slice(ls.length):e,n=t.indexOf("/mcp");if(n<0)return null;const o=t.slice(n),r=o.search(qI),i=(r<0?o:o.slice(0,r)).trim();return i?{leading:t.slice(0,n).trim(),clause:i,rest:(r<0?"":o.slice(r)).trim()}:null}function iA(e){const t=e.trim(),n=sA(t);if(n<0)return{headline:t,detail:null};const o=t.slice(n).trim();return{headline:t.slice(0,n).trim(),detail:o||null}}function sA(e){for(let t=0;t<e.length-1;t++)if(".!?…".includes(e[t])&&nA.test(e[t+1])&&!eA.test(e.slice(0,t+1))&&tA.test(e.slice(t+1).trimStart()[0]??""))return t+1;return-1}function aA(e,t){const n=e.split(`
|
|
37
|
+
`),o=n[0].match(JI),i=(typeof t.raw=="string"?t.raw.trim():"")||(o?n[0].slice(o[0].length):n[0]).trim()||e.trim(),a=n.slice(1).join(`
|
|
38
|
+
`).trim();return{provider:(o?.[1]??"").trim()||null,category:(o?.[2]??"").trim()||null,headline:i,detail:a||null}}function Fm(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,o=n.direction;if(o!=="to_child"&&o!=="to_parent")return null;const r=n.body;if(typeof r!="string"||!r.trim())return null;const i={...n};for(const a of["expects_reply","steer"])typeof i[a]!="boolean"&&(i[a]=null);for(const a of["label","job_id"])a in i&&typeof i[a]!="string"&&delete i[a];return i}function cA(e){const t=lA(e),n=e.split(`
|
|
39
|
+
`).map(o=>o.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function lA(e){const t=e.split(`
|
|
40
|
+
`).map(c=>c.trim()).filter(Boolean),n=c=>!Xu.test(c)&&!dA(c),o=t.find(n),r=t.find(c=>Xu.test(c)&&!c.startsWith("</"));let i=o??r??e.trim();const a=t.indexOf(i);if(a>=0&&i.endsWith(":")){const c=t.slice(a+1).find(n);c&&(i=`${i} ${c}`)}return Um(i)}function dA(e){return QI.has(e.replace(/\s+/g," ").trim().toLowerCase())}function Um(e){const t=e.trim();if(t.length<=Sr)return t;const n=t.slice(0,Sr),o=n.lastIndexOf(" ");return`${(o>0?n.slice(0,o):n).trimEnd()}…`}const uA="harness_injected",Bm=e=>!e||typeof e!="object"?!1:e[uA]===!0;function Hm(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function Wm(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const fA="ask";function Ju(e,t){return t===!0&&String(e??"")===fA}function pA(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function hA(e,t,n){const o=e.payload;if(!gE(o))return null;const r=o.details,i=_l(o,typeof r?.session_id=="string"?r.session_id:null);if(!i)return null;if(n?.kind==="tool"&&n.toolCallId===i.callId){if(!n.captureOnly)return n.diffFull?n:{...n,diffFull:i.descriptor};if(n.diffFull&&mA(n.diffFull,i.descriptor))return n}return{kind:"tool",id:`tool:${i.callId}`,ts:t,toolCallId:i.callId,toolName:i.tool,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:Lo,added:0,removed:0,diff:null,diffTruncatedRows:0,diffFull:i.descriptor,captureOnly:!0,stopped:!1}}function mA(e,t){return e.state===t.state&&(e.state!=="archived"||t.state==="archived"&&e.rows===t.rows)}function Gm(e){const t=e.payload;if(e.type==="custom"&&t?.custom_type===zr){const n=t.details;return`tool:${typeof n?.call_id=="string"?n.call_id:""}`}return`tool:${String(t?.tool_call_id??"")}`}function zm(e,t){const n=e.payload??{},o=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:jm,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:o,text:a,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const a=n.details??{},c=Mm(String(a.detail??""));return{kind:"notice",id:e.id,ts:o,text:c.text,copy:c.copy,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:o,complete:!0,text:Dm,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:o,complete:!0,text:Nm,level:"warning"};if(a.kind==="error"||a.kind==="interrupted"){const c=a.kind==="error"?{id:"stopped_with_error"}:{id:"interrupted"};return{kind:"notice",id:a.anchor,ts:o,complete:!0,text:Cs(c),copy:c,level:a.kind==="error"?"error":"warning"}}}}if(e.type==="custom"&&n.custom_type===pc){const a=n.details??{};return Ku(o,a,t)}if(e.type==="custom"&&n.custom_type===zr)return hA(e,o,t);if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(BI.has(a)||a===zr)return null;const c=n.details??{};if(a==="hub_message"){const f=ac(c);if(!f.body.trim())return null;const h=t?.kind==="custom"?t.receipt:void 0;return h&&fa(h.sender,f.sender)&&(f.sender=h.sender),{kind:"custom",id:e.id,ts:o,customType:a,text:f.envelope,attribution:"user",...Ui(a,f.envelope||f.body,c),receipt:h&&Object.keys(f).every(_=>h[_]===f[_])?h:f,images:Xn(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===zI){const{body:f,sender:h}=Fh(c);return{kind:"peer",id:e.id,ts:o,body:f,sender:t?.kind==="peer"&&fa(t.sender,h)?t.sender:h}}if(a===ZI){if(Xk(c)||Jk(c))return null;const f=String(c.text??"");return f.trim()?{kind:"wake",id:e.id,ts:o,text:f}:null}if(a===KI){const f=c.answers,h={};if(f&&typeof f=="object")for(const[v,b]of Object.entries(f))h[String(v)]=Array.isArray(b)?b.map(p=>String(p)):[];const _=c.questions,y=Array.isArray(_)?_.flatMap(v=>{if(!v||typeof v!="object")return[];const b=v;return[{id:String(b.id??""),question:String(b.question??""),secret:b.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:o,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:y,answers:h,secretLost:c.secret_lost===!0}}if(a===VI){const f=Number(c.waited_s);return{kind:"ask_timeout",id:e.id,ts:o,askId:String(c.ask_id??""),waitedS:Number.isFinite(f)&&f>0?f:0,urgent:c.urgent===!0}}if(a===pc)return Ku(o,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?zE(c):null)??String(c.text??c.detail??"");if(!d.trim())return null;const u=a==="job_result"?KE(c):void 0;return{kind:"custom",id:e.id,ts:o,customType:a,text:d,...u?{music:u,images:u.tracks.flatMap(f=>f.images)}:{},...a==="job_result"&&typeof c.job_id=="string"&&c.job_id.length>0?{jobId:c.job_id}:{},...a==="team_bridge_message"?{bridgeReceipt:Qk(c)}:{},attribution:n.attribution??"system",...Ui(a,d,c)}}const i=String(n.role??"");if(i==="user"){const a=Fm(n.provider_payload);if(a){const u=ac({...a,text:Qt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&fa(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:o,customType:"hub_message",text:u.envelope,attribution:"user",...Ui("hub_message",u.envelope||u.body,{...a,text:Qt(n)}),receipt:f&&Object.keys(u).every(_=>f[_]===u[_])?f:u,images:Xn(n,e.id,h)}}}if(Bm(n.provider_payload))return null;const c=Qt(n);if(mm(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:o,text:c,level:"warning"};const l=Rs(c),d=Cm(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:o,text:c,images:Xn(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(i==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=Qt(n);return!c&&a.length>0?{kind:"assistant",id:e.id,ts:o,text:"",streaming:!1,stopReason:String(n.stop_reason??"toolUse"),callsTools:!0,error:!1}:{kind:"assistant",id:e.id,ts:o,text:c,complete:!0,streaming:!1,callsTools:a.length>0,stopReason:n.stop_reason??null,error:!!n.is_error}}if(i==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(Wm(l))return null;const d=Rm(l.__fault);return{kind:"tool",id:`tool:${a}`,ts:o,toolCallId:a,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:Qt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Xn(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...im(c.details,t?.kind==="tool"?t:null),diff:rm(om(c.details),t?.kind==="tool"?t.diff:null),diffTruncatedRows:sm(c.details,t?.kind==="tool"?t.diffTruncatedRows??0:0),diffFull:lm(c.details,t?.kind==="tool"?t.diffFull??null:null),stopped:d,delivery:Yh(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:Vh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:Zh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:hm(String(n.tool_name??""),c.details,t?.kind==="tool"?t.details??null:null)}}return null}function gA(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 _A=/^(?:tool|compaction|local):/;function bA(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)&&!_A.test(t.id))return t.id}return null}function vA(e,t){const n=nI(t);if(n)return e.records[e.index.get(n)??-1]}function Rl(e){const t=Sh(e,e.records);if(t===e.records)return e;const n=t.map(gm);return{...e,records:n,index:St(n)}}const Zr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Km(e,t,n,o){const r={...e,sourceEntryId:t,journalSeq:o,journalGeneration:n};if(e.kind==="user"&&(e.provisional===!0||e.local===!0)){const{provisional:i,local:a,...c}=r;return c}return r}function yA(e){const t=new Set,n=new Set;for(const o of e.records){const r=o.sourceEntryId??(o.kind==="tool"||o.kind==="supplement"?null:o.id);typeof r!="string"||r.length<1||r.length>128||(t.add(r),o.journalGeneration===e.journalGeneration&&Zr(o.journalSeq)&&n.add(r))}return{carried:t,admitted:n}}function xl(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...o}=e;return o}function Qu(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 o=!1;const r=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=xl(a);return l!==a&&(o=!0),l});let i=o?{...e,records:r}:e;return i=Vm(i,n),i}function Vm(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:o}=yA(e),r=e.orderRevision??0,i=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)||o.has(d)||(a||(a=new Map(i??[])),a.set(d,r),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return a?{...e,journalBodyOwed:a,...l?{journalSourceVoid:l}:{}}:e}function ds(e,t,n){const o=n&&e.journalSourceUnavailable===!0?{...e,journalSourceUnavailable:void 0}:e;if(t.length===0)return o;const r=o.journalBodyOwed;let i=null;const a=o.journalSourceVoid;let c=null;for(const l of t)r?.has(l)&&(i||(i=new Map(r)),i.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!i&&!c?o:{...o,...i?{journalBodyOwed:i}:{},...c?{journalSourceVoid:c}:{}}}function si(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function Zm(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function wA(e,t,n){let o=zo(e,t,t.entries.map(i=>({id:i.id,journal_seq:i.journal_seq,role:i.payload?.role,tool_call_id:i.payload?.tool_call_id})),!0,n);for(const i of t.entries)o=cl(o,{...i.payload,id:i.id});const r=si(o,!1);return Rl(r.journalPeerSource===void 0&&!r.journalBodyOwed&&!r.journalSourceVoid&&r.journalSourceUnavailable===void 0?r:{...r,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function qu(e,t,n){let o=zo(e,t,(t.entries??[]).map(i=>({id:i.id,journal_seq:i.journal_seq,role:i.payload?.role,tool_call_id:i.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(o=si(o,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===o.journalGeneration){const i=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];i.length>0&&(o=Vm(o,i));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){o=ds(o,a,!1);const c=new Set(o.journalSourceVoid??[]);for(const l of a)c.add(l);o={...o,journalSourceVoid:c}}}return o=Zm(o,t),Rl(o)}function kA(e,t,n,o){let r=zo(e,t,[],!1,n,{peer:!0});r=si(r,!0);const i=r.journalBodyOwed,a=_=>o!==void 0&&(i?.get(_)??Number.NEGATIVE_INFINITY)>o,c=t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration,l=c?[...t.entries??[],...t.dependency_entries??[]]:[],d=[];let u=r.records,f=r.index;if(l.length>0){const _=new Map;for(const y of l){if(typeof y.id!="string"||y.id===""||a(y.id))continue;const v=Gm(y),b=f.get(y.id)??f.get(v),p=b===void 0?void 0:u[b];if(!p)continue;let A=zm(y,p);A&&(A={...A,sourceEntryId:y.id,...p.sourcePrecedes?{sourcePrecedes:p.sourcePrecedes}:{}},Zr(y.journal_seq)?(A=Km(A,y.id,t.journal_generation,y.journal_seq),d.push(y.id)):A=xl(A),_.set(p.id,A))}_.size>0&&(u=u.map(y=>_.get(y.id)??y),f=St(u))}let h=u===r.records?r:{...r,records:u,index:f};if(c){h=ds(h,d,!1);const _=(t.source_missing_ids??[]).filter(y=>typeof y=="string"&&y.length>0&&y.length<=128&&!a(y));if(_.length>0){h=ds(h,_,!1);const y=new Set(h.journalSourceVoid??[]);for(const v of _)y.add(v);h={...h,journalSourceVoid:y}}}return h=Zm(h,t),Rl(h)}function Ii(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function Er(e,t,n={}){let o=e;const r=o,i=[];let a=e.profileHistoryPending;const c=E=>si(ds(E.profileHistoryPending===a?E:{...E,profileHistoryPending:a},i,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(o=zo(o,t,t.entries.map(E=>({id:E.id,journal_seq:E.journal_seq,role:E.payload?.role,tool_call_id:E.payload?.tool_call_id})),n.authoritative===!0,n.orderRead,{peer:n.peerSource===!0}),t.journal_generation&&t.journal_generation!==o.journalGeneration)return c(o);const l=n.peerSource===!0&&typeof t.journal_generation=="string"&&t.journal_generation.length>0&&t.journal_generation===o.journalGeneration;for(const E of t.entries)o=cl(o,{...E.payload,id:E.id});const d=n.keepPaging===!0&&o.viewEpoch>0,u=n.pagedBefore!==void 0&&o.index.has(n.pagedBefore)?n.pagedBefore:o.records[0]?.id,f=XE(t.entries,o.records,d||r.journalGeneration!==o.journalGeneration?[]:o.profileHistoryPending);a=!d&&f.pending.length?f.pending:void 0;const h=[];for(const E of f.entries){if(d&&!UA(E,o.clearedAt))continue;const V=o.records[o.index.get(E.id)??-1]??o.records[o.index.get(Gm(E))??-1]??vA(o,E);let G=zm(E,V);if(JE(E,V)&&V&&(G=V),G&&(o.journalMode||G.kind==="tool"&&yl(G.toolName,G.details))&&(G={...G,sourceEntryId:E.id}),G&&o.journalMode){const me=V?.sourcePrecedes??(n.pagedBefore!==void 0&&!V?u:void 0);me!==void 0&&G.sourcePrecedes!==me&&(G={...G,sourcePrecedes:me})}G&&l&&Zr(E.journal_seq)?(G=Km(G,E.id,t.journal_generation,E.journal_seq),i.push(E.id)):G&&n.peerSource===!0&&(G=xl(G)),!(G&&V&&pA(V,n.readWitness))&&G&&h.push(G)}let _=o.argsByCall,y=!1;for(const E of t.entries){const V=E.payload?.tool_calls;if(!Array.isArray(V))continue;const G=Math.round((E.ts??0)*1e3);for(const me of V)!me||typeof me.id!="string"||_.has(me.id)||(y||(_=new Map(_),y=!0),_.set(me.id,{...me,anchoredAt:G,anchorId:E.id}))}for(let E=0;E<h.length;E++){const V=h[E];if(V.kind!=="tool")continue;const G=_.get(V.toolCallId);if(!G)continue;const me=G.arguments??null;h[E]={...V,args:me,intent:typeof me?.i=="string"?me.i:null}}const v=y?o.records.map(E=>{if(E.kind!=="tool"||E.args)return E;const G=_.get(E.toolCallId)?.arguments??null;return G?{...E,args:G,intent:E.intent??(typeof G.i=="string"?G.i:null)}:E}):o.records,b=new Set(t.entries.map(E=>E.id)),p=n.peerSource===!0&&n.replace===!0?o.records.filter(E=>E.kind==="user"&&(E.provisional===!0||E.local===!0)&&!b.has(E.id)):[],A=n.replace?p.length>0?{...Ut,records:p,index:St(p)}:Ut:{...o,records:v},k=new Map(A.records.map(E=>[E.id,E]));let M=o!==r||n.replace||!n.replace&&v!==o.records;for(const E of h){const V=k.get(E.id);if(!V){M=!0,k.set(E.id,E);continue}if(V.kind==="tool"&&E.kind==="tool"){const G={...E,args:E.args??V.args,intent:E.intent??V.intent,images:Om(E.images,V.images,"current")};mc(V,G)||(M=!0,k.set(E.id,G));continue}mc(V,E)||(M=!0,k.set(E.id,E))}const P=o.compacting&&t.entries.some(E=>o.index.has(E.id)||Math.round((E.ts??0)*1e3)<o.compactingSince?!1:E.type==="compaction"||E.type==="message"&&E.payload?.custom_type==="compaction_refused"),W=t.entries[0],R=W?Math.round((W.ts??0)*1e3):0,m=o.journalMode?vn:NI(A.records,R,n.statedByOwner!==!1);let w=A.oldestId,S=A.oldestTs,T=o.hasMore;n.keepPaging||(n.replace||o.oldestId===null?(W&&(w=W.id,S=R),T=t.has_more):n.pagedBefore!==void 0?W?(w=W.id,S=R,T=t.has_more):T=!1:W&&(o.journalMode?(o.journalPositions?.get(W.id)?.seq??Number.POSITIVE_INFINITY)<(o.journalPositions?.get(o.oldestId??"")?.seq??-1):R>0&&R<o.oldestTs)&&(w=W.id,S=R,T=t.has_more));const N=w!==o.oldestId||S!==o.oldestTs;if(!M&&!N&&o.hasMore===T&&!P&&m.size===0)return c(o);const Y=m.size===0?[...k.values()]:[...k.values()].map(E=>m.has(E.id)?LI(E):E),X=$m(Vr(Y,n.statedByOwner===!1?vn:new Set(h.map(E=>E.id)),o));return n.keepPaging?c({...o,records:X,index:St(X),argsByCall:_}):c({...o,records:X,index:St(X),oldestId:w,oldestTs:S,hasMore:T,argsByCall:_,compacting:P?!1:o.compacting,compactingSince:P?0:o.compactingSince})}const SA=/^(?:local|notice|retry|subagent|compaction):/;function Tl(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!SA.test(e.id)}}function EA(e,t,n=vn){if(e.journalMode||t.ts<=0)return e;const o=e.records.filter(r=>!(r.ts<t.ts&&Tl(r)&&!n.has(r.id)));return o.length===e.records.length?e:{...e,records:o,index:St(o),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const an={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function ba(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function gc(e,t,n=Date.now(),o={}){let r=e;const i=t.message;if(t.type==="journal_order_ready"){const l=typeof t.journal_generation=="string"?t.journal_generation:void 0;if(r={...r,orderNeedsReconcile:!0,orderWantedGeneration:t.reconcile===!0?void 0:l,orderDemand:t.reconcile===!0?{}:{generation:l}},t.reconcile===!0)return r;const d=zo(r,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=Vr(d.records,vn,d);return d===r&&u===r.records?r:{...d,records:u,index:St(u)}}i&&(r=cl(r,i));const a=o.frame,c=o.queuedAskEngine;switch(t.type){case"agent_start":{const l=Number(t.generation??r.generation+1);return l===r.generation?r:{...r,generation:l,compacting:!1,compactingSince:0}}case"compaction_start":return r.compacting?r:{...r,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??r.generation)<r.generation)return r;let d=r;for(const u of r.records)if(u.kind==="assistant"&&u.streaming&&(d=De(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=De(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=ba(i);if(i===void 0||l===null)return an.idlessFrameRefused+=1,r;const d=r.records[r.index.get(l)??-1];if(i.role==="user"){const u=Fm(i.provider_payload);if(u){const v=Qt(i),b=ac({...u,text:v});if(b.body.trim()){const p=d?.kind==="user"&&d.provisional===!0;return De(r,{kind:"custom",id:l,ts:p?us(r,n):n,customType:"hub_message",text:b.envelope,attribution:"user",...Ui("hub_message",b.envelope||b.body,{...u}),receipt:b,images:Xn(i,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(Bm(i.provider_payload))return r;const f=Qt(i);if(mm(f))return r;const h=d?.kind==="user"&&d.provisional===!0,_=Cm(i,l,d?.kind==="user"?d.documents:void 0),y=Rs(f);return De(r,{kind:"user",id:l,ts:h?us(r,n):n,text:f,images:Xn(i,l,d?.kind==="user"?d.images:void 0),..._.length?{documents:_}:{},...h?{provisional:!0}:{},...y?{skill:y}:{}})}return i.role!=="assistant"||d?r:De(r,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=ba(i);if(i===void 0||l===null)return an.idlessFrameRefused+=1,r;const d=r.index.get(l),u=String(t.delta??""),f=Qt(i);if(d===void 0)return!f&&!u?r:De(r,{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=r.records[d];if(h.kind!=="assistant")return r;if(!h.streaming)return an.settledAssistantUpdate+=1,r;if(o.seed!==!0&&a&&h.frame&&a.epoch===h.frame.epoch&&a.seq<=h.frame.seq)return an.staleUpdateFrameDropped+=1,r;const _=DI(h.frame,a);if(o.seed===!0&&!f)return!h.text&&!u?r:(an.seededDeltaWithheld+=h.text?1:0,De(r,{...h,text:h.text||u,..._?{frame:_}:{},truncated:h.text?"interrupted":"prefix"}));let y;if(f){if(y=f+u,y.length<=h.text.length)return r}else{if(!u)return r;y=h.text+u}return De(r,{...h,text:y,..._?{frame:_}:{},truncated:f?void 0:h.truncated})}case"message_end":{const l=ba(i);if(i===void 0)return an.idlessFrameRefused+=1,r;if(l===null){if(i.role!=="assistant")return an.idlessFrameRefused+=1,r;let y;for(const p of r.records)if(!(p.kind!=="assistant"||!p.streaming)){if(y!==void 0)return an.idlessFrameRefused+=1,r;y=p}if(y===void 0)return an.idlessFrameRefused+=1,r;const v=Array.isArray(i.tool_calls)?i.tool_calls:[],b={...y,streaming:!1,settledAt:y.settledAt??n,callsTools:v.length>0,...y.text||v.length===0?{complete:!0}:{}};return De(r,b)}if(i.role!=="assistant")return r;const d=r.index.get(l),u=Qt(i),f=d===void 0?void 0:r.records[d],h=Array.isArray(i.tool_calls)?i.tool_calls:[],_={kind:"assistant",id:l,ts:d===void 0?n:r.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:i.stop_reason??null,error:!!i.is_error,...a?{frame:a}:{}};return De(r,_)}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,_="journal_generation"in t||"journal_ordinals"in t||"entry_times"in t,y=r.journalPeerSource===!0||_,v=y&&u!==void 0&&u===r.journalGeneration,b=d.map(k=>String(k.id??"")).filter(k=>k.length>0&&k.length<=128),p={entries:d.map(k=>{const M=String(k.id??""),P=f?.[M],W=h?.[M];return{id:M,ts:v&&typeof W=="number"&&Number.isFinite(W)?W:n/1e3,type:"message",payload:{kind:k.custom_type?"custom":"message",...k},...v&&Zr(P)?{journal_seq:P}:{}}}),has_more:r.hasMore,...v?{journal_generation:u}:{}};let A=Er(r,p,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:y});if(y&&b.length>0)if(v){const k=b.filter(M=>!Zr(f?.[M]));k.length>0&&(A=Qu(A,k))}else A=Qu(A,b),u!==void 0&&(A=zo(A,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),A=si(A,!0));return A}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return r;const d=String(t.supersedes_tool_call_id??""),u=`tool:${l}`,f=r.records[r.index.get(u)??-1],h=d?r.records[r.index.get(`tool:${d}`)??-1]:void 0,_=f?.kind==="tool"?f:h?.kind==="tool"?h:void 0;if(_&&_.phase!=="composing"&&_.phase!=="queued")return d&&f?.kind==="tool"?_a(r,d):r;const v=String(t.not_run_reason??"").trim()||null,b=String(t.not_run_kind??"").trim()||null;if(Ju(t.tool_name,c)&&!v&&!_)return d?_a(r,d):r;const p=Number(t.argument_bytes??0),A={kind:"tool",id:u,ts:_?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:v?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:p>0?p:_?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:Lo,added:0,removed:0,diff:null,diffTruncatedRows:0,diffFull:null,stopped:!1,notRunReason:v,notRunKind:v?b:null,neverSent:v!==null};return d&&h?.kind==="tool"&&f?.kind!=="tool"?UI(r,d,A):De(d&&f?.kind==="tool"?_a(r,d):r,A)}case"tool_execution_start":{const l=String(t.tool_call_id??"");if(!l)return r;const d=`tool:${l}`,u=r.records[r.index.get(d)??-1];if(u&&u.kind==="tool"&&u.phase==="done"&&!u.notRunReason)return r;const f=Zu(r,l,t,u),h=f&&!r.argsByCall.has(l)?new Map(r.argsByCall).set(l,{arguments:f,anchoredAt:Fo(t)??n}):r.argsByCall,_=h===r.argsByCall?r:{...r,argsByCall:h};return Ju(t.tool_name,c)&&!u?_:De(_,{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:Fo(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:Lo,added:0,removed:0,diff:u?.kind==="tool"?u.diff:null,diffTruncatedRows:u?.kind==="tool"?u.diffTruncatedRows??0:0,diffFull:u?.kind==="tool"?u.diffFull??null: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 r;const d=`tool:${l}`,u=r.records[r.index.get(d)??-1];if(!u||u.kind!=="tool")return r;const f=t.partial_result??{},h=Xh(f.details,u.details);return h===(u.details??null)?r:De(r,{...u,details:h})}case"tool_execution_end":{const l=String(t.tool_call_id??"");if(!l)return r;const d=`tool:${l}`,u=r.records[r.index.get(d)??-1],f=t.result??{};if(Wm(f.details))return Jm(r,d);const h=Zu(r,l,t,u),_=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:Lo,added:0,removed:0,diff:null,diffTruncatedRows:0,diffFull:null,stopped:!1},y=h&&!r.argsByCall.has(l)?new Map(r.argsByCall).set(l,{arguments:h,anchoredAt:Fo(t)??n}):r.argsByCall,v=y===r.argsByCall?r:{...r,argsByCall:y},b=o.userStoppedAt??null,p=!!(t.is_error??f.is_error),A=Rm(f.details?.__fault),k=b!==null&&(typeof _.startedAt=="number"?_.startedAt<=b:p);return De(v,{..._,args:h,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:Qt(f)||null,isError:k||A?!1:p,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof _.startedAt=="number"?_.startedAt+t.duration_s*1e3:null,startedAt:null,images:$I(Xn(f,d,_.images),_.images),...im(f.details,_),diff:rm(om(f.details),_.diff),diffTruncatedRows:sm(f.details,_.diffTruncatedRows??0),diffFull:lm(f.details,_.diffFull??null),stopped:_.stopped||k||A,delivery:Yh(f.details,_.delivery,_.toolName),bridge:Vh(_.toolName,f.details,_.bridge),bridgeLabel:Zh(_.toolName,f.details,_.bridgeLabel),details:hm(_.toolName,f.details,_.details)})}case"supplement_progress":{const l=RI(t);if(!l)return r;const d=kl(l.anchor),u=r.records[r.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,h=Am(f,l,n);return h?De(r,h):r}case"notice":{const l=String(t.text??"");if(!l)return r;const d=`notice:${r.generation}:${l}`;return r.index.has(d)?r:De(r,{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:Mm(String(t.detail??"")),h=f?f.text:l&&d?HI(l,d):jm,_=`compaction:${r.generation}:${l}:${d}`,y=r.compacting?{...r,compacting:!1,compactingSince:0}:r;return y.index.has(_)?y:f?De(y,{kind:"notice",id:_,ts:n,text:h,copy:f.copy,level:f.level}):GI(De(y,{kind:"compaction",id:_,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:${r.generation}:${String(t.attempt??"")}`;return r.index.has(d)?r:De(r,{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=r.records[r.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?r:De(r,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return r}}function Fo(e){return Gw(e.started_at_epoch)}function Cl(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function IA(e){const t=Cl(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function AA(e,t){const n=Fo(e);if(n!==null)return n;const o=Cl(e);if(!o)return null;const r=t.argsByCall.get(o)?.anchoredAt;return typeof r=="number"&&Number.isFinite(r)&&r>0?r:null}function RA(e,t){if(Fo(e)!==null)return!1;const n=Cl(e);if(!n)return!1;const o=t.argsByCall.get(n)?.anchorId;if(typeof o!="string")return!1;const r=t.index.get(o);return r!==void 0&&r<=Pm(t.records)}function Ol(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 Os(e){return e.type==="tool_execution_end"}function xA(e,t,n=Date.now(),o=null){let r=e;t.streaming&&t.generation>r.generation&&(r={...r,generation:t.generation}),r.compacting&&(r={...r,compacting:!1,compactingSince:0});const i=t.streaming===!0,a=Hm(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let h=n;const _=IA(f);if(_!==null&&!r.index.has(_)){const y=AA(f,r);if(y!==null)h=y,c=!0,RA(f,r)&&l.add(_);else if(Os(f)||Ol(f)||!i)continue}r=gc(r,f,h,{seed:!0,queuedAskEngine:a,...o?{frame:o}:{}})}if(!c)return r;const d=Vr(r.records,l,r);return{...r,records:d,index:St(d)}}function ef(e){const t=new Map;for(const n of e??[]){if(!n)continue;const o=n;if(!Os(o)&&!Ol(o))continue;const r=String(o.tool_call_id??"");if(!r)continue;const i=Fo(o);i!==null&&t.set(r,i)}return t}function TA(e){const t=new Set;for(const n of e??[]){if(!n)continue;const o=n;if(o.type!=="tool_call_compose")continue;const r=o.not_run_reason;if(typeof r=="string"&&r.trim().length>0)continue;const i=String(o.tool_call_id??"");i&&t.add(i)}return t}const CA=5e3;function OA(e,t){const n=new Set(t),o=new Map;if(n.size===0)return o;for(const r of e){if(r.payload?.role!=="tool")continue;const i=r.payload.tool_call_id;if(typeof i!="string"||!n.has(i))continue;const a=r.ts;typeof a!="number"||!Number.isFinite(a)||o.set(i,Math.round(a*1e3))}return o}function PA(e,t,n,o=new Map,r=new Set){const i=e[0]?.ts;if(typeof i!="number"||!Number.isFinite(i))return!1;let a=null;for(const l of t){const d=n.get(l);if(d===void 0){if(r.has(l))continue;return!1}(a===null||d<a)&&(a=d)}for(const l of o.values())(a===null||l<a)&&(a=l);return a===null?!1:Math.round(i*1e3)<=a-CA}function tf(e,t){const n=[];for(const o of e??[]){if(!o)continue;const r=o;if(!Os(r)&&!Ol(r))continue;const i=String(r.tool_call_id??"");!i||n.includes(i)||t.has(i)||n.push(i)}return n}function nf(e,t,n,o){const r=[],i=new Set;for(const a of t)i.has(a)||(i.add(a),!n.has(a)&&((e.get(a)??0)>=o||r.push(a)));return r}const MA=3.25,_c=100,Pl=500;function of(e){return e<=0?_c:Math.min(Pl,_c+Math.ceil(MA*e))}function va(e,t){const n=[];if(t.size===0)return n;for(const o of e){const r=o.payload?.tool_calls;if(Array.isArray(r))for(const i of r)i&&typeof i.id=="string"&&t.has(i.id)&&n.push(i.id)}return n}function jA(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function $A(e,t){const n=new Set(t);for(const i of e){const a=i.payload?.tool_calls;if(Array.isArray(a))for(const c of a)c&&typeof c.id=="string"&&n.add(c.id)}const o=[],r=new Set;for(const i of e){if(i.payload?.role!=="tool")continue;const a=i.payload.tool_call_id;typeof a!="string"||n.has(a)||r.has(a)||(r.add(a),o.push(a))}return o}function DA(e,t){return e&&t===0}function NA(e){const t=new Set;for(const n of e??[]){if(!n)continue;const o=n,r=o.not_run_reason,i=o.type==="tool_call_compose"&&typeof r=="string"&&r.trim().length>0;if(o.type!=="tool_execution_start"&&!Os(o)&&!i)continue;const a=String(o.tool_call_id??"");a&&t.add(a)}return t}function Ym(e,t,n){const o=new Set(e),r=[];for(const i of t)!o.has(i)&&!n.has(i)&&r.push(i);for(const i of e){if(n.has(i))return r;t.has(i)&&r.push(i)}return r}function LA(e,t,n){return Ym(e,t,n).length}function rf(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=De(t,{...n,truncated:"interrupted"}));return t}function FA(e,t=Date.now()){return e.records.length===0&&!e.profileHistoryPending?.length?e:{...Ut,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function UA(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 sf(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function BA(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return Al(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function us(e,t){let n=t;for(const o of e.records)o.ts>n&&(n=o.ts);return n}function Xm(e,t,n,o,r=Date.now(),i=hc){if(e.index.has(t))return e;const a=Rs(n);return De(e,{kind:"user",id:t,ts:us(e,r),text:n,images:o,...i.length?{documents:i}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function Jm(e,t){return Al(e,n=>n.id===t)}let af=0;function HA(e,t,n,o=Date.now()){return af+=1,De(e,{kind:"notice",id:`local:${o}:${af}`,ts:us(e,o),text:t,level:n})}function dD(e,t,n,o){const r=t?.anchor_id,i=t?.kind;if(!r||i!=="error"&&i!=="interrupted"&&i!=="closed"&&i!=="retired"||n||e.index.has(r)||!t?.unseen&&!o?.has(r))return e;o?.add(r);const a=i==="error"?{id:"stopped_with_error"}:i==="interrupted"?{id:"interrupted"}:void 0;return De(e,{kind:"notice",id:r,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:i==="closed"?Dm:i==="retired"?Nm:Cs(a),...a?{copy:a}:{},level:i==="closed"?"info":i==="retired"?"warning":i==="error"?"error":"warning"})}const WA=5*60,GA="session_temporary",zA="session_temporary_deleted",KA=["running","on_screen","open_ask","armed_wake","armed_monitor","unread_mail","operator_hold","unseen_result","unsaved_files","linked","cannot_verify"];function cf(e,t){if(!t||!e)return null;const n=e.temporary;return n===null||typeof n!="object"||typeof n.marked_at!="number"||!Number.isFinite(n.marked_at)?null:n}function Qm(e,t){if(!t)return{normal:e,temporary:[]};let n=!1;for(const i of e)if(cf(i,!0)!==null){n=!0;break}if(!n)return{normal:e,temporary:[]};const o=[],r=[];for(const i of e)(cf(i,!0)!==null?r:o).push(i);return{normal:o,temporary:r}}function uD(e,t){return e?t.some(n=>n.session_id===e):!1}function VA(e,t){return e.hold!==null&&e.hold!==void 0||typeof e.deletes_at!="number"||!Number.isFinite(e.deletes_at)?null:Math.max(1,Math.floor((e.deletes_at-t)/60))}function fD(e,t){return typeof e!="number"||!Number.isFinite(e)?!1:e-t<=WA}function pD(e,t){if(e.hold!==null&&e.hold!==void 0)return{key:"hold",code:qm(e.hold)};const n=VA(e,t);return n===null?{key:"hold",code:"cannot_verify"}:{key:"deletes_in",minutes:n}}function qm(e){return KA.includes(e)?e:"cannot_verify"}const ZA={running:"ui.chat.sidebar_view.temporary.hold.running",on_screen:"ui.chat.sidebar_view.temporary.hold.on_screen",open_ask:"ui.chat.sidebar_view.temporary.hold.open_ask",armed_wake:"ui.chat.sidebar_view.temporary.hold.armed_wake",armed_monitor:"ui.chat.sidebar_view.temporary.hold.armed_monitor",unread_mail:"ui.chat.sidebar_view.temporary.hold.unread_mail",operator_hold:"ui.chat.sidebar_view.temporary.hold.operator_hold",unseen_result:"ui.chat.sidebar_view.temporary.hold.unseen_result",unsaved_files:"ui.chat.sidebar_view.temporary.hold.unsaved_files",linked:"ui.chat.sidebar_view.temporary.hold.linked",cannot_verify:"ui.chat.sidebar_view.temporary.hold.cannot_verify"};function hD(e){return ZA[qm(e)]}function mD(e,t,n){return!e||t?null:n!==null?"keep":"make"}function gD(e,t){return e!==GA?null:t==="pin"?"keep_and_pin":"keep_and_link"}function _D(e,t){return Qm(e,t).normal}function bD(e,t,n){const{normal:o,temporary:r}=Qm(e,t);if(!n||r.length===0)return o;const i=r.find(a=>a.session_id===n);return i?[i,...o]:o}function YA(e,t){return t&&e?.temporary===!0&&!e.peer}function vD(e){return e===!0?"ui.chat.composer.placeholder.temporary":null}function XA(e){return e===zA}const JA="compacting context…";function yD(e){return typeof e=="string"&&e.trim()===JA}const QA=[1500,5e3];async function wD(e,t=n=>new Promise(o=>setTimeout(o,n))){for(const n of QA){await t(n);try{if(await e())return}catch{}}}function qA(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 eR=["store","routed","request","snapshot","content","painted","sendable"],tR=6e4,nR="[open-trace]",oR=/^[A-Za-z0-9_-]{1,80}$/,rR=["sidebar","open","native"];function iR(e,t,n){const o=oR.test(e.sessionId)?e.sessionId:"?",r=rR.includes(e.entrance)?e.entrance:"open",i=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=[nR,`t=${e.token}`,`clickEpochMs=${e.clickEpochMs??"-"}`,`session=${o}`,`via=${r}`,`outcome=${t}`,...eR.map(u=>`${u}=${i(e.stages[u])}`),`settled=${i(l)}`];return n!==void 0&&d.push(`by=t${n}`),d.join(" ")}function sR(e){let t=0,n=null;const o=(i,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(iR(c,i,a));for(const l of c.endListeners.splice(0))l()}},r=(i,a)=>{i.stages[a]===void 0&&(i.stages[a]=e.now(),i.stages.painted!==void 0&&i.stages.sendable!==void 0&&o("settled"))};return{begin(i,a){t+=1;const c=t;n&&o("superseded",c);const l={token:c,sessionId:i,entrance:a,start:e.now(),clickEpochMs:performance.timeOrigin+performance.now(),stages:{},fallbacks:{},timer:void 0,frameRequested:!1,endListeners:[]};return l.timer=e.setTimer(()=>{n===l&&o("timeout")},tR),n=l,c},note(i,a,c,l){const d=n;if(!(!d||!i||d.sessionId!==i)&&!(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,r(d,"content"),e.nextFrame(()=>{n===d&&r(d,"painted")});return}a==="painted"||a==="content"||r(d,a)}},fail(i,a){!n||!i||n.sessionId!==i||o(a)},activeSessionId(){return n?.sessionId??null},currentToken(){return n?.token??null},onEnd(i,a){n?.token===i?n.endListeners.push(a):a()}}}const aR=typeof window<"u";function cR(e,t,n){t(()=>n(e))}const lR=e=>{const t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)},Uo=sR({now:()=>performance.now(),nextFrame:e=>{aR&&typeof requestAnimationFrame=="function"&&typeof MessageChannel=="function"?cR(e,t=>requestAnimationFrame(()=>t()),lR):setTimeout(e,0)},log:e=>console.warn(e),setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e)});function dR(e,t,n,o){let r=!1;const i=()=>{const c=e.activeSessionId();if(c===null||e.currentToken()!==t)return;const l=n();if(l.activeSessionId!==c||l.activeDraftKey){r&&e.fail(c,"left");return}r=!0,e.note(c,"store"),l.validatingSessionId!==c&&e.note(c,"sendable")},a=o(i);e.onEnd(t,a),i()}const lf=new Set(["openrouter","radient","radient-key"]),uR=new Set(["auto","openrouter/auto"]),fR=()=>g("ui.chat.session_readout.model.router_auto");function eg(e){return e.slice(e.lastIndexOf("/")+1)||e}function pR(e,t){return e===t||e===eg(t)}function bc(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 hR(e,t){return t?bc(e?.selected_model)===t||bc(e?.effective_model)===t:!1}function kD(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,o=typeof e.display_name=="string"?e.display_name.trim():"",r=lf.has(t)||!o||pR(o,e.model_id)||o.toLowerCase()==="unknown";return{name:lf.has(t)&&uR.has(e.model_id)?fR():r?eg(n):o,selector:n}}function SD(e,t,n=null){const o=e?.effective_model??e?.selected_model??null,r=n&&o?{...o,reasoning_effort:n}:o;return{identity:t??o,effort:r}}function ED(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function ID(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function AD(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 RD(e){const t=e?.effort_displacement,n=t?.note;if(typeof n!="string"||!n.trim())return null;const o=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||o.set(l,c)}if(!o.size)return n.trim();const r=[...o.keys()].sort((a,c)=>c.length-a.length).map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),i=new RegExp(`(^|[\\s(])(${r.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(i,(a,c,l)=>`${c}${o.get(l)}`)}function xD(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function mR(e){const t=e.trim();return t&&(tg(t)??t)}const df=new Map;function tg(e){const t=sn();let n=df.get(t);return n===void 0&&(n={auto:g("ui.chat.session_readout.effort.level.auto"),none:g("ui.chat.session_readout.effort.level.none"),minimal:g("ui.chat.session_readout.effort.level.minimal"),low:g("ui.chat.session_status.effort_level.low"),medium:g("ui.chat.session_status.effort_level.medium"),high:g("ui.chat.session_status.effort_level.high"),xhigh:g("ui.chat.session_readout.effort.level.xhigh"),max:g("ui.chat.session_readout.effort.level.max"),unknown:g("ui.chat.session_readout.effort.level.unknown"),reasoning:g("ui.chat.session_readout.effort.level.reasoning")},df.set(t,n)),n[e.toLowerCase()]}const _r=e=>mR(e).toLowerCase(),Ai=e=>{const t=tg(e.trim());return t===void 0?e:t.toLowerCase()};function ng(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 TD(e,t){const n=(e??t)?.effective_model;return ng(n)?null:n?.model_id??null}function CD(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(i=>typeof i=="string"):null,o=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",r=ng(e);return t?{label:t,adjustable:n===null||n.length>0,knownLadder:!!(n&&n.length>0),levelKnown:!0,detail:n&&n.length>0?g("ui.chat.session_readout.effort.detail.offers",{levels:Ni(n.map(_r))}):g("ui.chat.session_readout.effort.detail.session")}:n&&n.length>0?{label:"auto",adjustable:!0,knownLadder:!0,levelKnown:!0,detail:o?g("ui.chat.session_readout.effort.detail.auto_with_default",{default:_r(o),levels:Ni(n.map(_r))}):g("ui.chat.session_readout.effort.detail.auto",{levels:Ni(n.map(_r))})}:r?{label:"unknown",adjustable:!0,knownLadder:!1,levelKnown:!1,detail:g("ui.chat.session_readout.effort.detail.not_reported",{command:"/effort <level>"})}:n&&e.reasoning?{label:"reasoning",adjustable:!1,knownLadder:!0,levelKnown:!0,detail:g("ui.chat.session_readout.effort.detail.no_levels")}:n===null&&o?{label:o,adjustable:!1,knownLadder:!1,levelKnown:!0,detail:g("ui.chat.session_readout.effort.detail.default_only")}:null}function OD(e,t){if(!e)return null;if(!t||t.length===0||e.knownLadder)return e;const n=t.map(o=>typeof o=="object"&&o!==null&&"value"in o?String(o.value):"").filter(Boolean);return n.length===0?e:{...e,adjustable:!0,detail:g("ui.chat.session_readout.effort.detail.offers",{levels:Ni(n.map(_r))})}}function gR(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=ar(n.provider);if(!a)return null;const c=ar(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:ar(n.label)||a,effectiveState:d,owner:ar(n.owner_label)||ar(n.owner_device)||g("ui.chat.session_readout.access.owner_fallback"),observedAt:ya(n.observed_at),lastGrantAt:ya(n.last_grant_at),lastGrantExpiresAt:ya(n.last_grant_expires_at)}}if(!n||n.state!=="signed_out"&&n.state!=="temporarily_unavailable")return null;const o=typeof n.provider=="string"?n.provider:"";if(!o)return null;const r=e?.effective_model?.provider;if(r&&r!==o)return null;const i=typeof n.label=="string"&&n.label.trim()!==""?n.label:o;return n.state==="temporarily_unavailable"?{provider:o,label:i,state:n.state}:{provider:o,label:i}}function PD(e,t){if(!t)return;const n=e.find(o=>o.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function MD(e){return e&&e.draft!==!0?gR(e.frontend,e.servingLocality):null}function ar(e){return typeof e=="string"?e.trim():""}function ya(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function wa(e){return K_(new Date(e*1e3),{dateStyle:"medium",timeStyle:"short"})}function jD(e){const{label:t,effectiveState:n}=e,o=e.owner||g("ui.chat.session_readout.access.owner_fallback"),r={local:[g("ui.chat.session_readout.access.local.title",{label:t}),g("ui.chat.session_readout.access.local.description")],pending:[g("ui.chat.session_readout.access.pending.title",{label:t}),g("ui.chat.session_readout.access.pending.description")],eligible_borrow_unverified:[g("ui.chat.session_readout.access.eligible_borrow_unverified.title",{owner:o}),g("ui.chat.session_readout.access.eligible_borrow_unverified.description",{label:t,owner:o})],effective_borrow:[g("ui.chat.session_readout.access.effective_borrow.title",{label:t,owner:o}),g("ui.chat.session_readout.access.effective_borrow.description")],expired:[g("ui.chat.session_readout.access.expired.title",{label:t}),g("ui.chat.session_readout.access.expired.description",{owner:o})],withdrawn:[g("ui.chat.session_readout.access.withdrawn.title",{label:t}),g("ui.chat.session_readout.access.withdrawn.description")],owner_unavailable:[g("ui.chat.session_readout.access.owner_unavailable.title",{owner:o}),g("ui.chat.session_readout.access.owner_unavailable.description",{label:t,owner:o})],device_bound:[g("ui.chat.session_readout.access.device_bound.title",{label:t}),g("ui.chat.session_readout.access.device_bound.description")],absent:[g("ui.chat.session_readout.access.absent.title",{label:t}),e.connectHere===!0?g("ui.chat.session_readout.access.absent.description_connect"):g("ui.chat.session_readout.access.absent.description_remote")]},i=e.state==="temporarily_unavailable",[a,c]=n?r[n]:[i?g("ui.chat.session_status.temporarily_unavailable",{label:t}):g("ui.chat.session_status.not_signed_in",{label:t}),i?g("ui.chat.session_status.temporarily_unavailable_description"):g("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];n&&e.observedAt!==void 0&&l.push(g("ui.chat.session_readout.access.history.last_checked",{time:wa(e.observedAt)})),n&&e.lastGrantAt!==void 0&&l.push(g("ui.chat.session_readout.access.history.last_resolved",{time:wa(e.lastGrantAt)})),n&&e.lastGrantExpiresAt!==void 0&&l.push(g("ui.chat.session_readout.access.history.grant_expiry",{time:wa(e.lastGrantExpiresAt)}));const d=[...l];return n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push(g("ui.chat.session_readout.access.history.only")),{title:a,description:c,history:l.join(" "),historyLines:d,tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!i,canSwitchModel:n!=="effective_borrow"}}function $D(e){switch(e?.effectiveState){case"effective_borrow":case"pending":case"eligible_borrow_unverified":return!0;default:return!1}}function DD(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="not-cleared"||e.kind==="settled"&&e.canRetry}function ND(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function LD(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function _R(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function bR(e,t){return!!e.streams[t]}function og(e,t){return e.attached[t]?.turns.at(-1)}function FD(e,t){const n=og(e,t);return n?e.streams[n.asideId]:void 0}function UD(e,t){const n=e.attached[t]?.turns??[];for(let o=n.length-1;o>=0;o-=1){const r=n[o];if(r&&e.streams[r.asideId]?.settled)return r.asideId}}function vR(){return{text:"",streaming:!0,settled:!1,error:null}}function yR(e){return{text:e,streaming:!1,settled:!0,error:null}}function wR(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const kR=ri(e=>({streams:{},attached:{},attachAside:t=>e(n=>{const o=n.attached[t];return o&&o.notice===null?n:{attached:{...n.attached,[t]:o?{...o,notice:null}:{turns:[],notice:null}}}}),beginAsk:(t,n,o)=>e(r=>({streams:{...r.streams,[n]:vR()},attached:{...r.attached,[t]:{turns:[...r.attached[t]?.turns??[],{asideId:n,question:o}],notice:null}}})),applyAsideDelta:(t,n)=>e(o=>{const r=_R(o.streams[t],n);return r?{streams:{...o.streams,[t]:r}}:o}),settleAside:(t,n)=>e(o=>o.streams[t]?{streams:{...o.streams,[t]:yR(n)}}:o),failAside:(t,n)=>e(o=>bR(o,t)?{streams:{...o.streams,[t]:wR(o.streams[t],n)}}:o),setAsideNotice:(t,n)=>e(o=>{const r=o.attached[t];return r?{attached:{...o.attached,[t]:{...r,notice:n}}}:o}),queueAdoption:(t,n,o)=>e(r=>{const i=r.attached[t];return i?{attached:{...r.attached,[t]:{...i,notice:null,queued:{asideId:n,messageIds:[...o]}}}}:r}),unqueueAdoption:(t,n,o)=>e(r=>{const i=r.attached[t];if(i?.queued?.asideId!==n)return r;const{queued:a,...c}=i;return{attached:{...r.attached,[t]:{...c,notice:o}}}}),detachAside:t=>e(n=>{const o=n.attached[t],r={...n.attached};if(delete r[t],!o)return{attached:r};const i={...n.streams};for(const a of o.turns)delete i[a.asideId];return{streams:i,attached:r}})}));function BD(e,t){return og(e,t)?.asideId}const SR=4*1024*1024,uf=1024*1024,vc={pinned:!0},Ot=new Map,qt=new Map,ER=32;function ff(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function IR(e){const t=e.slice(-200),n=ff(t);if(n<=uf)return{records:t,bytes:n};let o=0,r=t.length,i=0;for(;r-o>1;){const a=Math.floor((o+r)/2),c=ff(t.slice(a));c>uf?o=a:(r=a,i=c)}return{records:t.slice(r),bytes:i}}function AR(e,t){const{records:n,bytes:o}=IR(BA(t.transcript).records);if(n.length===0){Ot.delete(e),qt.delete(e);return}const r={...t.transcript,records:n,index:new Map(n.map((a,c)=>[a.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},i={transcript:r,savedAt:Date.now(),bytes:o,owedLabels:pf(n,t.owedLabels),markLabels:pf(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>r.index.has(a))),scroll:RR(t.scroll??qt.get(e)??Ot.get(e)?.scroll??vc,r.index),busy:t.busy===!0};qt.delete(e),Ot.delete(e),Ot.set(e,i),TR()}function pf(e,t){if(!t||t.size===0)return hf;const n=new Set;for(const o of e)o.kind!=="tool"||o.args||o.toolCallId&&t.has(o.toolCallId)&&n.add(o.toolCallId);return n.size>0?n:hf}const hf=new Set;function RR(e,t){return e.pinned?vc:t.has(e.id)?e:vc}function rg(e){const t=Ot.get(e);if(!t)return null;const{bytes:n,...o}=t;return o}function xR(e){Ot.delete(e),qt.delete(e)}function HD(e,t){const n=Ot.get(e);if(n){n.scroll=t;return}for(qt.delete(e),qt.set(e,t);qt.size>ER;){const o=qt.keys().next().value;if(o===void 0)break;qt.delete(o)}}function TR(){let e=0;for(const t of Ot.values())e+=t.bytes;for(;e>SR&&Ot.size>0;){const t=Ot.keys().next().value;if(t===void 0)break;const n=Ot.get(t);Ot.delete(t),qt.delete(t),e-=n?.bytes??0}}const CR=8,OR=128,ig=new Set,PR="",ln=new Map,Ml=e=>e??PR;function WD(e){return ln.get(Ml(e))??ig}function GD(e,t,n){const o=Ml(e),r=ln.get(o)??new Set,i=new Set(r);if(n)for(i.delete(t),i.add(t);i.size>OR;){const a=i.values().next().value;if(a===void 0)break;i.delete(a)}else i.delete(t);for(ln.delete(o),i.size>0&&ln.set(o,i);ln.size>CR;){const a=ln.keys().next().value;if(a===void 0)break;ln.delete(a)}return ln.get(o)??ig}function MR(e){ln.delete(Ml(e))}const jR=128,fs=4096,ka=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),mf=e=>e.startsWith("qg:")&&e.length>3;function zD(e,t,n=null,o=[]){const r=new Map,i=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(r.has(u))return ka("duplicate-prior-id");if(r.size===fs)return ka("prior-id-limit");r.set(u,{ordinal:c,order:d})}l.eligible!==!1&&mf(l.key)&&t.has(l.key)&&i.size<jR&&i.set(c,l.key)}for(const c of o)if(!r.has(c)){if(r.size===fs)return ka("prior-id-limit");r.set(c,{ordinal:-1,order:-1})}const a=n===null?void 0:r.get(n);if(a!==void 0&&a.ordinal>=0){const c=e[a.ordinal];c.eligible!==!1&&mf(c.key)&&i.set(a.ordinal,c.key)}return{complete:!0,owners:r,keys:i,reason:null}}function KD(e,t,n={}){const o=f=>({episodes:[...t],reason:f});if(!e.complete)return o(e.reason??"incomplete-prior");if(e.owners.size>fs)return o("prior-id-limit");const r=new Set,i=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,h,_)=>{const y=a.get(f);y===void 0?a.set(f,{current:h,many:!1,lastOrder:_,reordered:!1,outside:!1}):(y.current!==h&&(y.many=!0),_<=y.lastOrder&&(y.reordered=!0),y.lastOrder=_)};for(let f=0;f<t.length;f+=1){const h=t[f];let _=null,y=!1;for(const b of h.segmentIds){if(i!==null){if(i.has(b))return o("duplicate-current-id");if(i.size===fs)return o("current-uniqueness-unproved");i.add(b)}const p=e.owners.get(b);if(p!==void 0){if(r.has(b))return o("duplicate-current-id");r.add(b),l(p.ordinal,f,p.order),_===null?_=p.ordinal:_!==p.ordinal&&(y=!0)}}if(h.eligible===!1||y||_===null||_<0)continue;const v=e.keys.get(_);v!==void 0&&c.set(f,{owner:_,key:v})}for(const f of n.outsideCurrentIds??[]){const h=e.owners.get(f);if(h===void 0||r.has(f))continue;const _=a.get(h.ordinal);_!==void 0&&(_.outside=!0)}for(const[f,h]of c){const _=a.get(h.owner),y=h.key.slice(3);(_===void 0||_.many||_.reordered||_.outside||!r.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 o("key-collision");u.add(h)}}return{episodes:t.map((f,h)=>{const _=c.get(h);return _===void 0?f:{...f,key:_.key}}),reason:null}}const $R=8,DR="",Yn=new Map,jl=e=>e??DR;function VD(e){return Yn.get(jl(e))??null}function ZD(e,t){const n=jl(e);for(Yn.delete(n),Yn.set(n,t);Yn.size>$R;){const o=Yn.keys().next().value;if(o===void 0)break;Yn.delete(o)}}function NR(e){Yn.delete(jl(e))}function LR(){let e=null;const t=async(n,o)=>{n.setLoading?.(!0);const r=n.getTranscript().orderRevision??0,i=()=>(n.getTranscript().orderRevision??0)===r;try{let a=o,c=await n.readPage(a);if(!n.isCurrent()||!i())return{kind:"stale"};if(c.cursor_missing){const u=bA(n.getTranscript()),f=u!==null&&u!==a?u:gA(c,a);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(a=f,c=await n.readPage(a),!n.isCurrent()||!i())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)!==r?u:Er(u,c,{...u.oldestId===o?{pagedBefore:a}:{},...n.peerSource?.()===!0?{peerSource:!0}:{}})));return(d.orderRevision??0)!==r||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,o){if(e!==null&&e.key===n)return e.promise;const r=o.getTranscript();if(!r.hasMore||!r.oldestId)return Promise.resolve({kind:"nothing-to-load"});const i={key:n,promise:t(o,r.oldestId)};e=i;const a=()=>{e===i&&(e=null)};return i.promise.then(a,a),i.promise}}}const FR={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"},UR={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function $l(e){return{kind:e,statement:g(FR[e]),action:UR[e]}}function gf(e){return $l(Vw(e))}const BR=()=>$l("historyUnreadable"),HR=new Set(["subagent_start","subagent_progress","subagent_end"]),WR=(e,t)=>({...e,[t]:(e[t]??0)+1}),GR=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const o=sg(n);o&&(t[o]=(t[o]??0)+1)}return t},sg=e=>{if(!e||typeof e!="object")return null;const t=e;return HR.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},zR=(e,t)=>{const n=sg(t);return n?WR(e,n):e};function _f(e,t,n){if(!n||!e)return{};const o=e.context_tokens;if(typeof o!="number"||!Number.isFinite(o)||o<=0)return{};const r=t.context_tokens;return typeof r=="number"&&Number.isFinite(r)&&r>=o?{}:{context_tokens:o,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 KR(e){for(const t of e)t.type==="aside_delta"&&kR.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function VR(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const zn=new Set,br=new Set;function ZR(e,t){let n=null;for(const o of t)e.has(o)&&(n=n??new Set(e),n.delete(o));return n??e}const YR=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),XR=15e3,yc=[500,1e3,2e3,4e3,8e3,8e3],JR=yc.length,QR=2e4,qR=1e4,ex=1e4;function bf(e){const t=Math.max(1,Math.min(e,yc.length));return yc[t-1]??8e3}const tx=3,nx=250,ox=32*1024,vf=512,yf=new Set(["turn_end","agent_end"]),rx=3,wf=2,ix=500,kf=Pl,sx=6,Sa=ih("sessions.history"),ax=2e3,Sf={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},to=new Map,Bi=new Map,cx=8,lx=2048,Ef=1024,dx=1024,ux="",Hn=new Map;function If(e){const t=e??ux,n=Hn.get(t);if(n)return Hn.delete(t),Hn.set(t,n),n;const o={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,o);Hn.size>cx;){const r=Hn.keys().next().value;if(r===void 0||r===t)break;Hn.delete(r)}return o}function Ea(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function fx(e,t){return e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0||e.paintBusy===!0?!0:t}function Ia(e,t,n,o){return t.has(n)?!1:e.inFlight.has(n)?!0:o}function px(e,t){return Bi.set(e,t),()=>{Bi.get(e)===t&&Bi.delete(e)}}function YD(e){const t=Bi.get(e);return t?(t(),!0):!1}const Qe=new Map,hx=4,mx=16;function ag(e,t){e(n=>Xm(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function gx(e,t,n){const o=e.index.get(t),r=o===void 0?void 0:e.records[o];if(o===void 0||!r||r.kind!=="user"||!r.local||r.text===n)return e;const i=e.records.slice(),{skill:a,...c}=r,l=Rs(n);return i[o]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:i}}function wc(e,t){let n=Qe.get(e);if(!n){if(Qe.size>=mx){const i=Qe.keys().next();i.done||Qe.delete(i.value)}n=new Map,Qe.set(e,n)}const o={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(o.id,o);n.size>hx;){const i=n.keys().next();if(i.done)break;n.delete(i.value)}const r=to.get(e);r&&ag(r,o)}function _x(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 kc(e,t){const n=Qe.get(e);n&&(n.delete(t),n.size===0&&Qe.delete(e))}function Sc(e,t){const n=Qe.get(e)?.get(t);n&&(n.settled=!0)}function Af(e,t){return e?Qe.get(e)?.has(t)===!0:!1}function XD(e){return e?(Qe.get(e)?.size??0)>0:!1}function bx(e,t,n){const o=Qe.get(e)?.get(t);if(!o)return;o.text=n;const r=to.get(e);r&&r(i=>gx(i,t,n))}function vx(e,t){if(e===t)return;const n=Qe.get(e);if(!n)return;Qe.delete(e);const o=Qe.get(t)??new Map;for(const[r,i]of n)i.identity=t,o.set(r,i);Qe.set(t,o)}function Ri(e){Qe.delete(e)}function yx(e,t){const n=Qe.get(e);if(n)for(const o of[...n.keys()]){const r=t.index.get(o),i=r===void 0?void 0:t.records[r];i?.kind==="user"&&i.local!==!0&&kc(e,o)}}function wx(e,t){to.set(e,t);const n=Qe.get(e);if(n)for(const o of n.values())ag(t,o);return()=>{to.get(e)===t&&to.delete(e)}}function kx(e,t){const n=Qe.get(e);if(!n)return t;let o=t;for(const r of n.values())o=Xm(o,r.id,r.text,r.images,void 0,r.documents);return o}function Sx(e,t,n,o=!0){return e===t||!o?!0:!n}function Ex(e,t){const n=to.get(e);if(!n)return kc(e,t),"queued";let o="queued";return n(r=>{const i=r.records[r.index.get(t)??-1];return!i||i.kind!=="user"?r:i.local?(o="retracted",Jm(r,t)):(o="owner",r)}),kc(e,t),o}function cg(e,t){const n=to.get(e);if(!n)return"unseen";let o="unseen";return n(r=>{const i=r.records[r.index.get(t)??-1];return!i||i.kind!=="user"||(o=i.local?"local":"owner"),r}),o}function Ix(e){const t=rg(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels,scroll:t.scroll,busy:t.busy}:{transcript:Ut,stale:!1,owedLabels:zn,markLabels:br,scroll:null,busy:!1}}function Ax(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(Ft(n))}function xi(e,t){for(const n of t)e.add(Ft(n))}const Rf=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function Ti(e,t,n){return n&&t&&_E(e.entries??[],t),e}function JD(e,t,n=!0,o=e,r={}){const i=r.openFrame===!0,a=r.journalOrder===!0,c=x.useRef(a);c.current=a;const l=x.useRef(i);l.current=i;const d=x.useRef(null),u=r.peerJournalSource===!0,f=x.useRef(u);f.current=u;const h=x.useRef(null),_=x.useRef(0),y=x.useRef(0),v=x.useRef(0),b=x.useRef(null),p=x.useRef(null),A=x.useCallback(()=>{if(!e||!c.current||!f.current)return!1;const $=Je.getState();return Tg($.sessions,$.placementFacts,e)},[e]),k=x.useCallback(()=>{const $=h.current;return A()&&$!==null&&$.sessionId===e&&$.peer},[A,e]),M=x.useCallback(()=>{const $=h.current;return $!==null&&$.sessionId===e&&$.peer},[e]),[P,W]=x.useState(()=>{const $=t&&e?Ix(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:o?kx(o,$?.transcript??Ut):Ut,stale:$?.stale??!1,paintScroll:$?.scroll??null,paintBusy:$?.busy??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:$?.owedLabels??zn,labelMarked:$?.markLabels??br,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),R=x.useRef(P),m=x.useCallback($=>{const J=$(R.current);return J===R.current||(R.current=J,W(J)),J},[]);x.useEffect(()=>W_(()=>{m($=>{const{failure:J}=$;if(!J?.kind)return $;const he=$l(J.kind);return he.statement===J.statement&&he.action===J.action?$:{...$,failure:he}})}),[m]);const w=x.useRef(e),S=x.useRef(n),T=x.useRef([]),N=x.useRef(Ut.index),Y=x.useRef(new Set),X=x.useRef(new Set),E=x.useRef(If(e)),V=x.useRef(new Set),G=x.useRef(null),me=x.useRef({}),z=x.useRef(null),ye=x.useRef(null),be=x.useRef(null),Ce=x.useRef(0),$e=x.useRef(0),_t=x.useRef(0);x.useEffect(()=>{if(!e||!t)return;const $=++$e.current,J=new WeakMap;let he=null;const Le=(te,oe)=>{const Se=J.get(te);if(Se===void 0||xt(oe)===Se.revision)return!1;const we=te.payload.history.journal_generation;return!(typeof we=="string"&&we.length>0&&we===oe.journalGeneration)};let Q=null,ht=!1,ze=0,Ee=0,Ke=0,U=0,Oe=0;const Fe=new Map;let Ve=0,Pe=0,Xe=!1;const Un=()=>{Ve&&(window.clearTimeout(Ve),Ve=0)},M_=te=>{for(const oe of te)E.current.attempts.set(oe,(E.current.attempts.get(oe)??0)+1)},Gs=te=>{m(oe=>{const Se=new Set;for(const Ue of oe.labelPending)oe.labelPending.has(Ue)&&(Ia(E.current,oe.transcript.argsByCall,Ue,Ea(oe))||Se.add(Ue));let we=null;for(const Ue of oe.labelMarked)Ia(E.current,oe.transcript.argsByCall,Ue,Ea(oe))||(we=we??new Set(oe.labelMarked),we.delete(Ue));if(Se.size===0&&!we)return oe;const ie=new Set(oe.labelPending);for(const Ue of Se)ie.delete(Ue);return{...oe,labelPending:ie.size?ie:zn,labelMarked:we&&we.size===0?br:we??oe.labelMarked}})},j_=te=>{m(oe=>{let Se=null,we=null;for(const ie of te)oe.labelPending.has(ie)&&(Se=Se??new Set(oe.labelPending),Se.delete(ie),we=we??new Set(oe.labelMarked),we.add(ie));return!Se||!we?oe:{...oe,labelPending:Se.size?Se:zn,labelMarked:we}})},ui=async(te,oe,Se=Sf,we=1,ie,Ue=oe,qe=null)=>{Ce.current+=1,$e.current===te&&m(Me=>Me.historyReadPending?Me:{...Me,historyReadPending:!0});for(const Me of Se.targets)E.current.inFlight.add(Me),V.current.add(Me);let pe=!1;try{pe=await $_(te,oe,Ue,qe,Se,we,ie)}finally{if(Ce.current=Math.max(0,Ce.current-1),Ce.current===0&&m(Me=>Me.historyReadPending?{...Me,historyReadPending:!1}:Me),!pe){for(const Me of Se.targets)E.current.inFlight.delete(Me);E.current.refused&&j_(Se.targets),Gs()}}},$_=async(te,oe,Se,we,ie,Ue,qe)=>{const pe={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:Se.size===0},Me=R.current.transcript.viewEpoch,at=await D_(te,oe,Se,we,ie,Ue,pe,qe);if(at||$e.current!==te||pe.reachedHeld||R.current.transcript.viewEpoch!==Me)return at;const It=oe!==Se&&[...oe].some(Nt=>Se.has(Nt));if(It&&pe.joined)return at;let tt;if(pe.oldest){if(!pe.hasMore)return at;tt={id:pe.oldest.id,ts:Math.round((pe.oldest.ts??0)*1e3)}}else{if(It||!we)return at;tt=we}if(!tt)return at;const Dt=m(Nt=>{const Lt=EA(Nt.transcript,tt,pe.keys);return Lt===Nt.transcript?Nt:{...Nt,transcript:Lt}});return N.current=Dt.transcript.index,at},D_=async(te,oe,Se,we,ie,Ue,qe,pe)=>{const Me=R.current.transcript.viewEpoch,at=()=>R.current.transcript.viewEpoch!==Me,It=new Set;let tt,Dt=0,Nt=0,Lt=!1,kn=Se.size===0,fo=!1;const er=R.current.cold,po=G.current,ho=po?{epoch:po.epoch,seq:po.seq}:null,At=new Set(ie.found),Bn=()=>LA(ie.order,ie.targets,At),zs=()=>Ym(ie.order,ie.targets,At),O=()=>{const ne=new Map;for(const Re of Ie){if(At.has(Re))continue;const Rt=Be.get(Re);Rt!==void 0&&ne.set(Re,Rt)}return ne},C=new Set(ie.every);for(const ne of At)C.add(ne);const Ie=new Set,Be=new Map;let vt=1;const Z=ie.targets.size>0;let mo=Math.max(of(Bn()),Z?E.current.depth:0),_e=0;for(;Dt<kf&&Nt<sx;){Nt+=1;let ne;const Re=ic(R.current.transcript),Rt=Re.revision;try{ne=await Ge({op:"sessions.history",sessionId:e,...tt?{beforeId:tt}:{},limit:Math.min(mo,kf-Dt),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Jt(R.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}}),Ti(ne,e,l.current)}catch{if(at())return!1;if(R.current.transcript.records.length>0){if(_e++>0)return E.current.refused=!0,!1;continue}return Ue<tx?(Oe=window.setTimeout(()=>{if(Oe=0,$e.current!==te||at()){Gs();return}ui(te,oe,ie,Ue+1,pe,Se,we)},bf(Ue)),!0):(m(Te=>({...Te,status:"unavailable",failure:BR(),heldFrontend:null,...Te.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{Gs()}if($e.current!==te||at())return!1;if(xt(R.current.transcript)!==Rt){if(!R.current.hydrated)continue;return!1}E.current.refused=!1;const Zt=ne.entries[0];Dt+=ne.entries.length,pe?.(ne.entries.length),Aa(Y.current,ne.entries),xi(X.current,ne.entries),m(Te=>{if(xt(Te.transcript)!==Rt)return Te;const Yt=Er(Te.transcript,ne,{authoritative:!0,orderRead:Re,peerSource:M(),readWitness:ho}),go=va(ne.entries,C),Vs=new Set(Te.labelPending);for(const F_ of go)Vs.delete(F_);return{...Te,hydrated:Te.hydrated||ne.entries.length>0||!er,labelPending:Vs.size?Vs:zn,labelMarked:ZR(Te.labelMarked,go),transcript:Yt}}),e&&tt===void 0&&Je.getState().resolveHeldFromServer(e,ne.entries,!ne.cursor_missing);const fi=Bn();for(const Te of va(ne.entries,C))At.add(Te),C.add(Te);if(jA(ne.entries)&&(fo=!0),Z){const Te=$A(ne.entries,C);for(const Yt of Te)Ie.add(Yt),C.add(Yt);for(const[Yt,go]of OA(ne.entries,Te))Be.set(Yt,go);for(const Yt of[...Ie])At.has(Yt)&&Ie.delete(Yt);Ie.size>0&&vt--<=0&&Ie.clear()}Lt=Lt||oe.size===0||ne.entries.some(Te=>oe.has(Ft(Te))||It.has(Te.id)),kn=kn||ne.entries.some(Te=>Se.has(Ft(Te)));for(const Te of ne.entries)It.add(Te.id);for(const Te of ne.entries)qe.keys.add(Ft(Te));Zt&&(qe.oldest=Zt),qe.hasMore=ne.has_more,qe.joined=Lt,qe.reachedHeld=kn;const Ks=Bn()+Ie.size;Z&&Bn()<fi&&(E.current.depth=Math.min(Pl,Math.max(E.current.depth,Dt)));let kd=!1;if(Z){const Te=zs();kd=PA(ne.entries,Te,ie.starts,O(),new Set(Te.filter(go=>ie.waiting.has(go))))||fo}if(DA(Lt&&kn,kd?0:Ks)||!Zt||!ne.has_more)return!1;tt=Zt.id,mo=Ks>0?of(Ks):_c}return!1},bd=()=>{if(ze&&cancelAnimationFrame(ze),Ee&&clearTimeout(Ee),ze=0,Ee=0,$e.current!==$)return;const te=T.current;if(T.current=[],te.length===0)return;const oe=new Set,Se=new Map;for(const O of Y.current)R.current.transcript.index.has(O)||Y.current.delete(O);for(const O of X.current)R.current.transcript.index.has(O)||X.current.delete(O);for(const O of R.current.transcript.records)Tl(O)&&!Y.current.has(O.id)&&(oe.add(O.id),Se.set(O.id,X.current.has(O.id)?O.ts:null));let we=null;for(const O of te){if(O.type!=="snapshot")continue;const C=O.payload.history,Ie=C.entries[0];if(!Ie||!C.has_more)continue;const Be=Math.round((Ie.ts??0)*1e3);Be>0&&(!we||Be<we.ts)&&(we={id:Ie.id,ts:Be})}KR(te);const ie=O=>{const C=O.payload.history.entries,Ie=C.at(-1);if(!Ie)return!1;if(Ax(O.payload)){if(oe.size===0)return!0;const Be=new Set;for(const vt of C)Be.add(Ft(vt));return C.some(vt=>oe.has(Ft(vt)))?!0:W0(O.payload.history,Se,Be)}return Ie.id===O.payload.frontend.snapshot.history_cursor?!1:oe.has(Ft(Ie))},Ue=O=>O!=null&&N.current.has(O);let qe=!1;const pe=K0(te.flatMap(O=>O.type==="frontend.update"?[O.payload]:[]),R.current.frontend?.jobs??[],R.current.transcript.records,O=>N.current.has(O)).filter(O=>(Fe.get(O)??0)<rx);for(const O of pe)Fe.set(O,(Fe.get(O)??0)+1);const Me=pe.length>0||te.some(O=>O.type==="attention"?!Ue(O.payload.anchor_id):O.type==="snapshot"&&!ie(O)),at=R.current.cold&&!R.current.hydrated&&te.some(O=>O.type==="snapshot"||O.type==="frontend.replace"||O.type==="frontend.update"?O.payload.cold===!1:!1),It=new Set(R.current.transcript.argsByCall.keys()),tt=[],Dt=new Set;for(const O of te){if(O.type!=="snapshot")continue;const C=Le(O,R.current.transcript);C||xi(X.current,O.payload.history.entries);for(const Ie of O.payload.history.entries){C||Dt.add(Ft(Ie));const Be=Ie.payload?.tool_calls;if(Array.isArray(Be))for(const vt of Be)vt&&typeof vt.id=="string"&&It.add(vt.id)}for(const Ie of O.payload.frontend.snapshot.live_events??[]){const Be=Ie.message;!C&&typeof Be?.id=="string"&&Dt.add(Be.id)}tt.push(...O.payload.frontend.snapshot.live_events??[])}if(pe.length>0)for(const O of R.current.transcript.index.keys())Dt.add(O);const Nt=te.some(O=>O.type==="event"&&yf.has(String(O.payload.type??""))),Lt=nf(E.current.attempts,tf(tt,It),It,wf),kn=Nt?nf(E.current.attempts,[...E.current.attempts.keys(),...E.current.settled],It,wf):[],fo=[];for(const O of te){if(O.type!=="event")continue;const C=O.payload;String(C.type??"")==="tool_execution_end"&&String(C.tool_call_id??"")&&fo.push(C)}const er=[];for(const O of fo){const C=String(O.tool_call_id??"");It.has(C)||E.current.settled.has(C)||er.push(C)}for(const O of er)E.current.settled.add(O);for(;E.current.settled.size>vf;){const O=E.current.settled.values().next().value;if(O===void 0)break;E.current.settled.delete(O)}for(const[O,C]of ef(fo))E.current.starts.set(O,C);for(;E.current.starts.size>Ef;){const O=E.current.starts.keys().next().value;if(O===void 0)break;E.current.starts.delete(O)}const po=E.current.settleRows<ix?er:[],ho=[...new Set([...Lt,...kn,...po])],At=ho.filter(O=>!E.current.painted.has(O));if(tt.length>0){E.current.order=tf(tt,new Set);for(const[O,C]of ef(tt))E.current.starts.set(O,C);for(;E.current.starts.size>Ef;){const O=E.current.starts.keys().next().value;if(O===void 0)break;E.current.starts.delete(O)}for(const O of TA(tt))E.current.waiting.add(O);for(const O of NA(tt))E.current.waiting.delete(O);for(;E.current.waiting.size>dx;){const O=E.current.waiting.values().next().value;if(O===void 0)break;E.current.waiting.delete(O)}}for(const O of[...E.current.attempts.keys()])It.has(O)&&E.current.attempts.delete(O);for(M_([...Lt,...kn]);E.current.attempts.size>vf;){const O=E.current.attempts.keys().next().value;if(O===void 0)break;E.current.attempts.delete(O)}if(performance.mark("lop:transcript:flush:start"),m(O=>{let C={...O},Ie=C.frontend!==null;qe=!1;let Be=null;const vt=Date.now();for(const Z of te){if(Z.type==="heartbeat")continue;if(Z.type==="gap"){he=null,C={...C,frontend:null,heldFrontend:C.frontend??C.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:rf(C.transcript)},Ie=!1;continue}if(Z.type==="open")he=null;else if("seq"in Z){const _e={epoch:Z.epoch,seq:Z.seq},ne=Rf(Z);if(!ne&&!zw(he,_e,{allowEqual:Z.type==="snapshot"}))continue;ne||(he=_e)}const mo=G.current;if((Z.type==="open"||"seq"in Z)&&!Rf(Z)&&(G.current={epoch:Z.epoch,seq:Z.seq},C={...C,receipt:G.current}),Z.type==="open"){if(C={...C,subscriptionId:Z.payload.subscription_id},Z.payload.gap){const _e=C.frontend??C.heldFrontend;C={...C,frontend:null,heldFrontend:_e,history:null,transcript:rf(C.transcript)},_e&&C.status==="live"&&(C={...C,status:"reconnecting"}),Ie=!1}continue}if(!Ie){if(Z.type==="event"&&(Be=gc(Be??C.transcript,Z.payload,vt,{frame:{epoch:Z.epoch,seq:Z.seq}})),Z.type==="snapshot"){const _e=J.get(Z),ne=Le(Z,C.transcript);ne&&(qe=!0);const Re=Z.payload,Rt=!Re.history.cursor_missing&&!ne;let Zt=Be??C.transcript;Rt&&(performance.mark("lop:open:history:start"),Ti(Re.history,d.current,d.current!==null),Zt=Er(Zt,Re.history,{authoritative:!0,orderRead:_e,peerSource:M(),readWitness:{epoch:Z.epoch,seq:Z.seq}}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),Aa(Y.current,Re.history.entries),xi(X.current,Re.history.entries)),e&&Je.getState().resolveHeldFromServer(e,Re.history.entries,Rt),performance.mark("lop:open:seed:start"),Zt=xA(Zt,Re.frontend.snapshot,vt,{epoch:Z.epoch,seq:Z.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const fi=_f(C.frontend??C.heldFrontend,Re.frontend.snapshot,Re.cold===!0||Re.attaching===!0);C={...C,contextCarried:Object.keys(fi).length>0,subagentPulses:GR(Re.frontend.snapshot.live_events),status:"live",stale:!1,paintBusy:!1,paintScroll:null,frontend:{...Re.frontend.snapshot,...fi,attention:Co(C.frontend?.attention,Re.frontend.snapshot.attention,e)},history:ne?C.history:Re.history,cold:Re.cold,ownerEpoch:Re.frontend.epoch,failure:null,hydrated:C.hydrated||Rt&&Re.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:Zt},Ie=!0,Be=null}continue}if(Z.type==="attention"){C.frontend&&(C={...C,frontend:{...C.frontend,attention:Co(C.frontend.attention,Z.payload,e)}});continue}if(Z.type==="frontend.update"){const _e=Z.payload,ne=_e.changes??{};if((_e.degraded===!0||_e.paused===!0)&&(C={...C,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!C.frontend)continue;const Re=_e.epoch!==C.ownerEpoch&&ne.epoch===_e.epoch,Rt=_e.changes!==void 0&&ne.epoch===_e.epoch;(Re||_e.epoch===C.ownerEpoch&&(C.frontend.sequence<_e.sequence||C.frontend.sequence===_e.sequence&&Rt))&&(C={...C,contextCarried:!1,ownerEpoch:Re?_e.epoch:C.ownerEpoch,frontend:{...C.frontend,...ne,...ne.jobs==null&&_e.job_deltas?{jobs:gh(C.frontend.jobs??[],_e.job_deltas)}:{},attention:Co(C.frontend.attention,ne.attention,e),sequence:_e.sequence},...typeof _e.cold=="boolean"?{cold:_e.cold}:{}},Rt&&C.liveUpdatesNotice==="update"&&C.liveUpdatesPaused&&(C={...C,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(Z.type==="frontend.replace"){if(C.frontend&&Kw(mo,e,Z)){const _e=Z.payload.frontend,ne=_f(C.frontend,_e.snapshot,Z.payload.cold===!0);C={...C,contextCarried:Object.keys(ne).length>0,frontend:{..._e.snapshot,...ne,attention:Co(C.frontend.attention,_e.snapshot.attention,e)},ownerEpoch:_e.epoch,cold:Z.payload.cold,...C.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(Z.type==="event"){const _e=String(Z.payload.type??"");if(Z.payload.action==="reload"){C={...C,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}YR.has(_e)&&(C={...C,terminal:_e}),yf.has(_e)&&(C={...C,turnsCompleted:C.turnsCompleted+1});const ne=gc(C.transcript,Z.payload,vt,{frame:{epoch:Z.epoch,seq:Z.seq},userStoppedAt:e?Je.getState().stoppedTurns[e]??null:null,queuedAskEngine:Hm(C.frontend)});ne!==C.transcript&&(C={...C,transcript:ne});const Re=zR(C.subagentPulses,Z.payload);Re!==C.subagentPulses&&(C={...C,subagentPulses:Re})}}if(!Ie&&Be){for(const Z of Be.index.keys())C.transcript.index.has(Z)||Y.current.add(Z);C={...C,transcript:Be}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),N.current=C.transcript.index,!VR(te))return O;if(At.length>0){const Z=new Set(C.labelPending);for(const mo of At)Z.add(mo);C={...C,labelPending:Z}}return C.frontend!==null&&C.frontend!==C.heldFrontend&&(C={...C,heldFrontend:C.frontend}),C}),At.length>0){for(const O of At)E.current.painted.add(O);for(;E.current.painted.size>lx;){const O=E.current.painted.values().next().value;if(O===void 0)break;E.current.painted.delete(O)}}const Bn=Me||qe,zs=po.length>0&&Lt.length===0&&kn.length===0&&!Bn&&!at;if(Bn||ho.length>0||at){const O=new Set(ho),C=E.current.order;ui($,Dt,ho.length>0?{targets:O,order:C,starts:E.current.starts,waiting:E.current.waiting,every:new Set([...C,...O]),found:new Set(va(te.flatMap(Ie=>Ie.type==="snapshot"?Ie.payload.history.entries:[]),new Set(C))),pending:At}:Sf,1,zs?Ie=>{E.current.settleRows+=Ie}:void 0,oe,we)}if($0())for(const O of te)"epoch"in O&&"seq"in O&&D0({carrier:"canonical-sse",sessionId:e,epoch:O.epoch,seq:O.seq,disposition:"processed"})},Qo=()=>{const te=Q;if(Q=null,h.current=null,_.current+=1,y.current&&(window.clearTimeout(y.current),y.current=0),v.current+=1,!!te){ht=!0;try{te()}finally{ht=!1}}},qo=()=>{const te=ic(R.current.transcript),oe=Uo.currentToken(),Se=++_t.current;Un(),Ve=window.setTimeout(()=>{Ve=0,$e.current===$&&(Qo(),m(ie=>({...ie,subscriptionId:null,status:"unavailable",failure:gf(kr.ended),...ie.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Xe&&(Xe=!0,Pe=window.setTimeout(()=>{Pe=0,$e.current===$&&yd()},qR)))},QR);const we=A();d.current=l.current?e??null:null,Q=h0({sessionId:e,epoch:me.current.epoch,afterSeq:me.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:Jt(R.current.transcript).slice(0,512),...we?{peerJournalSource:!0}:{}}:{}},ie=>{if($e.current===$&&_t.current===Se){if(ie.kind==="error"||ie.kind==="end"){if(ht)return;if(Un(),Qo(),ie.kind==="error"&&ie.status===404){if(!n){e&&Je.getState().retireDraftWarm(e),m(pe=>({...pe,subscriptionId:null}));return}e&&(xR(e),MR(e),NR(e),Je.getState().retireDraftsForSession(e)),m(pe=>({...pe,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...pe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),e&&Je.getState().temporaryChats&&Ge({op:"sessions.get",sessionId:e}).catch(pe=>{$e.current===$&&(!(pe instanceof Ae)||!XA(pe.code)||m(Me=>Me.missing?{...Me,temporaryDeleted:!0}:Me))});return}const Ue=ie.kind==="error"?ie.detail??g("ui.common.errors.event_stream_failed"):g("ui.common.errors.event_stream_closed");if(m(pe=>({...pe,subscriptionId:null})),Ke>=JR){m(pe=>({...pe,status:"unavailable",failure:gf(Ue),...pe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}Ke+=1;const qe=G.current;qe&&(me.current={epoch:qe.epoch,afterSeq:qe.seq}),m(pe=>pe.status==="unavailable"&&Ke>1?pe:{...pe,status:"reconnecting",failure:null}),U=window.setTimeout(()=>{U=0,$e.current===$&&qo()},bf(Ke));return}if(ie.data!==void 0)try{const Ue=ie.data,qe=ie.receipt?performance.now():0,pe=Ue.length>=ox;pe&&performance.mark("lop:open:parse:start");const Me=JSON.parse(Ue),at=ie.receipt?performance.now():0;Me.type==="snapshot"&&J.set(Me,te),pe&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),Me.type==="snapshot"&&(ie.receipt&&console.warn(Qw(ie.receipt,oe,qe,at)),Uo.note(e,"snapshot",oe),Ke=0,Un(),Xe=!1),T.current.push(Me),ze||(ze=requestAnimationFrame(bd)),Ee||(Ee=window.setTimeout(bd,nx))}catch{}}},ie=>{ie==="requested"&&Uo.note(e,"request",oe)}),h.current={sessionId:e,peer:we},_.current+=1},vd=()=>{U!==0&&(window.clearTimeout(U),U=0),me.current={},G.current=null,Qo(),qo()},yd=()=>{Ke=0,Pe&&(window.clearTimeout(Pe),Pe=0),U&&(window.clearTimeout(U),U=0),Oe&&(window.clearTimeout(Oe),Oe=0),m(te=>({...te,failure:null,status:te.status==="unavailable"?"connecting":te.status,transcript:Ii(te.transcript,!1)})),R.current.hydrated||ui($,new Set(R.current.transcript.index.keys())),!Q&&qo()};qo(),z.current=yd,ye.current=()=>{R.current.liveUpdatesReloading||(m(te=>({...te,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Ke=0,U&&(window.clearTimeout(U),U=0),Pe&&(window.clearTimeout(Pe),Pe=0),vd())},be.current=()=>{!R.current.hydrated&&Ce.current===0&&ui($,new Set(R.current.transcript.index.keys()))};const N_=px(e,vd),wd=()=>{if(!t||!e||b.current===e)return;const te=h.current;te===null||te.sessionId!==e||te.peer||A()&&(b.current=e,Qo(),qo())};p.current=wd;const L_=Je.subscribe(()=>{wd()});return()=>{$e.current+=1,z.current=null,be.current=null,ye.current=null,p.current=null,L_(),y.current&&(window.clearTimeout(y.current),y.current=0),N_(),Qo(),ze&&cancelAnimationFrame(ze),Ee&&clearTimeout(Ee),U&&clearTimeout(U),Oe&&clearTimeout(Oe),le.current&&(window.clearTimeout(le.current),le.current=0),ke.current&&(window.clearTimeout(ke.current),ke.current=0),Pe&&window.clearTimeout(Pe),Un(),T.current=[]}},[m,e,t,n,a,A,k,M]),x.useEffect(()=>{!e||!t||p.current?.()},[e,t,u]),x.useEffect(()=>{me.current={},G.current=null,N.current=Ut.index;const $=Sx(w.current,e,n,S.current);w.current=e,S.current=n;const J=e?rg(e):null;N.current=$?R.current.transcript.index:(J?.transcript??Ut).index;const he=new Set($?Y.current:[]);for(const Q of J?.replayBorn??[])he.add(Q);const Le=$?R.current.transcript.index:(J?.transcript??Ut).index;for(const Q of he)Le.has(Q)||he.delete(Q);Y.current=he,$||(X.current=new Set),m(Q=>({...Q,frontend:null,heldFrontend:$?Q.heldFrontend:null,contextCarried:$?Q.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:$?Q.turnsCompleted:0,transcript:$?Q.transcript:J?.transcript??Ut,stale:$?Q.stale:J!==null,paintScroll:$?null:J?.scroll??null,paintBusy:$?Q.paintBusy:J?.busy===!0,missing:$?Q.missing:!1,temporaryDeleted:$?Q.temporaryDeleted:void 0,status:"connecting",subagentPulses:{},labelPending:J?.owedLabels??zn,labelMarked:J?.markLabels??br,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),E.current=If(e)},[e,n]);const jt=x.useRef(o);jt.current=o,x.useEffect(()=>{if(e)return()=>{const $=R.current.transcript;$.records.length>0&&AR(e,{transcript:$,owedLabels:new Set([...R.current.labelPending].filter(J=>Ia(E.current,R.current.transcript.argsByCall,J,Ea(R.current)))),markLabels:new Set(R.current.labelMarked),replayBorn:new Set(Y.current),busy:fx(R.current,_x(jt.current)!==null)});for(const J of V.current)E.current.inFlight.delete(J);V.current.clear()}},[e]);const le=x.useRef(0);x.useEffect(()=>{if(P.labelPending.size===0&&P.labelMarked.size===0){le.current&&(window.clearTimeout(le.current),le.current=0);return}if(le.current)return;const $=()=>{le.current=0;const J=R.current.labelPending,he=R.current.labelMarked;if(J.size===0&&he.size===0)return;const Le=E.current;for(const Q of J)if(Le.inFlight.has(Q)){le.current=window.setTimeout($,Sa);return}for(const Q of he)if(Le.inFlight.has(Q)){le.current=window.setTimeout($,Sa);return}m(Q=>Q.labelPending.size===0&&Q.labelMarked.size===0?Q:{...Q,labelPending:zn,labelMarked:br})};le.current=window.setTimeout($,Sa)},[m,P.labelPending,P.labelMarked]);const ke=x.useRef(0);x.useEffect(()=>{if(P.labelPending.size===0){ke.current&&(window.clearTimeout(ke.current),ke.current=0),m($=>$.labelHoldLate?{...$,labelHoldLate:!1}:$);return}P.labelHoldLate||ke.current||(ke.current=window.setTimeout(()=>{ke.current=0,m($=>$.labelPending.size===0||$.labelHoldLate?$:{...$,labelHoldLate:!0})},ax))},[m,P.labelPending,P.labelHoldLate]);const et=x.useRef(e);et.current=e;const Ne=x.useRef({id:e,epoch:0});Ne.current.id!==e&&(Ne.current={id:e,epoch:Ne.current.epoch+1});const Et=x.useRef(null);Et.current===null&&(Et.current=LR());const ge=x.useRef(!1),xe=x.useRef(null),[pt,$t]=x.useState(0);x.useEffect(()=>{const $=P.transcript,J=Jt($);if(!e||!a||!$.orderNeedsReconcile&&(!$.journalGeneration||J.length===0)||ge.current)return;const he=U=>({fields:JSON.stringify([pt,e,U.viewEpoch,xt(U),U.orderNeedsReconcile,U.orderWantedGeneration,Jt(U)]),demand:U.orderDemand}),Le=he($);if(xe.current?.fields===Le.fields&&xe.current.demand===Le.demand)return;xe.current=Le;const Q=e,ht=$.viewEpoch;ge.current=!0;let ze=null,Ee=$;const Ke=U=>{if(!U.peer||et.current!==Q||R.current.transcript.viewEpoch!==ht||_.current!==U.streamEpoch)return;const Oe=U.kind==="authority"?U.frame.payload.history:U.page,Fe=Oe.journal_order_state;if(Fe==="ready"){y.current&&(window.clearTimeout(y.current),y.current=0),m(Pe=>{const Xe=Ii(Pe.transcript,!1);return Xe===Pe.transcript?Pe:{...Pe,transcript:Xe}});return}if(Fe==="unavailable"){if(y.current&&(window.clearTimeout(y.current),y.current=0),Oe.reconcile===!0)return;m(Pe=>{const Xe=Ii(Pe.transcript,!0);return Xe===Pe.transcript?Pe:{...Pe,transcript:Xe}});return}if(Fe!=="building")return;y.current&&(window.clearTimeout(y.current),y.current=0);const Ve=++v.current;y.current=window.setTimeout(()=>{y.current=0,v.current===Ve&&et.current===Q&&R.current.transcript.viewEpoch===ht&&_.current===U.streamEpoch&&m(Pe=>{const Xe=Ii(Pe.transcript,!0);return Xe===Pe.transcript?Pe:{...Pe,transcript:Xe}})},ex)};B0({getTranscript:()=>R.current.transcript,isCurrent:()=>et.current===Q&&R.current.transcript.viewEpoch===ht,sweep:(U,Oe)=>{if(!k())return;if(U.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${Q}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const Fe=U.journalGeneration;if(typeof Fe!="string"||Fe.length===0)return{kind:"none",path:`/v1/desktop/sessions/${Q}/history`,query:new URLSearchParams};if(Eh(U,Oe?.("lookup")).length>0){const Xe=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:Fe});return{kind:"lookup",path:`/v1/desktop/sessions/${Q}/history`,query:Xe}}if(ll(U).length>0){const Xe=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:Fe});return{kind:"payload",path:`/v1/desktop/sessions/${Q}/history`,query:Xe}}return{kind:"none",path:`/v1/desktop/sessions/${Q}/history`,query:new URLSearchParams}},read:async(U,Oe)=>{Ee=R.current.transcript,xe.current=he(Ee);const Fe=k(),Ve=_.current;if(Oe==="lookup"||Oe==="payload"){const Xe=R.current.transcript.journalGeneration,Un=await Ge({op:"sessions.history",sessionId:Q,limit:100,journalOrder:!0,orderIds:U,peerJournalSource:!0,sourceRead:Oe==="payload"?"payload":"metadata",...typeof Xe=="string"&&Xe.length>0?{expectedJournalGeneration:Xe}:{}});return Oe==="payload"?{kind:"payload",page:Un,peer:Fe,streamEpoch:Ve}:{kind:"lookup",page:Un,peer:Fe,streamEpoch:Ve}}return{kind:"authority",frame:await Ge({op:"sessions.get",sessionId:Q,journalOrder:!0,orderIds:U,...Fe?{peerJournalSource:!0}:{}}),peer:Fe,streamEpoch:Ve}},page:U=>U.kind==="authority"?U.frame.payload.history:U.page,lookupPath:`/v1/desktop/sessions/${Q}`,commit:(U,Oe,Fe)=>{U.peer&&_.current!==U.streamEpoch||(m(Ve=>et.current!==Q||xt(Ve.transcript)!==Oe||Ve.transcript.viewEpoch!==ht?Ve:{...Ve,transcript:U.kind==="authority"?U.peer?qu(Ve.transcript,U.frame.payload.history,{authoritative:!0,orderRead:Fe}):wA(Ve.transcript,U.frame.payload.history,Fe):U.kind==="payload"?kA(Ve.transcript,U.page,Fe,Oe):qu(Ve.transcript,U.page,{authoritative:!1})}),Ke(U))}}).then(U=>{ze=U.kind==="complete"?U.transcript:null}).catch(U=>{console.warn("[canonical] source-order reconcile refused",U)}).finally(()=>{ge.current=!1;const U=R.current.transcript,Oe=ze??Ee;ze&&et.current===Q&&U.viewEpoch===ht&&!U.orderNeedsReconcile&&(xe.current=he(Oe)),(et.current!==Q||U.viewEpoch!==ht||xt(U)!==xt(Oe)||U.orderWantedGeneration!==Oe.orderWantedGeneration||U.orderNeedsReconcile!==Oe.orderNeedsReconcile||U.orderDemand!==Oe.orderDemand||JSON.stringify(Jt(U))!==JSON.stringify(Jt(Oe)))&&$t(Fe=>Fe+1)})},[m,e,a,k,P.transcript,pt]);const bt=x.useCallback(async()=>{const $=Et.current;if(!e||!$)return{kind:"nothing-to-load"};const J=e,he=Ne.current.epoch,Le=()=>Ne.current.epoch===he,Q=R.current.transcript.viewEpoch,ht=()=>R.current.transcript.viewEpoch===Q,ze=await $.load(`${J}#${he}`,{getTranscript:()=>R.current.transcript,readPage:Ee=>{const Ke=l.current;return Ge({op:"sessions.history",sessionId:J,beforeId:Ee,limit:100,openFrame:Ke,...c.current?{journalOrder:!0,orderIds:Jt(R.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}}).then(U=>Ti(U,J,Ke))},isCurrent:()=>Le()&&ht(),commit:Ee=>m(Ke=>{const U=Ee(Ke.transcript);return U===Ke.transcript?Ke:{...Ke,transcript:U}}).transcript,setLoading:Ee=>{Le()&&m(Ke=>Ke.loadingOlder===Ee?Ke:{...Ke,loadingOlder:Ee})},peerSource:M});return Le()&&(ze.kind==="failed"?m(Ee=>Ee.olderFailed?Ee:{...Ee,olderFailed:!0}):ze.kind==="applied"&&m(Ee=>Ee.olderFailed?{...Ee,olderFailed:!1}:Ee)),ze},[m,e,k,M]),Jo=x.useCallback(async()=>(await bt()).kind==="applied",[bt]),Fn=x.useRef(!1),dd=x.useCallback(async($,J)=>{if(!e||Fn.current)return!1;const he=e;Fn.current=!0;const Le=xt(R.current.transcript),Q=G.current,ht=Q?{epoch:Q.epoch,seq:Q.seq}:null;try{const ze=await Ge({op:"sessions.history",sessionId:he,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Jt(R.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}});return Ti(ze,he,l.current),et.current!==he||xt(R.current.transcript)!==Le||R.current.transcript.viewEpoch!==J?!1:(m(Ee=>xt(Ee.transcript)!==Le?Ee:{...Ee,transcript:Er(Ee.transcript,ze,{keepPaging:!0,peerSource:M(),readWitness:ht})}),Aa(Y.current,ze.entries),xi(X.current,ze.entries),qA(ze.entries,$))}catch{return!1}finally{Fn.current=!1}},[m,e,k,M]);x.useEffect(()=>o?wx(o,J=>{m(he=>{const Le=J(he.transcript);return Le===he.transcript?he:{...he,transcript:Le}})}):void 0,[m,o]),x.useEffect(()=>{o&&yx(o,P.transcript)},[o,P.transcript]);const ud=x.useCallback(()=>{m($=>({...$,transcript:FA($.transcript),olderFailed:!1,heldFrontend:null}))},[m]),fd=x.useCallback(()=>{z.current?.()},[]),pd=x.useCallback(()=>{ye.current?.()},[]),hd=x.useCallback(()=>{be.current?.()},[]),md=x.useCallback(($,J="info")=>{m(he=>({...he,transcript:HA(he.transcript,$,J)}))},[m]),gd=x.useCallback($=>{m(J=>({...J,pendingModel:$}))},[m]),_d=x.useCallback(()=>{m($=>$.pendingModel===null?$:{...$,pendingModel:null})},[m]);return x.useEffect(()=>{const $=P.pendingModel;if(!$)return;const J=bc($);if(!J)return;const he=P.frontend;hR(he,J)&&m(Le=>({...Le,pendingModel:null}))},[m,P.frontend,P.pendingModel]),x.useEffect(()=>{if(!P.pendingModel)return;const $=window.setTimeout(()=>m(J=>({...J,pendingModel:null})),XR);return()=>window.clearTimeout($)},[m,P.pendingModel]),x.useMemo(()=>({...P,awaitingHydration:t&&!!e&&n&&!P.hydrated,loadOlder:Jo,loadOlderDetailed:bt,refreshTail:dd,clearView:ud,addNote:md,paintPendingModel:gd,clearPendingModel:_d,retry:fd,rehydrate:hd,reloadFromHistory:pd}),[P,t,e,n,Jo,bt,dd,ud,md,gd,_d,fd,hd,pd])}function Ps(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
|
|
41
|
+
|
|
42
|
+
`)?e:`${t}
|
|
43
|
+
|
|
44
|
+
${e}`}const Ra={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function Hi(e,t,n){const o=[...e.attachments??[]],r=[],i=[],a=new Set;for(const h of t.attachments){const _=o.find(v=>v.path===h&&!a.has(v.id));if(_){a.add(_.id),i.push(_.id);continue}const y={id:n(),path:h};r.push(y),i.push(y.id)}const c=[...e.replies??[]],l=t.replies.filter(h=>!c.some(_=>_.id===h.id)),d=t.text,u=[...r,...o],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:Ps(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:i,replyIds:t.replies.map(h=>f.find(_=>_.id===h.id)?.id).filter(h=>h!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function Rx(e,t){const n=e.lateDeliveredText??e.returned?.text;if(!n||t.includes(n))return!0;const o=Math.max(8,Math.min(24,Math.floor(n.length/3)));for(let r=0;r+o<=n.length;r++)if(t.includes(n.slice(r,r+o)))return!0;return!1}function xx(e){return{text:Ps(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function Tx(e,t){if(!e||!t)return!1;const n=xx(e),o=e.attachments??[],r=e.replies??[];return n.text.trim()===t.text.trim()&&o.length===t.chipIds.length&&o.every((i,a)=>i.id===t.chipIds[a])&&r.length===t.replyIds.length&&r.every((i,a)=>i.id===t.replyIds[a])}function Cx(e,t=()=>crypto.randomUUID()){const n={};for(const[o,r]of Object.entries(e??{}))n[o]=r.inFlight?Hi(r,r.inFlight,t):r;return n}function Ox(e,t){const n=t.text,o=Ps(e.currentInput??"",e.pendingText??"");let r=o,i="overlap";n===""?i="draft-only":o.startsWith(n)&&(r=o.slice(n.length).replace(/^\n+/,""),i="draft-only");const a=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:r,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:i}}const Px=300,lg="conversation-input-store";let Yr=null,dg=lg,yt=null,xa=!1;const Ec=()=>{try{return globalThis.localStorage??null}catch{return null}},Ir=()=>{yt!==null&&(clearTimeout(yt),yt=null);const e=Yr;if(!e)return;const t=dg,n=Ec();if(n){try{n.setItem(t,JSON.stringify(e))}catch(o){xa||(xa=!0,console.warn("[composer] the draft could not be persisted; it stays in memory for this session",o));return}Yr=null,xa=!1}},QD=()=>{Ir()},qD=()=>{Yr=null,yt!==null&&(clearTimeout(yt),yt=null)},Mx={getItem:e=>{const t=Ec();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)=>{Yr=t,dg=e,yt!==null&&clearTimeout(yt),yt=setTimeout(()=>{yt=null,Ir()},Px)},removeItem:e=>{Yr=null,yt!==null&&(clearTimeout(yt),yt=null),Ec()?.removeItem(e)}};typeof window<"u"&&typeof window.addEventListener=="function"&&(window.addEventListener("pagehide",Ir),window.addEventListener("beforeunload",Ir),window.document?.addEventListener("visibilitychange",()=>{window.document.visibilityState==="hidden"&&Ir()}));const lt=ri()(Is((e,t)=>({inputByConversation:{},addReply:(n,o)=>{const r=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(r.replies)?r.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:[...i,o]}}})},removeReply:(n,o)=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:r.replies.filter(i=>i.id!==o)}}})},clearReplies:n=>{const o=t().inputByConversation[n];o&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,replies:[]}}})},addAttachment:(n,o)=>{const r=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(r.attachments)?r.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[...i,o]}}})},removeAttachment:(n,o)=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:r.attachments.filter(i=>i.id!==o)}}})},clearAttachments:n=>{const o=t().inputByConversation[n];o&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,attachments:[]}}})},setCurrentInput:(n,o,r=0)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...i,lateDelivered:i.lateDelivered==="overlap"&&!Rx(i,o)?void 0:i.lateDelivered,currentInput:o,unredactedChars:o?r:0}}})},getUnredactedChars:n=>t().inputByConversation[n]?.unredactedChars||0,getCurrentInput:n=>t().inputByConversation[n]?.currentInput||"",addSubmittedMessage:(n,o)=>{const r=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=r.submittedMessages[r.submittedMessages.length-1],a=o&&o!==i?[...r.submittedMessages.slice(-19),o]:r.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...r,submittedMessages:a}}})},getSubmittedMessages:n=>t().inputByConversation[n]?.submittedMessages||[],clearSubmittedMessages:n=>{const o=t().inputByConversation[n];o&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,submittedMessages:[]}}})},getCurrentHistoryIndex:n=>t().inputByConversation[n]?.currentHistoryIndex??null,setCurrentHistoryIndex:(n,o)=>{const r=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=r.submittedMessages;let a=null;typeof o=="number"&&i.length>0&&(a=Math.max(0,Math.min(o,i.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentHistoryIndex:a}}})},resetCurrentHistoryIndex:n=>{const o=t().inputByConversation[n];o&&(o.currentHistoryIndex??null)!==null&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,currentHistoryIndex:null}}})},clearAll:n=>{const{[n]:o,...r}=t().inputByConversation;e({inputByConversation:r})},restoreRow:(n,o)=>{e({inputByConversation:{...t().inputByConversation,[n]:{...o,textRevision:(o.textRevision??0)+1}}})},beginInFlight:(n,o,r=!0)=>{const i=t().inputByConversation[n]??Ra,a=new Set(o.attachments.map(d=>d.id)),c=new Set(o.replies.map(d=>d.id)),l=i.currentInput===o.text;e({inputByConversation:{...t().inputByConversation,[n]:{...i,currentInput:l?"":i.currentInput,unredactedChars:l?0:i.unredactedChars,textRevision:l?(i.textRevision??0)+1:i.textRevision,attachments:(i.attachments??[]).filter(d=>!a.has(d.id)),replies:(i.replies??[]).filter(d=>!c.has(d.id)),inFlight:r?{text:o.text,attachments:o.attachments.map(d=>d.path),replies:[...o.replies],unredactedChars:l?i.unredactedChars:0,volatileText:o.volatileText}:i.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const o={...t().inputByConversation};let r=!1;for(const i of n){const a=o[i];!a||!a.inFlight&&!a.returned||(o[i]={...a,inFlight:void 0,returned:void 0},r=!0)}r&&e({inputByConversation:o})},returnInFlight:(n,o)=>{const r={...t().inputByConversation},i=r[n],a=i?.inFlight??r[o]?.inFlight;let c=r[o]??Ra;n!==o&&i&&(c=Hi(c,{text:i.currentInput??"",attachments:(i.attachments??[]).map(l=>l.path),replies:i.replies??[],unredactedChars:i.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:r[o]?.returned},delete r[n]),a&&(c=Hi(c,a,()=>crypto.randomUUID())),!(!a&&n===o)&&(r[o]=c,e({inputByConversation:r}))},adoptReturnedText:n=>{const o=t().inputByConversation[n];if(o?.pendingText===void 0)return null;const r=Ps(o.currentInput??"",o.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...o,currentInput:r,pendingText:void 0,textRevision:(o.textRevision??0)+1}}}),r},returnPayload:(n,o)=>{const r=t().inputByConversation[n]??Ra;r.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:Hi(r,o,()=>crypto.randomUUID())}})},reconcileDelivered:n=>{const o=t().inputByConversation[n];if(!o)return;const r=f=>(f.currentInput??"")===""&&(f.attachments??[]).length===0&&(f.replies??[]).length===0,i=o.returned!==void 0||o.inFlight!==void 0,a=o.returned?Tx(o,o.returned):r(o),c=o.returned?Ox(o,o.returned):null,l={...o,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,volatilePendingText:void 0,textRevision:(o.textRevision??0)+1},d=(c?.row.currentInput??"")==="",u=c&&!r(c.row)?{...c.row,returned:void 0,inFlight:void 0,volatilePendingText:d?void 0:o.volatilePendingText,lateDelivered:c.box==="overlap"&&d?"draft-only":c.box,lateDeliveredText:c.box==="overlap"&&!d?o.returned?.text:void 0,textRevision:(o.textRevision??0)+1}:{...o,returned:void 0,inFlight:void 0,lateDelivered:i&&o.returned?.text?"overlap":i?"delivered":void 0,lateDeliveredText:i?o.returned?.text:void 0};e({inputByConversation:{...t().inputByConversation,[n]:a||c!==null&&r(c.row)?l:u}})},dismissLateDelivery:n=>{const o=t().inputByConversation[n];o?.lateDelivered&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,lateDelivered:void 0,lateDeliveredText:void 0}}})},clearComposer:n=>{const o=t().inputByConversation[n];o&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,volatilePendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,textRevision:(o.textRevision??0)+1}}})},setComposerText:(n,o)=>{const r=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:o,unredactedChars:r.unredactedChars??0,textRevision:(r.textRevision??0)+1}}})}}),{name:lg,storage:Mx,partialize:e=>({inputByConversation:Object.fromEntries(Object.entries(e.inputByConversation).map(([t,n])=>{let o=n;return o.inFlight?.volatileText&&(o={...o,inFlight:{...o.inFlight,text:""}}),o.returned?.volatileText&&(o={...o,returned:{...o.returned,text:""}}),o.volatilePendingText&&(o={...o,pendingText:void 0}),o.volatilePendingText&&(o={...o,lateDeliveredText:void 0}),[t,o]}))}),merge:(e,t)=>({...t,inputByConversation:Cx(e?.inputByConversation)})}));function ug(e){if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null}function eN(e,t){return t?e.filter(n=>n.session_id===t&&fg(n)).length:0}function fg(e){if(ug(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function jx(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function tN(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 nN={cwd:""};function $x(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,jx(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function Dx(e){return(await Ge({op:"sessions.preview",requestId:crypto.randomUUID(),cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}})).frontend}function oN(e,t){const n=e.trim();if(!n)return{checked:!0,rung:null,confirmation:r=>g("ui.chat.session_readout.draft.confirm_model",{selector:r})};if(!t.ladderKnown)return{checked:!1,rung:null,refusal:g("ui.chat.session_readout.draft.refusal_ladder_unread")};const o=t.ladder.find(r=>r.trim().toLowerCase()===n.toLowerCase());return o?{checked:!0,rung:o,confirmation:r=>g("ui.chat.session_readout.draft.confirm_model_effort",{selector:r,effort:Ai(o)})}:{checked:!0,rung:null,confirmation:r=>t.level?g("ui.chat.session_readout.draft.confirm_effort_changed",{selector:r,level:Ai(t.level),wanted:Ai(n)}):g("ui.chat.session_readout.draft.confirm_effort_unset",{selector:r,wanted:Ai(n)})}}function rN(e,t){return e!==!0?null:t==="on"?g("ui.chat.fast_mode.stays_on"):t==="off"?g("ui.chat.fast_mode.turned_off"):g("ui.chat.fast_mode.unsupported_stays_off")}const iN=()=>g("ui.chat.fast_mode.service_cannot_carry"),sN="fast_unavailable";function Dl(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...o}=e;return o}function aN(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function cN(e){const t=e instanceof Ae?e:null;return t?.code==="fast_mode_unsupported"?g("ui.chat.fast_mode.pick_unsupported"):t?.status===422?g("ui.chat.fast_mode.service_unavailable"):g("ui.chat.fast_mode.not_changed")}function lN(e,t){const n={...e,model:Dl(e.model,t)};return{queryKey:$x(n),queryFn:()=>Dx(n),placeholderData:tb,staleTime:3e4,retry:!1}}function ae(e){return typeof e=="string"?e.trim():""}function Eo(e){const t=ae(e);return t||null}function Nn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function vr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function pg(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function no(e,t){return typeof e=="boolean"?e:t}function Ic(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Zo(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 Zo(t)}return[]}function Nx(e){if(!Cn(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:pg(e.attempts),last_frame_at:Nn(e.last_frame_at),next_retry_at:Nn(e.next_retry_at),last_error:ae(e.last_error)}}function Cn(e){return typeof e=="object"&&e!==null}const Lx=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function Fx(e,t){const n=ae(e);return Lx.includes(n)?n:t?"reachable":"unreachable_legacy"}const Ux=["running","not_listening","unknown"];function Bx(e){const t=ae(e);return Ux.includes(t)?t:void 0}function Hx(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:Nn(t.latency_ms)})).filter(t=>t.endpoint!=="")}function dN(e){const t=new Set,n=[];for(const a of Zo(e)){const c=ae(a.device_id);if(!c||t.has(c)||typeof a.reachable!="boolean")continue;t.add(c);const l=Bx(a.remote_relay),d=Hx(a.attempts),u=a.reachable?void 0:Nx(a.redial);n.push({device_id:c,name:ae(a.name),reachable:a.reachable,link_state:Fx(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:Eo(a.unreachable_reason??a.reason),last_seen_at:Nn(a.last_seen_at),session_count:vr(a.session_count),rtt_ms:Nn(a.rtt_ms)})}const o=Cn(e)?e:{},r=ae(o.self_device_id),i=Ic(o.degraded);return{peers:n,...r?{self_device_id:r}:{},...i.length?{degraded:i}:{}}}function Wx(e){const t=ae(e.device_id);return t?{device_id:t,name:ae(e.name),role:ae(e.role),capabilities:Ic(e.capabilities),active:no(e.active,!0),suspect:no(e.suspect,!1),endpoints:Ic(e.endpoints),last_seen_at:Nn(e.last_seen_at),reachable:no(e.reachable,!0),reason:ae(e.reason??e.unreachable_reason),scope:ae(e.scope)}:null}function Gx(e){const t=ae(e.network_id);return t?{network_id:t,name:ae(e.name),epoch:pg(e.epoch),trust:ae(e.trust),members:Zo(e.members).map(Wx).filter(n=>n!==null)}:null}function uN(e){const t=Cn(e)?e:{},n=ae(t.self_device_id);return{networks:Zo(t.networks).map(Gx).filter(o=>o!==null),...n?{self_device_id:n}:{}}}function zx(e){return e.live_state.trim().toLowerCase()==="busy"}function fN(e){const t=[],n=new Set,o=Array.isArray(e)?e:e?.sessions??e;for(const r of Zo(o)){const i=ae(r.id);if(!i||n.has(i))continue;const a=r.locality==="remote"?"remote":ae(r.locality)==="local"?"local":null;if(!a)continue;n.add(i);const c=Cn(r.status)?{code:ae(r.status.code),label:ae(r.status.label)}:null,l=Cn(r.binding)?{agent:Eo(r.binding.agent),team:Eo(r.binding.team)}:null,d=Cn(r.opened_by)?{agent:Eo(r.opened_by.agent),label:Eo(r.opened_by.label),session:Eo(r.opened_by.session)}:null;t.push({id:i,name:ae(r.name),mtime:Nn(r.mtime)??0,locality:a,owner_device:ae(r.owner_device),owner_device_name:ae(r.owner_device_name),reachable:no(r.reachable,!0),unreachable_reason:ae(r.unreachable_reason),live_state:ae(r.live_state),archived:no(r.archived,!1),created_at:Nn(r.created_at),pinned:no(r.pinned,!1),...typeof r.active=="boolean"?{active:r.active}:{},waiting_on:vr(r.waiting_on),jobs_running:vr(r.jobs_running),subagents_running:vr(r.subagents_running),subagents_queued:vr(r.subagents_queued),...typeof r.background_work=="boolean"?{background_work:r.background_work}:{},...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function pN(e){const{id:t,name:n,mtime:o,...r}=e;return{...r,session_id:t,title:n,updated_at:o}}function hN(e){if(!Cn(e))return null;const t=ae(e.session_id);if(!t)return null;const n=e.mode==="keep"?"keep":"move",o=ae(e.new_session_id)||(n==="move"?t:"");return o?{locality:e.locality==="local"?"local":"remote",owner_device:ae(e.owner_device),source_retired:no(e.source_retired,n==="move"),session_id:t,new_session_id:o,mode:n,phases:Zo(e.phases).map(r=>({phase:ae(r.phase),peer:ae(r.peer),progress:typeof r.progress=="number"?r.progress:0}))}:null}const Kx=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function mN(e){const t=e,n=ae(t?.code)||"move_refused",o=typeof t?.status=="number"?t.status:null;return{code:n,sentence:ae(t?.message)||g("ui.mesh.errors.move_refused"),status:o,unconfirmed:o===503||Kx.has(n)}}function gN(e){const t=ae(e.name);return t||g("ui.mesh.mesh_types.device_suffix",{suffix:ae(e.device_id).slice(-6)})}function Vx(e){const t=ae(e.name);return t?JSON.stringify(t):g("ui.mesh.mesh_types.unnamed_device")}function Zx(e,t){const n=ae(e);if(!t)return n;const o=t.map(ae).filter(i=>i.length>0&&i!==n);let r=Math.min(10,n.length);for(;r<n.length&&o.some(i=>i.startsWith(n.slice(0,r)));)r+=1;return r<n.length?`${n.slice(0,r)}…`:n}function _N(e,t,n=!1){const o=n?Zx(e.id,t):ae(e.id);return`${Vx(e)} ${o}`}function bN(e){const t=ae(e.name);return t||g("ui.mesh.mesh_types.network_suffix",{suffix:ae(e.network_id).slice(-6)})}const Yx=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function Xx(e){const t=e.trim();return t!==""&&Yx.includes(t)}function hg(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"||Xx(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const vN=()=>g("ui.mesh.mesh_graph.identity_suspect");function mg(e){switch(e){case"self":return g("ui.mesh.mesh_drop.this_device");case"reached":return g("ui.mesh.mesh_reach.reached");case"relay-down":return g("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return g("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return g("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return g("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return g("ui.mesh.mesh_reach.not_a_member");case"unanswered":return g("ui.mesh.mesh_reach.no_answer");case"not-attempted":return g("ui.mesh.mesh_reach.not_asked");default:return g("ui.mesh.mesh_reach.unknown")}}function yN(e){const t=hg(e),n=mg(t);return e.reason?`${n} — ${e.reason}`:n}const wN={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"},kN={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function SN(e){const t=e.trim();switch(t){case"ok":return g("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return g("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return g("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return g("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return g("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?g("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function EN(e){return e.reachable?"":e.remoteRelay==="not_listening"?g("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?g("ui.mesh.mesh_reach.peer_closed_handshake"):""}function IN(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(o=>zx(o))?"working":"idle",source:"derived"}}function Jx(e,t){const n={...e};for(const[o,r]of Object.entries(t))(!n[o]||r.at>=n[o].at)&&(n[o]=r);return n}function Qx(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 o=hg({state:"unreachable",reachable:n.reachable,reason:n.reason??"",sessionCount:n.session_count??null}),r=o==="unanswered",i=r&&n.redial_state==="reconnecting";return e.peer_reach===o&&e.link_down===r&&(e.link_reconnecting??!1)===i&&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:r,link_reconnecting:i,peer_reach:o,last_seen_at:n.last_seen_at,link_down_reason:n.reason}}function AN(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${g("ui.chat.canonical.transcript.reconnecting")} · ${Ac(n,t)}`:g("ui.presence.link_down_last_seen",{age:Ac(n,t)})}function Ac(e,t){if(e===null)return g("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?g("ui.presence.just_now"):n<3600?g("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?g("ui.presence.hours_ago",{count:Math.floor(n/3600)}):g("ui.presence.days_ago",{count:Math.floor(n/86400)})}function RN(e,t){if(e.link_reconnecting===!0)return g("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return g("ui.presence.link_down_compact",{age:Ac(n,t)})}function qx(e,t,n,o){if(o<=n)return{facts:e,watermark:n,removed:[]};const r=Object.fromEntries(Object.entries(e).filter(([,i])=>i.at>o));for(const[i,a]of Object.entries(t))(!r[i]||a.at>=r[i].at)&&(r[i]=a);return{facts:r,watermark:o,removed:Object.keys(e).filter(i=>!r[i])}}function xN(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?mg(e.peer_reach):null}const e1=Object.freeze({}),Nl=["model","effort","fast","cwd"],t1=new Set(["pending","applying","queued_next_step","waiting_idle"]);function gg(e){return!!(e&&t1.has(e.state))}function n1(e,t){return t?e.request_id===t.request_id?t.local?!0:e.generation>t.generation||e.generation===t.generation&&!xf(e,t):e.generation!==t.generation?e.generation>t.generation:t.local?!1:!xf(e,t):!0}function xf(e,t){return!e.updated_at||!t.updated_at?!1:Date.parse(e.updated_at)<Date.parse(t.updated_at)}let _g=0;const bg=new WeakMap;function o1(e){return bg.set(e,++_g),e}function TN(){return _g}function r1(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Xr(e,t,n){const o={...e};return Object.keys(n).length===0?delete o[t]:o[t]=n,o}function Rc(e,t,n,o){const r=e[t]??{},i=r[n];if(o===null){if(!i||i.local)return e;const{[n]:a,...c}=r;return Xr(e,t,c)}return o.kind!==n||!n1(o,i)||i&&!i.local&&r1(o,i)?e:Xr(e,t,{...r,[n]:o1(o)})}function vg(e,t,n,o){let r=e;for(const i of Nl){const a=n[i];if(a){r=Rc(r,t,i,a);continue}if(o===void 0)continue;const c=r[t]?.[i];c&&(bg.get(c)??0)>o||(r=Rc(r,t,i,null))}return r}function i1(e,t,n,o=Number.POSITIVE_INFINITY){const r=n?[n]:[...new Set([...Object.keys(e),...Object.keys(t)])];let i=e;for(const a of r)i=vg(i,a,t[a]??{},o);return i}function s1(e,t,n,o=Date.now()){const r=e[t]??{},i=r[n.kind],a=new Date(o).toISOString(),c={kind:n.kind,value:n.value,effort:n.effort??null,request_id:n.requestId,generation:(i?.generation??0)+1,base:i?.base??null,state:"pending",attempts:0,created_at:a,updated_at:a,error:null,local:!0};return Xr(e,t,{...r,[n.kind]:c})}function a1(e,t,n,o,r,i=Date.now()){const a=e[t],c=a?.[n];return!a||!c||c.request_id!==o?e:Xr(e,t,{...a,[n]:{...c,state:"failed",error:r,updated_at:new Date(i).toISOString()}})}function c1(e,t,n,o){const r=e[t],i=r?.[n];if(!r||!i||i.generation!==o)return e;const{[n]:a,...c}=r;return Xr(e,t,c)}function CN(e){const t=a=>{const c=e?.[a];return c&&(c.state==="pending"||c.state==="applying"||c.state==="queued_next_step")?c:null},n=t("model"),o=t("effort"),r=t("fast"),i=t("cwd");return{model:typeof n?.value=="string"?n.value:null,effort:typeof o?.value=="string"?o.value:typeof n?.effort=="string"&&n.effort?n.effort:null,fast:typeof r?.value=="boolean"?r.value:null,cwd:typeof i?.value=="string"?i.value:null}}function ON(e){if(!e)return null;let t=null;for(const n of Nl){const o=e[n];if(o?.state==="failed")return o;!t&&o&&gg(o)&&(t=o)}return t}function PN(e){if(!e)return[];const t=[];for(const n of Nl){const o=e[n];o&&(gg(o)||o.state==="failed")&&t.push(o)}return t}function MN(e){const t=e.status??null;return{code:e.code??(t===null?"runtime_unreachable":"refused"),message:e.message??"",retryable:t===null||t>=500}}function jN(e,t){if(e===t)return[];const n=[];for(const[o,r]of Object.entries(t)){const i=r.cwd;if(i?.state!=="applied"||typeof i.value!="string")continue;const a=e[o]?.cwd;a?.state==="applied"&&a.request_id===i.request_id||n.push(i.value)}return n}function $N(e){return e.local?e.state==="failed"&&e.error?.retryable===!0:!0}const Tf=new Set;function DN(e){return Tf.has(e)?!1:(Tf.add(e),!0)}function NN(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?g("ui.chat.canonical.untitled"):n==="this chat"?g("ui.chat.canonical.this_chat"):n:t==="this_chat"?g("ui.chat.canonical.this_chat"):g("ui.chat.canonical.untitled")}function xc(e,t){return e.map((n,o)=>({id:`${t}:doc:${o}`,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 Ci=(e,t)=>e instanceof Ae?ns(e,t):e instanceof Error?e.message:t,Ms="session_unvalidated",l1=()=>g("ui.common.errors.session_unvalidated"),ps="leading_slash_message",yg=()=>g("ui.common.errors.leading_slash_message");function d1(e,t){return e instanceof Ae&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const wg="attachment_read_failed",kg="store_out_of_space",Sg="store_unavailable";function Cf(e){return e===kg||e===Sg}const u1="answer_not_sent",Eg="aside_not_answered",Ig="aside_still_answering";function yr(e){return e===ps||e===wg||e===kg||e===Sg||e===u1||e===Eg||e===Ig||e===Ms||e===Ss}function f1(e){return e instanceof Ae&&e.status===409&&Ll(e)===void 0}function Ag(e,t=!1){return m1(e)||f1(e)&&!t?"not_sent":e instanceof Ae&&e.status===404?"gone":"unknown"}function Ll(e){if(e instanceof Ae||e instanceof _n)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const mt={get unconfirmed(){return g("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return g("ui.chat.canonical.send_failure.unreachable")},get busy(){return g("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return g("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return g("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return g("ui.chat.canonical.send_failure.retiring")},get notReady(){return g("ui.chat.canonical.send_failure.not_ready")},get generic(){return g("ui.chat.canonical.send_failure.generic")},get gone(){return g("ui.chat.canonical.send_failure.gone")},get sendLock(){return g("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return g("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return g("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return g("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return g("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return g("ui.chat.canonical.send_failure.late_delivery_overlap")}};function LN(e){return e?mt.gateLock:mt.sendLock}const FN=()=>g("ui.common.actions.retry"),UN=()=>g("ui.common.actions.clear");function p1(e,t,n=!1){const o=Ag(e,n),r=t??Ll(e),i=ns(e,mt.generic);return o==="gone"?{message:mt.gone,retry:!1,code:r}:o==="not_sent"?r===Ss?{message:mt.busy,retry:!0,code:r}:r===th?{message:mt.retiring,retry:!0,code:r}:r===We.serverUpdating?{message:Qn(r),retry:!0,code:r}:r===Ms?{message:mt.notReady,retry:!yr(r),code:r}:r===Eg?{message:mt.asideNotAnswered,retry:!1,code:r}:r===Ig?{message:mt.asideStillAnswering,retry:!1,code:r}:r===ps?{message:yg(),retry:!1,code:r}:{message:i,retry:!1,code:r}:al(e)?{message:Qn(We.serverUpdating),retry:r===We.transportFailed,code:r}:r===We.transportFailed?{message:mt.unreachable,retry:!0,code:r}:Es(r)?{message:Qn(r),retry:!1,code:r}:r===il?{message:mt.unconfirmed,retry:!yr(r),code:r}:r===rw.runtimeUnreachable?{message:mt.unconfirmed,retry:!0,code:r}:r?{message:i,retry:!yr(r),code:r}:{message:mt.unconfirmed,retry:!yr(r),code:r}}function Tc(e){return e.trim()}function BN(e,t){if(t.length===0)return Tc(e);const n=t.map(o=>`<reply-to>${o.text}</reply-to>`).join(`
|
|
45
|
+
`);return Tc(`${n}
|
|
46
|
+
${e}`)}function Cc(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function h1(e,t,n,o){if(t.peer!==void 0||n?.locality==="remote"||o?.locality==="remote")return!1;const r=t.submittedAt;if(r===void 0||r<=0)return!1;const i=e[0]?.ts;return i===void 0||i<=0?!1:i*1e3<=r}function HN(e,t,n){if(e)return e;if(!t)return null;const o=Object.entries(n).filter(([,i])=>Cc(i,t));return(o.find(([,i])=>i.submittedText!==void 0||i.undelivered!==void 0||i.error!==void 0||i.admissionAttempted===!0||i.pending===!0)??o[0])?.[0]??`send:${t}`}function js(e,t){return t??e??void 0}function Rg(e,t,n){return e?t??void 0:n??void 0}function WN(e,t,n){return js(e,Rg(e,t,n))}function GN(e,t,n){const o=js(t,n);if(!e||o===void 0)return o;if(t===e.draftKey&&n===e.sessionId)return e.key;if(e.sessionId!==void 0&&n===void 0&&t!==null&&t===e.draftKey)return`${e.key}#unbound`;const r=e.draftKey!==null&&e.sessionId===void 0&&t===e.draftKey&&n!==void 0,i=e.sessionId!==void 0&&n===e.sessionId;return r||i?e.key:o}function m1(e){return e instanceof Ae?e.status===413||e.status===422?!0:e.code===Ss||e.code===th||e.code===We.noCredential||e.code===We.serverUpdating||Cf(e.code):e instanceof _n&&(e.code===Ms||e.code===wg||Cf(e.code))}function ai(e,t){const n=e.startsWith("send:")?e.slice(5):null;return js(e.startsWith("draft:")?e:null,t??n)??e}function g1(e,t){const n=lt.getState(),o=ai(e,t),r=o===""||o===e?[e]:[e,o];n.settleInFlight(r),o!==""&&o!==e&&n.inputByConversation[e]&&n.returnInFlight(e,o)}function zN(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 o=ai(e,t.sessionId);return lt.getState().returnPayload(o,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),Je.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:mt.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!yr(t.heldClaimCode),heldClaimCode:void 0}),!0}function KN(e,t){if(!t)return!1;const n=t.undelivered,o=t.submittedText,r=o!==void 0&&t.error!==void 0&&t.errorRetry!==void 0;if(!n&&!r)return!1;const i=ai(e,t.sessionId);if(n){if(Af(i,n.recordId))return!1;const c=cg(i,n.recordId);return c!=="unseen"?(c==="owner"&&Je.getState().retractUndelivered(e,n.recordId),!1):(wc(i,{id:n.recordId,text:n.text,images:[],documents:xc(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(o===void 0)return!1;const a=t.admissionRequestId;return Af(i,a)?!1:(wc(i,{id:a,text:t.submittedRendered??o,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${a}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type})),documents:xc(t.submittedFiles??[],a)}),!0)}function Of(e,t,n){Ex(ai(e,t),n)}function _1(e,t,n){if(e.submittedText!==t)return!1;const o=e.submittedAttachments??[];return o.length!==n.length?!1:o.every((r,i)=>r===n[i])}function b1(e,t){return!!t&&e===t}const v1=3,y1=5e3,w1=2e3;async function k1(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=v1||!(n instanceof Ae)||n.code!==Ss)throw n;const o=Math.min(Math.max(0,n.retryAfterMs??w1),y1);await new Promise(r=>setTimeout(r,o))}}async function S1(e){await k1(async()=>{await Ge(e)})}async function VN(e,t,n,o,r){const i=Je.getState();if(b1(i.validatingSessionId,n))throw new _n(l1(),Ms);const a=i.drafts[e];if(a?.pending)return null;const c=Tc(t.text),l=a?.submittedText!==void 0&&_1(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,_=l&&a?a.submittedInputMode:t.inputMode,y=l&&a?a.submittedInputPath:t.inputPath,v=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),b=Date.now();i.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:v,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:h,submittedInputMode:_,submittedInputPath:y,error:void 0,errorCode:void 0,submittedAt:b});const p=js(e.startsWith("draft:")?e:null,n??d.sessionId)??null;p&&wc(p,{id:v,submittedAt:b,text:c,images:u.map((P,W)=>({id:`${v}:${W}`,data:P.data_b64,attachment:null,mimeType:P.mime_type})),documents:xc(f??[],v),onPainted:o});let A=l,k=n??d.sessionId,M=null;try{if(!k){if(M="sessions.create",k=await i.createSession(t.cwd,d.target,d.createRequestId,Dl(d.model??null,i.draftFastCarries),d.warmId,d.peer,YA(d,i.temporaryChats)?!0:void 0)??void 0,!k)throw new _n(Je.getState().error??g("ui.common.errors.chat_start_simple"));i.updateDraft(e,{sessionId:k}),p&&vx(p,k),i.fetchSessions()}const P=l&&a?.submittedRendered!==void 0?a.submittedRendered:r?await r(k)??c:c;return A=!0,i.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:P}),k&&bx(k,v,P),M="sessions.message",await S1({op:"sessions.message",sessionId:k,requestId:v,text:P,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:h,inputMode:_,inputPath:y}),i.finishDraft(e,k),Je.setState({error:null}),k}catch(P){Je.setState({error:null});const W=l&&a?.admissionAttempted===!0,R=Ag(P,W),m=M==="sessions.message"&&d1(P,c),w=m?ps:Ll(P),S=p1(P,w,W);let T=!1;const N=k??p??void 0;if(N&&R==="unknown"&&(T=A&&cg(N,v)==="owner"),i.updateDraft(e,{pending:!1,admissionAttempted:R==="unknown"&&A,errorCode:w,error:S.message,errorRetry:S.retry}),T)return k?(i.finishDraft(e,k),k):null;const Y=ai(e,k??d.sessionId),X=p&&p!==Y?[p,Y]:[Y];throw lt.getState().settleInFlight(X),p&&p!==Y&<.getState().returnInFlight(p,Y),N&&Sc(N,v),e!==N&&Sc(e,v),m?new Ae(422,yg(),P,ps):P}}const xg=50,Pf="activity",E1=25,I1=500;function A1(e){return e?xg:I1}function Mf(e,t){return`${e}:${t}`}function R1(e){const t=new Set;for(const n of Object.values(e))for(const o of n.ids)t.add(o);return t}function x1(e){const t=[];for(const[n,o]of Object.entries(e))o.locality==="remote"&&t.push(n);return t}function T1(e,t){const n=new Set;for(const[o,r]of Object.entries(t))r.locality==="remote"&&n.add(o);for(const o of e)o.locality==="remote"&&n.add(o.session_id);return n}function Tg(e,t,n){if(t[n]?.locality==="remote")return!0;for(const o of e)if(o.session_id===n&&o.locality==="remote")return!0;return!1}function C1(e){const t=new Set(e.tailIds),n=new Set(e.keepIds??[]),o=new Set(e.page.map(c=>c.session_id)),r=e.sessions.filter(c=>o.has(c.session_id)?!1:e.scopeIds.has(c.session_id)||n.has(c.session_id)?!0:t.has(c.session_id)),i=e.merge(e.sessions,e.page),a=new Set(i.map(c=>c.session_id));for(const c of r)a.has(c.session_id)||(a.add(c.session_id),i.push(c));return{rows:i,tailIds:e.tailIds.filter(c=>a.has(c))}}function O1(e){const t=[...e.previousIds],n=new Set(t);for(const i of e.page)n.has(i.session_id)||(n.add(i.session_id),t.push(i.session_id));const o=[...e.sessions],r=new Map(o.map((i,a)=>[i.session_id,a]));for(const i of e.page){const a=r.get(i.session_id);if(a===void 0){r.set(i.session_id,o.length),o.push(i);continue}o[a]=e.merge(o[a],i)}return{rows:o,ids:t}}function Kn(e,t){return{...e,...t,...j1(e,t),...$1(t,e),attention:Co(e?.attention,t.attention,t.session_id)}}const ZN=ug,P1=e=>e.filter(fg),jf=(e,t,n)=>{const o=e.findIndex(c=>c.session_id===t);if(o<0)return e;const r=e[o],i=Co(r.attention,n,t);if(i===r.attention)return e;const a=e.slice();return a[o]={...r,attention:i},a},M1=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function j1(e,t){const n=o=>typeof o?.status_revision=="number"&&typeof o?.status_epoch=="string"?{status_revision:o.status_revision,status_epoch:o.status_epoch}:void 0;return n(t)??n(e)??{}}function $1(e,t){const n=typeof t?.status_epoch=="string"&&t.status_epoch===e.status_epoch,o=t?.status_revision,r=e.status_revision;return t?.status!==void 0&&n&&typeof o=="number"&&typeof r=="number"&&o>r?{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 D1(e,t){const n={};let o=!1;for(const[r,i]of Object.entries(e)){if(i.at<t){o=!0;continue}n[r]=i}return o?n:e}function Ta(e,t){const n={...e.archiveFacts};delete n[t];const o={...e.placementFacts};delete o[t];const r=e.answerSeq+1;return{sessions:e.sessions.filter(i=>i.session_id!==t),archiveFacts:n,placementFacts:o,answerSeq:r,forgotten:{...e.forgotten,[t]:{at:r,title:e.sessions.find(i=>i.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function Cg(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 Og(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 Pg(e,t,n){const o=lt.getState();if(t&&t!==e){o.adoptReturnedText(t);const r=lt.getState().inputByConversation[t];r&&r.inFlight===void 0&&((r.currentInput??"")!==""||(r.attachments?.length??0)>0)&&o.returnInFlight(t,e)}n&&o.returnPayload(e,{text:n.text,attachments:n.attachments,replies:[]})}function N1(e,t,n){const o=lt.getState(),r=n??(e?o.getCurrentInput(e):"");r&&o.setComposerText(t,r),e&&e!==t&&o.setComposerText(e,"")}function L1(e,t){let n=null;const o=[];for(const[r,i]of Object.entries(e))!i.sessionId||t[i.sessionId]===void 0||(n??={...e},n[r]=Cg(i),o.push({key:r,sessionId:i.sessionId,payload:Og(i)}));return{drafts:n??e,restored:o}}function Mg(e){return e.map(({id:t,name:n,mtime:o,...r})=>({...r,session_id:t,title:n,updated_at:o}))}function $f(e,t){return Mg(e).filter(n=>t[n.session_id]===void 0)}function Ca(e){return typeof e=="string"&&e.length>0?e:null}function F1(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,o=n(t.total),r=n(t.active),i=n(t.unbound);if(o===null||r===null||i===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:o,active:r,unbound:i,scopes:a}}function U1(e,t){const n=new Map(e.map(o=>[o.session_id,o]));return[...new Map(t.map(o=>[o.session_id,Kn(n.get(o.session_id),o)])).values()]}let Oa=0,yo=null;function B1(e,t,n){const o=yo;if(o)return o.invalidated=!0,o.limit=e,o.withCounts=t,o.promise;const r={limit:e,withCounts:t,invalidated:!1,promise:null};return yo=r,r.promise=(async()=>{try{for(;;){r.invalidated=!1;let i;try{i=await n(r.limit,r.withCounts)}catch(a){if(r.invalidated)continue;throw a}if(!r.invalidated)return yo===r&&(yo=null),i}}finally{yo===r&&(yo=null)}})(),r.promise}function jg(){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 H1(){const e=jg();return e.kind==="session"?e.sessionId:null}function W1(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 G1(e,t){const n={...t,...e},{drafts:o,restored:r}=L1(n.drafts,n.forgotten),i=o===n.drafts?n:{...n,drafts:o};for(const l of r)Pg(l.key,l.sessionId,l.payload);const a=jg();if(a.kind==="session")return{...i,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...i,activeSessionId:null};const c=W1(i);return c?{...i,...c}:i}const Je=ri()(Is((e,t)=>({sessions:[],settingsIntents:e1,hydrateSettingsIntents:(n,o,r)=>{e(i=>{const a=i1(i.settingsIntents,n,o,r);return a===i.settingsIntents?i:{settingsIntents:a}})},applySettingsIntentFrame:(n,o,r)=>{e(i=>{const a=Rc(i.settingsIntents,n,o,r);return a===i.settingsIntents?i:{settingsIntents:a}})},applySettingsIntentSlots:(n,o)=>{e(r=>{const i=vg(r.settingsIntents,n,o);return i===r.settingsIntents?r:{settingsIntents:i}})},paintSettingsIntent:(n,o)=>{e(r=>({settingsIntents:s1(r.settingsIntents,n,o)}))},failSettingsIntent:(n,o,r,i)=>{e(a=>{const c=a1(a.settingsIntents,n,o,r,i);return c===a.settingsIntents?a:{settingsIntents:c}})},removeSettingsIntent:(n,o,r)=>{e(i=>{const a=c1(i.settingsIntents,n,o,r);return a===i.settingsIntents?i:{settingsIntents:a}})},cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,temporaryChats:!1,activeSessionId:H1(),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(o=>{const r=Object.entries(o.drafts);return r.some(([,i])=>!i.sessionId)?{cwd:n,drafts:Object.fromEntries(r.map(([i,a])=>a.sessionId?[i,a]:[i,{...a,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=A1(t().cataloguePageable),o=!1)=>{const r=++Oa,i=t().answerSeq+1;e({answerSeq:i}),e({loading:!0,error:null});try{const a=await B1(n,o,(l,d)=>Ge({op:"sessions.list",limit:l,include_archived:!0,...t().temporaryChats?{include_temporary:!0}:{},...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:Pf}:{}}));if(r!==Oa)return;const c=Mg(a.sessions);e(l=>{const d={...l.pinFacts};for(const[m,w]of Object.entries(d))w.at>=i||delete d[m];const u=new Set(c.map(m=>m.session_id));let f=!1;const h={...l.forgotten};for(const[m,w]of Object.entries(h))w.at<i&&u.has(m)&&(delete h[m],f=!0);const _=f?h:l.forgotten,y=c.filter(m=>_[m.session_id]===void 0);let v=null;for(const m of y){const w=l.placementFacts[m.session_id];if(w===void 0||w.at>=i)continue;const S=m.locality==="remote"?"remote":m.locality==="local"?"local":null;S!==null&&(v??={...l.placementFacts},v[m.session_id]={locality:S,owner_device:typeof m.owner_device=="string"?m.owner_device:"",at:l.answerSeq+1})}const b=Ca(a.next_cursor),p=b===null&&a.truncated!==!0,A=y.map(m=>m.session_id),k=l.sessions.filter(m=>_[m.session_id]===void 0&&(l.pinFacts[m.session_id]?.at??-1)>=i),M=C1({sessions:l.sessions,scopeIds:R1(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...x1(l.placementFacts)],tailIds:p?[]:l.head.tailIds,page:y,merge:U1});let P=M.rows;for(const m of k){const w=l.pinFacts[m.session_id],S=P.findIndex(T=>T.session_id===m.session_id);S===-1?P=[...P,{...m,pinned:w.pinned}]:P[S]={...P[S],pinned:w.pinned}}const W=D1(l.archiveFacts,i),R=F1(a.counts);return{sessions:P,pinFacts:d,archiveFacts:W,...v===null?{}:{placementFacts:v,answerSeq:l.answerSeq+1},forgotten:_,loading:!1,truncated:a.truncated===!0,head:{pageIds:A,tailIds:M.tailIds,nextCursor:b,tailCursor:p?null:l.head.tailStarted?l.head.tailCursor:b,tailStarted:l.head.tailStarted,complete:p,loading:!1,error:null,at:i},...R===null?{}:{counts:R},statusUnavailable:Array.isArray(a.degraded)?a.degraded.filter(m=>typeof m=="string"):[]}})}catch(a){r===Oa&&e({loading:!1,error:Ci(a,g("ui.common.errors.chats_refresh"))})}},fetchCatalogueTail:async()=>{const n=t().head,o=n.tailCursor;if(!(o===null||n.loading)){e(r=>({head:{...r.head,loading:!0,error:null,tailStarted:!0,tailCursor:o}}));try{const r=await Ge({op:"sessions.list",limit:xg,include_archived:!0,...t().temporaryChats?{include_temporary:!0}:{},cursor:o,...t().catalogueActivityHead?{sort:Pf}:{}}),i=$f(r.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 i){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=Ca(r.next_cursor);return{sessions:l,head:{...a.head,tailIds:[...a.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(r){e(i=>({head:{...i.head,loading:!1,error:Ci(r,g("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,o,r=null,i=E1)=>{const a=Mf(n,o);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 Ge({op:"sessions.list",limit:i,include_archived:!1,scope_kind:n,scope_name:o,...r===null?{}:{cursor:r}}),d=$f(l.sessions,t().forgotten);e(u=>{const f=u.scopes[a];if(f===void 0||f.at!==c)return{};const h=r!==null&&l.cursor_missing!==!0,_=O1({sessions:u.sessions,previousIds:h?f.ids:[],page:d,merge:Kn}),y=Ca(l.next_cursor);return{sessions:_.rows,scopes:{...u.scopes,[a]:{ids:_.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:Ci(l,g("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,o)=>{const r=Mf(n,o);e(i=>{const a=i.scopes[r];if(a===void 0)return{};const c={...i.scopes};delete c[r];const l=i.activeSessionId,d=new Set(a.ids),u=new Set(i.head.pageIds),f=i.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})},setTemporaryChats:n=>{t().temporaryChats!==n&&e({temporaryChats:n})},setDraftTemporary:(n,o)=>e(r=>{const i=r.drafts[n];return i?i.temporary===!0===o?{}:{drafts:{...r.drafts,[n]:{...i,temporary:o?!0:void 0,...i.sessionId?{}:{createRequestId:crypto.randomUUID()}}}}:{}}),setSessionTemporary:async(n,o)=>{try{const r=await Ge({op:"sessions.temporary",sessionId:n,temporary:o}),i=r&&typeof r.temporary=="object"?r.temporary:null;return e(a=>({sessions:a.sessions.map(c=>c.session_id===n?{...c,temporary:i}:c)})),{ok:!0}}catch(r){return{ok:!1,code:r instanceof Ae?r.code:void 0,detail:ns(r,"")}}},setDraftFastCarries:n=>{t().draftFastCarries!==n&&e({draftFastCarries:n})},setDraftWarmable:n=>{if(t().draftWarmable===n||(e({draftWarmable:n}),!n))return;const o=t().activeDraftKey,r=o?t().drafts[o]:void 0;if(!o||!r||r.sessionId||r.warmId)return;lt.getState().inputByConversation[o]?.currentInput&&t().ensureDraftWarm(o)},setArchiveUndo:n=>{e({archiveUndo:n})},setDraftsUndo:n=>{e({draftsUndo:n})},raiseBulkReadDeferral:n=>{e(o=>({bulkReadDeferral:{count:n,at:o.answerSeq+1}}))},clearBulkReadDeferral:()=>{e({bulkReadDeferral:null})},setStagedByDiscard:n=>{e({stagedByDiscard:n})},restoreDraftsUndo:()=>e(n=>{const o=n.draftsUndo;if(!o)return{};const r={...n.drafts};for(const[a,c]of Object.entries(o.drafts))a in r||(r[a]=c);const i=lt.getState();for(const[a,c]of Object.entries(o.composer)){const l=i.inputByConversation[a];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||i.restoreRow(a,c)}return{drafts:r,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,o,r)=>{const i=t().answerSeq+1,a=t().archiveFacts[n]??null,c=r??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:i,archiveFacts:{...l.archiveFacts,[n]:{archived:o,at:i,answered:!1}}}));try{return await Ge({op:"sessions.archive",sessionId:n,archived:o}),e(l=>{const u=l.archiveFacts[n]?.at!==i;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:o,at:i,answered:!0}},archiveUndo:u?l.archiveUndo:o?{sessionId:n,title:c??void 0,archived:!0,at:i}:null,archiveFailure:l.archiveFailure?.sessionId===n?null:l.archiveFailure}}),!0}catch(l){return e(d=>{const u=d.archiveFacts[n]?.at!==i,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:o,title:c||"",detail:l instanceof Ae&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await Ge({op:"sessions.delete",sessionId:n,confirmed:!0}),e(o=>Ta(o,n)),t().retireDraftsForSession(n),{ok:!0}}catch(o){const r=o instanceof Ae?o.status:null,i=o instanceof Ae?o.code??null:null;return r===404?(e(a=>Ta(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:i==="session_delete_refused",detail:o instanceof Ae&&o.message?o.message:g("ui.common.errors.conversation_delete")}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,o,r=crypto.randomUUID(),i,a,c,l)=>{try{const d=await Ge({op:"sessions.create",requestId:r,cwd:n,...o?{target:o}:{},...i?{model:i}:{},...a?{draftId:a}:{},...c?{peer:c}:{},...l?{temporary:!0}:{}}),u=t().sessions.some(h=>h.session_id===d.session_id),f=Date.now()/1e3;return t().upsertSession({session_id:d.session_id,cwd:n,binding:d.binding,...u?{}:{created_at:f,updated_at:f},...l?{temporary:{marked_at:Date.now()/1e3,idle_minutes:30,deletes_at:null,hold:"running"}}:{}}),c&&t().settlePlacement(d.session_id,{locality:"remote",owner_device:c}),d.session_id}catch(d){throw e({error:Ci(d,g("ui.common.errors.chat_start"))}),d}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,o=Date.now())=>e(r=>({stoppedTurns:{...r.stoppedTurns,[n]:o}})),clearTurnStopped:n=>e(o=>{if(!(n in o.stoppedTurns))return o;const{[n]:r,...i}=o.stoppedTurns;return{stoppedTurns:i}}),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,...Ta(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(o=>({readAckRearm:M1(o.readAckRearm,n)}))},publishReadAckNotice:(n,o,r)=>{e(i=>{const a=i.readAckNotice;return a?.sessionId===n&&a.kind===o?i:{readAckNotice:{sessionId:n,kind:o,revision:(a?.revision??0)+1,reason:r}}})},clearReadAckNotice:n=>{e(o=>o.readAckNotice?.sessionId===n?{readAckNotice:null}:o)},applyAttention:(n,o)=>{e(r=>{const i=jf(r.sessions,n,o);return i===r.sessions?r:{...r,sessions:i}})},applyAttentionMany:n=>{e(o=>{let r=o.sessions;for(const i of n){const a=i?.conversation_id;typeof a!="string"||!a.startsWith("session/")||(r=jf(r,a.slice(8),i))}return r===o.sessions?o:{...o,sessions:r}})},markAllRead:async()=>{const n=P1(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 o=await Ge({op:"attention.seen",items:n});t().applyAttentionMany(o.read);const r=T1(t().sessions,t().placementFacts),i=o.unknown.filter(a=>r.has(a)).length;return{attempted:n.length,cleared:o.read.length,superseded:o.superseded.length,unknown:o.unknown.length,deferred:i}},applySessionStatus:(n,o,r,i,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===i)return y;d=!0;const{status_revision:v,status_epoch:b,...p}=y;return p});if(l<0)return d?{...c,sessions:u}:c;const f=u[l],_=!(a!==void 0&&Object.keys(a).some(y=>f[y]!==a[y]))&&f.status?.code===o.code&&f.status?.label===o.label&&f.status_revision===r&&f.status_epoch===i;return _&&!d?c:(_||(u[l]={...f,...a,status:o,status_revision:r,status_epoch:i}),{...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,o=!1)=>{const i=(!o&&n?`draft:${n.kind}:${n.name}`:null)??`draft:${crypto.randomUUID()}`,a=t().drafts[i],c=Rg(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[i],f[d]={...a,key:d},{drafts:f}})}const l=t().drafts[i];return e(d=>({activeDraftKey:i,validatingSessionId:null,error:null,drafts:{...d.drafts,[i]:l??{key:i,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),i},restageDraft:(n,o)=>{const r=t().activeDraftKey,i=t().stageDraft(n);return N1(r,i,o),i},startNewChat:n=>{const o=t().stageDraft();return e({activeSessionId:null,validatingSessionId:null}),n&&(lt.getState().adoptReturnedText(n),lt.getState().inputByConversation[n]?.pendingText===void 0&<.getState().returnInFlight(n,o)),o},updateDraft:(n,o)=>e(r=>{const i=r.drafts[n],a=o.key!==void 0&&o.createRequestId!==void 0&&o.admissionRequestId!==void 0;return!i&&!a?{}:{drafts:{...r.drafts,[n]:{...r.drafts[n],...o}}}}),setDraftPeer:(n,o)=>e(r=>{const i=r.drafts[n];if(!i)return{};const a=o??void 0;return(i.peer??void 0)===a?{}:{drafts:{...r.drafts,[n]:{...i,peer:a,...i.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}}),setDraftModel:(n,o)=>e(r=>{const i=r.drafts[n];return i?{drafts:{...r.drafts,[n]:{...i,model:o,...i.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}:{}}),ensureDraftWarm:n=>{const o=t();if(!o.draftWarmable)return;const r=o.drafts[n];if(!r||r.sessionId||r.warmId||!o.cwd||r.peer)return;const i=r.draftRequestId??crypto.randomUUID();r.draftRequestId||t().updateDraft(n,{draftRequestId:i});const a=Dl(r.model??null,o.draftFastCarries);Ge({op:"sessions.draft",requestId:i,cwd:o.cwd,...r.target?{target:r.target}:{},...a?{model:a}:{}}).then(c=>{const l=t().drafts[n];l&&!l.warmId&&!l.sessionId&&l.draftRequestId===i&&t().updateDraft(n,{warmId:c.draft_id})}).catch(()=>{})},finishDraft:(n,o)=>e(r=>{g1(n,o);const i={...r.drafts};return delete i[n],{drafts:i,...r.activeDraftKey===n?{activeDraftKey:null,activeSessionId:o}:{}}}),retireDraftSession:n=>{const o=t().drafts[n];if(!o?.sessionId||o.pending)return;const r=o.sessionId,i=Og(o);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:Cg(c)}}}),Pg(n,r,i)},retireDraftsForSession:n=>{for(const[o,r]of Object.entries(t().drafts))o.startsWith("draft:")&&r.sessionId===n&&t().retireDraftSession(o)},retireDraftWarm:n=>{const o=Object.entries(t().drafts).filter(([r,i])=>r.startsWith("draft:")&&i.warmId===n&&!i.sessionId);o.length!==0&&e(r=>{const i={...r.drafts};for(const[a]of o){const c=i[a];!c||c.warmId!==n||c.sessionId||(i[a]={...c,warmId:void 0,draftRequestId:crypto.randomUUID()})}return{drafts:i}})},discardDraft:n=>e(o=>{const r={...o.drafts},i=r[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),a=r[n],c=lt.getState().inputByConversation[n];Ri(n),i&&i!==n&&Ri(i),delete r[n],lt.getState().clearAll(n);const l=a?{at:o.answerSeq+1,keys:[n],drafts:{[n]:a},composer:c?{[n]:c}:{}}:null;return{drafts:r,...l?{answerSeq:l.at,draftsUndo:l}:{},...o.activeDraftKey===n?{activeDraftKey:null}:{}}}),discardDrafts:n=>e(o=>{const r={...o.drafts};let i=!1;const a=[],c={},l={};for(const u of n){if(!(u in r))continue;const f=r[u];if(!f)continue;const h=f.sessionId??(u.startsWith("send:")?u.slice(5):void 0);Ri(u),h&&h!==u&&Ri(h),a.push(u),c[u]=f;const _=lt.getState().inputByConversation[u];_&&(l[u]=_),delete r[u],lt.getState().clearAll(u),o.activeDraftKey===u&&(i=!0)}if(a.length===0)return{};const d=o.answerSeq+1;return{drafts:r,answerSeq:d,draftsUndo:{at:d,keys:a,drafts:c,composer:l},...i?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,o,r)=>e(i=>{const a=o.map(S=>S.id),c=Object.entries(i.drafts).filter(([,S])=>Cc(S,n)&&S.undelivered!==void 0&&a.includes(S.undelivered.recordId));let l=i.drafts;if(c.length>0){l={...l};for(const[S,T]of c){const N=T.undelivered?.recordId,{undelivered:Y,...X}=T;l[S]=X,N!==void 0&&Of(S,T.sessionId,N)}}const d=Object.entries(l).find(([,S])=>Cc(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,_=a.includes(h);if(!_&&!r)return c.length>0?{drafts:l}:{};if(!_&&!h1(o,f,i.placementFacts[n],i.sessions.find(S=>S.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:y,submittedText:v,submittedAttachments:b,submittedImages:p,submittedMode:A,submittedInputMode:k,submittedInputPath:M,heldClaimCode:P,error:W,errorCode:R,errorRetry:m,...w}=f;return _||Sc(n,h),{drafts:{...l,[u]:{...w,..._?{}:{undelivered:{recordId:h,text:v??"",attachments:b??[]}},admissionRequestId:crypto.randomUUID()}}}}),retractUndelivered:(n,o)=>{const r=t().drafts[n];!r||r.undelivered?.recordId!==o||(e(i=>{const{undelivered:a,...c}=i.drafts[n];return{drafts:{...i.drafts,[n]:c}}}),Of(n,r.sessionId,o))},bindSession:(n,o)=>t().setActiveSession(o),beginAnswer:()=>{const n=t().answerSeq+1;return e({answerSeq:n}),n},applySearchAnswer:(n,o)=>e(r=>{let i=null,a=null,c=null;for(const l of o){const d=r.archiveFacts[l.id];if(d!==void 0&&d.at<n&&(c=c??{...r.archiveFacts},delete c[l.id]),!(d!==void 0&&d.at>=n)&&typeof l.archived=="boolean"&&r.sessions.some(f=>f.session_id===l.id&&f.archived!==l.archived)){a=a??r.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=r.pinFacts[l.id];if(!(u!==void 0&&u.at>=n)&&(u!==void 0&&(i=i??{...r.pinFacts},delete i[l.id]),r.sessions.some(f=>f.session_id===l.id&&f.pinned!==l.pinned))){a=a??r.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return i===null&&a===null&&c===null?{}:{...i===null?{}:{pinFacts:i},...a===null?{}:{sessions:a},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,o,r)=>{const i=t().sessions.find(h=>h.session_id===n),a=t().pinFacts[n]??null,c=i===void 0?a?.pinned??!1:i.pinned===!0,l=i===void 0&&r!==void 0?{session_id:n,title:r.title||"",updated_at:r.updated_at,pinned:o}:null,d=t().beginAnswer(),u=i?.title??r?.title,f=i?.updated_at??r?.updated_at;e(h=>({sessions:l===null?h.sessions.map(_=>_.session_id===n?{..._,pinned:o}:_):[...h.sessions,l],pinFacts:{...h.pinFacts,[n]:{pinned:o,at:d,title:u,updated_at:f}},pinFailure:null}));try{const h=await Ge({op:"sessions.pin",sessionId:n,pinned:o});let _=!1;return e(y=>{const v=y.pinFacts[n];return v===void 0||v.at!==d?{}:(_=!0,{sessions:y.sessions.map(b=>b.session_id===n?{...b,pinned:h.pinned===!0}:b),pinFacts:{...y.pinFacts,[n]:{...v,pinned:h.pinned===!0}}})}),_}catch(h){return e(_=>{const y=_.pinFacts[n];if(y!==void 0&&y.at!==d)return{};const v={..._.pinFacts};return a===null&&i===void 0?delete v[n]:v[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:_.sessions.map(b=>b.session_id===n?{...b,pinned:c}:b),pinFacts:v,pinFailure:{sessionId:n,pinned:o,title:i?.title||"",detail:ns(h,""),...h instanceof Ae&&h.code?{code:h.code}:{}}}}),!1}},upsertSession:n=>e(o=>({sessions:o.sessions.some(i=>i.session_id===n.session_id)?o.sessions.map(i=>i.session_id===n.session_id?Kn(i,n):i):[...o.sessions,n]})),settlePlacement:(n,o)=>{const r=t().beginAnswer();e(i=>({sessions:i.sessions.map(a=>a.session_id===n?Kn(a,{session_id:n,locality:o.locality,owner_device:o.owner_device}):a),placementFacts:{...i.placementFacts,[n]:{locality:o.locality,owner_device:o.owner_device,at:r}}}))},settlePeerCatalogue:(n,o,r={},i=void 0)=>{e(a=>{const c={...a.forgotten};for(const m of n)c[m.session_id]?.at<o&&delete c[m.session_id];const l=n.filter(m=>{if(c[m.session_id]||m.locality==="remote"&&a.peerDeviceSnapshotAt>o&&typeof m.owner_device=="string"&&!a.peerDeviceFacts[m.owner_device])return!1;const w=a.placementFacts[m.session_id];return!w||w.at<o}),d={...a.placementFacts},u=new Set;let f=!1,h=0;for(const m of l){const w=m.locality==="remote"?"remote":m.locality==="local"?"local":null;if(w===null)continue;const S=a.placementFacts[m.session_id];if(S!==void 0){if(S.at>=o)continue}else if(w!=="remote")continue;h=h===0?a.answerSeq+1:h,u.add(m.session_id),d[m.session_id]={locality:w,owner_device:w==="remote"&&typeof m.owner_device=="string"?m.owner_device:"",at:h},f=!0}const _=i===void 0?null:qx(a.peerDeviceFacts,r,a.peerDeviceSnapshotAt,i),y=_?.facts??Jx(a.peerDeviceFacts,Object.fromEntries(Object.entries(r).filter(([,m])=>m.at>a.peerDeviceSnapshotAt))),v=l.filter(m=>m.locality==="remote");let b=a.sessions,p=!1;const A=[],k=new Map;for(let m=0;m<b.length;m+=1)k.set(b[m].session_id,m);for(const m of v){const w=k.get(m.session_id);if(w===void 0){A.push(m);continue}b[w]!==m&&(p||(b=b.slice(),p=!0),b[w]=Kn(b[w],m))}A.length>0&&(b=[...b,...A]);for(const m of l){if(m.locality==="remote"||!u.has(m.session_id))continue;const w=k.get(m.session_id);w===void 0||b[w]===m||(p||(b=b.slice(),p=!0),b[w]=Kn(b[w],m))}const M=new Set(l.map(m=>m.session_id)),P=new Set;for(const m of l)m.locality==="remote"&&typeof m.owner_device=="string"&&m.owner_device!==""&&m.reachable!==!1&&P.add(m.owner_device);const W=new Set;for(const m of b){if(m.locality!=="remote"||typeof m.owner_device!="string"||!_?.removed.includes(m.owner_device))continue;const w=a.placementFacts[m.session_id];w&&w.at>=(i??0)||(W.add(m.session_id),delete d[m.session_id])}for(const[m,w]of Object.entries(a.placementFacts))w.locality==="remote"&&(M.has(m)||w.at>=o||y[w.owner_device]?.reachable!==!1&&(w.owner_device===""||!P.has(w.owner_device)||(W.add(m),delete d[m])));W.size>0&&(b=b.filter(m=>!W.has(m.session_id)));const R=b.map(m=>Qx(m,y));return R.some((m,w)=>m!==b[w])&&(b=R,p=!0),!f&&A.length===0&&!p&&W.size===0&&Object.keys(r).length===0&&i===void 0?{}:{sessions:b,placementFacts:d,peerDeviceFacts:y,peerDeviceSnapshotAt:_?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:G1,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 YN(e,t){return t?e.filter(n=>n.archived!==!0):e}function XN(e,t){let n=!1;const o=e.map(r=>{const i=t[r.session_id];return i===void 0||!i.answered||r.archived===i.archived?r:(n=!0,{...r,archived:i.archived})});return n?o:e}function JN(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function QN(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const qN="This backend cannot archive conversations. Update the backend and try again.",eL="This conversation is already archived. Use /unarchive to restore it.",tL="This conversation is not archived, so there is nothing to restore.",nL="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 oL(e,t,n){return n&&e&&t.trim().length>0}function rL(e,t){return t===e}const se=e=>{const[t,n,o]=[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}),r=(t*.4124564+n*.3575761+o*.1804375)/.95047,i=t*.2126729+n*.7151522+o*.072175,a=(t*.0193339+n*.119192+o*.9503041)/1.08883,c=f=>f>216/24389?Math.cbrt(f):841/108*f+4/29,[l,d,u]=[c(r),c(i),c(a)];return[116*d-16,500*(l-d),200*(d-u)]},fe=(e,t)=>{const[n,o,r]=se(e),[i,a,c]=se(t),l=Math.PI/180,d=180/Math.PI,u=(Math.hypot(o,r)+Math.hypot(a,c))/2,f=.5*(1-Math.sqrt(u**7/(u**7+25**7))),[h,_]=[(1+f)*o,(1+f)*a],[y,v]=[Math.hypot(h,r),Math.hypot(_,c)],b=(E,V)=>{if(E===0&&V===0)return 0;const G=Math.atan2(E,V)*d;return G<0?G+360:G},[p,A]=[b(r,h),b(c,_)],k=i-n,M=v-y;let P=0;y*v!==0&&(P=A-p,P>180?P-=360:P<-180&&(P+=360));const W=2*Math.sqrt(y*v)*Math.sin(P*l/2),R=(n+i)/2,m=(y+v)/2;let w;y*v===0?w=p+A:(w=Math.abs(p-A)>180?(p+A+360)/2:(p+A)/2,w>=360&&(w-=360));const S=1-.17*Math.cos((w-30)*l)+.24*Math.cos(2*w*l)+.32*Math.cos((3*w+6)*l)-.2*Math.cos((4*w-63)*l),T=1+.015*(R-50)**2/Math.sqrt(20+(R-50)**2),N=1+.045*m,Y=1+.015*m*S,X=-Math.sin(2*30*Math.exp(-(((w-275)/25)**2))*l)*2*Math.sqrt(m**7/(m**7+25**7));return Math.sqrt((k/T)**2+(M/N)**2+(W/Y)**2+X*(M/N)*(W/Y))},hs=([e,t,n])=>{const o=(e+16)/116,r=o+t/500,i=o-n/200,a=_=>_>6/29?_**3:3*(6/29)**2*(_-4/29),c=a(r)*.95047,l=a(o),d=a(i)*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(_=>_<=.0031308?12.92*_:1.055*_**(1/2.4)-.055);if(f.some(_=>_<-.0015||_>1.0015))return null;const h=_=>Math.round(Math.min(1,Math.max(0,_))*255).toString(16).padStart(2,"0").toUpperCase();return`#${f.map(h).join("")}`},D=e=>Math.round(e*100)/100,Df=e=>{const t=e.replace("#","").trim(),n=t.length===3?t.split("").map(a=>a+a).join(""):t,[o,r,i]=[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*o+.7152*r+.0722*i},re=(e,t)=>{const[n,o]=[Df(e),Df(t)].sort((r,i)=>i-r);return(n+.05)/(o+.05)},z1=/^#[0-9a-fA-F]{3,8}$/,H=e=>typeof e=="string"&&z1.test(e),Pa=(e,t,n)=>{const o=f=>{const h=f.replace("#","").trim(),_=h.length===3?h.split("").map(y=>y+y).join(""):h;return[0,2,4].map(y=>Number.parseInt(_.slice(y,y+2),16))},[r,i,a]=o(e),[c,l,d]=o(t),u=(f,h)=>Math.round(f*n+h*(1-n));return`#${[u(r,c),u(i,l),u(a,d)].map(f=>f.toString(16).padStart(2,"0")).join("")}`},yn={"under-window":{dark:81,light:199},menu:{dark:102,light:171},popover:{dark:122,light:143}},Fl=["canvas","surface","elevated"],$s=["ink","inkMuted","inkDim"],ci=4.5,K1=3,V1=1.5,$g=["danger","success","warning","info"],Dg={hover:.05,selected:.08,field:.05,work:.08},Ng=4,Z1=1.5,Ul=.96,Y1=["sunken","surface"],Lg=3.5,Oc=e=>{const t=e.replace("#",""),n=t.length===3?t.split("").map(a=>a+a).join(""):t.slice(0,6),[o,r,i]=[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*o+.7152*r+.0722*i},Yo=(e,t)=>{const[n,o]=[Oc(e),Oc(t)].sort((r,i)=>i-r);return(n+.05)/(o+.05)},Nf=(e,t)=>Number.parseInt(e.slice(1+t*2,3+t*2),16),Ln=e=>`#${e.toString(16).padStart(2,"0").repeat(3)}`,st=(e,t,n)=>`#${[0,1,2].map(o=>Math.round(Nf(e,o)*t+Nf(n,o)*(1-t)).toString(16).padStart(2,"0")).join("")}`,Mt=e=>Oc(e.canvas)<.18?"dark":"light",Fg=(e,t,n,o,r=ci)=>{for(let i=.2;i<=1.0001;i+=.01)if(Yo(e[n],st(e[t],i,o))>=r)return Math.round(i*100)/100;return 1},Bl=(e,t,n,o,r)=>{for(let i=.2;i<=1.0001;i+=.01){const a=st(e[t],i,o);if(Yo(e[n],st(e.ink,r,a))>=(n==="inkDim"?Lg:ci))return Math.round(i*100)/100}return 1},X1=(e,t)=>st(e.ink,t,e.borderControl);function J1(e,t){const n={};for(const o of["dark","light"]){let r=0;for(const i of Object.keys(yn))for(const{palette:a}of t){if(Mt(a)!==o)continue;const c=st(a.canvas,e[i][o].canvas,Ln(yn[i][o]));let l=.01;for(;l<1&&fe(st(a.ink,l,c),c)<Ng;)l=Math.round((l+.01)*100)/100;r=Math.max(r,l)}n[o]=Math.round(r*100)/100}return n}function Q1(e,t=Dg){const n={};for(const[o,r]of Object.entries(yn)){n[o]={};for(const i of["dark","light"]){n[o][i]={};for(const a of Fl){let c=0;for(const{palette:l}of e)if(Mt(l)===i)for(const d of $s)c=Math.max(c,Fg(l,a,d,Ln(r[i])),...Object.values(t).map(u=>Bl(l,a,d,Ln(r[i]),u)));n[o][i][a]=Math.min(1,Math.round((c+.02)*100)/100)}}}return n}function q1(e){const t={};for(const n of["dark","light"]){let o=0;for(const{palette:r}of e){if(Mt(r)!==n)continue;const i=n==="dark"?"#ffffff":"#000000";for(const a of $s)o=Math.max(o,Fg(r,"elevated",a,i,a==="inkDim"?Lg:ci))}t[n]=Math.round(o*100)/100}return t}function Ug(e,t){let n=1;for(const o of Object.keys(e))n=Math.min(n,e[o][t]?.canvas??1);return n}function Bg(e,t,n,o){const r=o==="dark"?"#ffffff":"#000000";return st(e.elevated,t,st(e.canvas,Ug(n,o),r))}function eT(e,t){const n={};for(const o of["dark","light"]){const r=Ug(t,o),i=o==="dark"?"#ffffff":"#000000";let a=0;for(const{palette:c}of e){if(Mt(c)!==o)continue;const l=st(c.canvas,r,i);for(const d of["inkMuted","ink"]){let u=.2;for(;u<=1.0001&&!(Yo(c[d],st(c.elevated,u,l))>=ci);u+=.01);a=Math.max(a,Math.round(Math.min(u,1)*100)/100)}}n[o]=Math.round(a*100)/100}return n}function tT(e,t,n){const o={};for(const r of["dark","light"]){let i=0;for(const{palette:a}of e){if(Mt(a)!==r)continue;const c=Bg(a,n[r],t,r);for(const l of $g){let d=0;for(;d<=1.0001&&!(Yo(st(a.ink,d,a[l]),c)>=ci);d+=.05);i=Math.max(i,Math.round(Math.min(d,1)*100)/100)}}o[r]=Math.round(i*100)/100}return o}function nT(e,t,n){const o={};for(const r of["dark","light"]){const i=n[r],a=Math.max(Ul,i),c=[Math.round((a-.8*(a-i))*100)/100,i];let l=0;for(const{palette:d}of e)if(Mt(d)===r)for(const u of c){const f=Bg(d,u,t,r);let h=0;for(;h<=1.0001&&!(Yo(st(d.ink,h,d.hairline),f)>=V1);h+=.05);l=Math.max(l,Math.round(Math.min(h,1)*100)/100)}o[r]=Math.round(l*100)/100}return o}function oT(e,t){const n={};for(const[o,r]of Object.entries(yn)){n[o]={};for(const i of["dark","light"]){let a=0;for(const{palette:c}of t)if(Mt(c)===i)for(const l of Fl){const d=st(c[l],e[o][i][l],Ln(r[i]));let u=0;for(;u<1&&Yo(X1(c,u),d)<K1;)u=Math.round((u+.05)*100)/100;a=Math.max(a,u)}n[o][i]=Math.min(1,Math.round((a+.05)*100)/100)}}return n}const cr=new Map;function rT(e){const t=Mt(e),n=o=>Object.values(yn).every(r=>Fl.every(i=>$s.every(a=>Bl(e,i,a,Ln(r[t]),o)<=.95)));return Object.fromEntries(Object.entries(Dg).map(([o,r])=>{let i=r;for(;i>.01&&!n(i);)i=Math.round((i-.01)*100)/100;return[o,i]}))}function iT(e,t){const n=Mt(e);let o=J1(t,[{palette:e}])[n];const r=()=>Object.entries(yn).every(([i,a])=>Array.from({length:101},(c,l)=>{const d=t[i][n].canvas,u=Math.max(Ul,d),f=Math.round((u-l/100*(u-d))*100)/100,h=st(e.canvas,f,Ln(a[n]));return fe(st(e.ink,o,h),h)>=Ng}).every(Boolean));for(;o<1&&!r();)o=Math.round((o+.01)*100)/100;return{dark:0,light:0,[n]:o}}function sT(e,t){const n=Mt(e);for(const o of Y1)for(let r=5;r<=104;r++){const i=r/100;if(Object.entries(yn).every(([c,l])=>Array.from({length:101},(d,u)=>{const f=t[c][n].canvas,h=Math.max(Ul,f),_=Math.round((h-u/100*(h-f))*100)/100,y=Math.round(_*i*100)/100;if(y>1)return!1;const v=st(e.canvas,_,Ln(l[n]));return fe(st(e[o],y,v),v)>=Z1}).every(Boolean)))return{dark:{role:o,scale:i},light:{role:o,scale:i}}}return null}function aT(e,t){const n=Mt(e);for(;;){const o=iT(e,t);let r=!1;for(const[i,a]of Object.entries(yn)){const c=Math.min(1,Math.round((Math.max(...$s.map(l=>Bl(e,"canvas",l,Ln(a[n]),o[n])))+.02)*100)/100);c>t[i][n].canvas&&(t[i][n].canvas=c,r=!0)}if(!r)return o}}const cT=["canvas","surface","elevated","sunken","ink","inkMuted","inkDim","borderControl","hairline",...$g];function lT(e){for(const t of cT){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 iL(e){lT(e);const t=JSON.stringify(e),n=cr.get(t);if(n)return n;const o=[{palette:e}],r=rT(e),i=Q1(o,r);let a,c;for(let u=0;u<=99;u++){let f=!1;for(const h of Object.keys(yn)){const _=Mt(e),y=i[h][_].canvas,v=Math.max(y,u/100);f||=v!==y,i[h][_].canvas=v}if(!(u>0&&!f)&&(a=aT(e,i),c=sT(e,i),c))break}if(!c)throw new Error("palette roles cannot form a readable transparent lane");const l=eT(o,i),d={alphaFloor:i,blockVeil:a,laneWash:c,controlMix:oT(i,o),bandFloor:q1(o),overlayFloor:l,overlayInkMix:tT(o,i,l),overlayEdgeMix:nT(o,i,l),stateAlpha:r};return cr.set(t,d),cr.size>8&&cr.delete(cr.keys().next().value),d}const Pc=new WeakMap,dT=(e,t)=>{t?Pc.set(e,t):Pc.delete(e)},sL=e=>Pc.get(e);/**
|
|
47
|
+
* @remix-run/router v1.23.0
|
|
48
|
+
*
|
|
49
|
+
* Copyright (c) Remix Software Inc.
|
|
50
|
+
*
|
|
51
|
+
* This source code is licensed under the MIT license found in the
|
|
52
|
+
* LICENSE.md file in the root directory of this source tree.
|
|
53
|
+
*
|
|
54
|
+
* @license MIT
|
|
55
|
+
*/function Jr(){return Jr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},Jr.apply(this,arguments)}var Tn;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Tn||(Tn={}));const Lf="popstate";function aL(e){e===void 0&&(e={});function t(r,i){let{pathname:a="/",search:c="",hash:l=""}=lo(r.location.hash.substr(1));return!a.startsWith("/")&&!a.startsWith(".")&&(a="/"+a),Mc("",{pathname:a,search:c,hash:l},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function n(r,i){let a=r.document.querySelector("base"),c="";if(a&&a.getAttribute("href")){let l=r.location.href,d=l.indexOf("#");c=d===-1?l:l.slice(0,d)}return c+"#"+(typeof i=="string"?i:Hg(i))}function o(r,i){Hl(r.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(i)+")")}return fT(t,n,o,e)}function Ye(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Hl(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function uT(){return Math.random().toString(36).substr(2,8)}function Ff(e,t){return{usr:e.state,key:e.key,idx:t}}function Mc(e,t,n,o){return n===void 0&&(n=null),Jr({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?lo(t):t,{state:n,key:t&&t.key||o||uT()})}function Hg(e){let{pathname:t="/",search:n="",hash:o=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),o&&o!=="#"&&(t+=o.charAt(0)==="#"?o:"#"+o),t}function lo(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let o=e.indexOf("?");o>=0&&(t.search=e.substr(o),e=e.substr(0,o)),e&&(t.pathname=e)}return t}function fT(e,t,n,o){o===void 0&&(o={});let{window:r=document.defaultView,v5Compat:i=!1}=o,a=r.history,c=Tn.Pop,l=null,d=u();d==null&&(d=0,a.replaceState(Jr({},a.state,{idx:d}),""));function u(){return(a.state||{idx:null}).idx}function f(){c=Tn.Pop;let b=u(),p=b==null?null:b-d;d=b,l&&l({action:c,location:v.location,delta:p})}function h(b,p){c=Tn.Push;let A=Mc(v.location,b,p);n&&n(A,b),d=u()+1;let k=Ff(A,d),M=v.createHref(A);try{a.pushState(k,"",M)}catch(P){if(P instanceof DOMException&&P.name==="DataCloneError")throw P;r.location.assign(M)}i&&l&&l({action:c,location:v.location,delta:1})}function _(b,p){c=Tn.Replace;let A=Mc(v.location,b,p);n&&n(A,b),d=u();let k=Ff(A,d),M=v.createHref(A);a.replaceState(k,"",M),i&&l&&l({action:c,location:v.location,delta:0})}function y(b){let p=r.location.origin!=="null"?r.location.origin:r.location.href,A=typeof b=="string"?b:Hg(b);return A=A.replace(/ $/,"%20"),Ye(p,"No window.location.(origin|href) available to create URL for href: "+A),new URL(A,p)}let v={get action(){return c},get location(){return e(r,a)},listen(b){if(l)throw new Error("A history only accepts one active listener");return r.addEventListener(Lf,f),l=b,()=>{r.removeEventListener(Lf,f),l=null}},createHref(b){return t(r,b)},createURL:y,encodeLocation(b){let p=y(b);return{pathname:p.pathname,search:p.search,hash:p.hash}},push:h,replace:_,go(b){return a.go(b)}};return v}var Uf;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Uf||(Uf={}));function pT(e,t,n){return n===void 0&&(n="/"),hT(e,t,n)}function hT(e,t,n,o){let r=typeof t=="string"?lo(t):t,i=zg(r.pathname||"/",n);if(i==null)return null;let a=Wg(e);mT(a);let c=null;for(let l=0;c==null&&l<a.length;++l){let d=RT(i);c=ET(a[l],d)}return c}function Wg(e,t,n,o){t===void 0&&(t=[]),n===void 0&&(n=[]),o===void 0&&(o="");let r=(i,a,c)=>{let l={relativePath:c===void 0?i.path||"":c,caseSensitive:i.caseSensitive===!0,childrenIndex:a,route:i};l.relativePath.startsWith("/")&&(Ye(l.relativePath.startsWith(o),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+o+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(o.length));let d=On([o,l.relativePath]),u=n.concat(l);i.children&&i.children.length>0&&(Ye(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),Wg(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:kT(d,i.index),routesMeta:u})};return e.forEach((i,a)=>{var c;if(i.path===""||!((c=i.path)!=null&&c.includes("?")))r(i,a);else for(let l of Gg(i.path))r(i,a,l)}),t}function Gg(e){let t=e.split("/");if(t.length===0)return[];let[n,...o]=t,r=n.endsWith("?"),i=n.replace(/\?$/,"");if(o.length===0)return r?[i,""]:[i];let a=Gg(o.join("/")),c=[];return c.push(...a.map(l=>l===""?i:[i,l].join("/"))),r&&c.push(...a),c.map(l=>e.startsWith("/")&&l===""?"/":l)}function mT(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:ST(t.routesMeta.map(o=>o.childrenIndex),n.routesMeta.map(o=>o.childrenIndex)))}const gT=/^:[\w-]+$/,_T=3,bT=2,vT=1,yT=10,wT=-2,Bf=e=>e==="*";function kT(e,t){let n=e.split("/"),o=n.length;return n.some(Bf)&&(o+=wT),t&&(o+=bT),n.filter(r=>!Bf(r)).reduce((r,i)=>r+(gT.test(i)?_T:i===""?vT:yT),o)}function ST(e,t){return e.length===t.length&&e.slice(0,-1).every((o,r)=>o===t[r])?e[e.length-1]-t[t.length-1]:0}function ET(e,t,n){let{routesMeta:o}=e,r={},i="/",a=[];for(let c=0;c<o.length;++c){let l=o[c],d=c===o.length-1,u=i==="/"?t:t.slice(i.length)||"/",f=IT({path:l.relativePath,caseSensitive:l.caseSensitive,end:d},u),h=l.route;if(!f)return null;Object.assign(r,f.params),a.push({params:r,pathname:On([i,f.pathname]),pathnameBase:OT(On([i,f.pathnameBase])),route:h}),f.pathnameBase!=="/"&&(i=On([i,f.pathnameBase]))}return a}function IT(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,o]=AT(e.path,e.caseSensitive,e.end),r=t.match(n);if(!r)return null;let i=r[0],a=i.replace(/(.)\/+$/,"$1"),c=r.slice(1);return{params:o.reduce((d,u,f)=>{let{paramName:h,isOptional:_}=u;if(h==="*"){let v=c[f]||"";a=i.slice(0,i.length-v.length).replace(/(.)\/+$/,"$1")}const y=c[f];return _&&!y?d[h]=void 0:d[h]=(y||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:a,pattern:e}}function AT(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Hl(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 o=[],r="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,c,l)=>(o.push({paramName:c,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(o.push({paramName:"*"}),r+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?r+="\\/*$":e!==""&&e!=="/"&&(r+="(?:(?=\\/|$))"),[new RegExp(r,t?void 0:"i"),o]}function RT(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Hl(!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 zg(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,o=e.charAt(n);return o&&o!=="/"?null:e.slice(n)||"/"}function xT(e,t){t===void 0&&(t="/");let{pathname:n,search:o="",hash:r=""}=typeof e=="string"?lo(e):e;return{pathname:n?n.startsWith("/")?n:TT(n,t):t,search:PT(o),hash:MT(r)}}function TT(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(r=>{r===".."?n.length>1&&n.pop():r!=="."&&n.push(r)}),n.length>1?n.join("/"):"/"}function Ma(e,t,n,o){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(o)+"]. 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 CT(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Wl(e,t){let n=CT(e);return t?n.map((o,r)=>r===n.length-1?o.pathname:o.pathnameBase):n.map(o=>o.pathnameBase)}function Gl(e,t,n,o){o===void 0&&(o=!1);let r;typeof e=="string"?r=lo(e):(r=Jr({},e),Ye(!r.pathname||!r.pathname.includes("?"),Ma("?","pathname","search",r)),Ye(!r.pathname||!r.pathname.includes("#"),Ma("#","pathname","hash",r)),Ye(!r.search||!r.search.includes("#"),Ma("#","search","hash",r)));let i=e===""||r.pathname==="",a=i?"/":r.pathname,c;if(a==null)c=n;else{let f=t.length-1;if(!o&&a.startsWith("..")){let h=a.split("/");for(;h[0]==="..";)h.shift(),f-=1;r.pathname=h.join("/")}c=f>=0?t[f]:"/"}let l=xT(r,c),d=a&&a!=="/"&&a.endsWith("/"),u=(i||a===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(d||u)&&(l.pathname+="/"),l}const On=e=>e.join("/").replace(/\/\/+/g,"/"),OT=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),PT=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,MT=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function jT(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Kg=["post","put","patch","delete"];new Set(Kg);const $T=["get",...Kg];new Set($T);/**
|
|
56
|
+
* React Router v6.30.0
|
|
57
|
+
*
|
|
58
|
+
* Copyright (c) Remix Software Inc.
|
|
59
|
+
*
|
|
60
|
+
* This source code is licensed under the MIT license found in the
|
|
61
|
+
* LICENSE.md file in the root directory of this source tree.
|
|
62
|
+
*
|
|
63
|
+
* @license MIT
|
|
64
|
+
*/function Qr(){return Qr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},Qr.apply(this,arguments)}const zl=x.createContext(null),DT=x.createContext(null),uo=x.createContext(null),Ds=x.createContext(null),wn=x.createContext({outlet:null,matches:[],isDataRoute:!1}),Vg=x.createContext(null);function cL(e,t){let{relative:n}=t===void 0?{}:t;Xo()||Ye(!1);let{basename:o,navigator:r}=x.useContext(uo),{hash:i,pathname:a,search:c}=FT(e,{relative:n}),l=a;return o!=="/"&&(l=a==="/"?o:On([o,a])),r.createHref({pathname:l,search:c,hash:i})}function Xo(){return x.useContext(Ds)!=null}function Ns(){return Xo()||Ye(!1),x.useContext(Ds).location}function Zg(e){x.useContext(uo).static||x.useLayoutEffect(e)}function NT(){let{isDataRoute:e}=x.useContext(wn);return e?JT():LT()}function LT(){Xo()||Ye(!1);let e=x.useContext(zl),{basename:t,future:n,navigator:o}=x.useContext(uo),{matches:r}=x.useContext(wn),{pathname:i}=Ns(),a=JSON.stringify(Wl(r,n.v7_relativeSplatPath)),c=x.useRef(!1);return Zg(()=>{c.current=!0}),x.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){o.go(d);return}let f=Gl(d,JSON.parse(a),i,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:On([t,f.pathname])),(u.replace?o.replace:o.push)(f,u.state,u)},[t,o,a,i,e])}function lL(){let{matches:e}=x.useContext(wn),t=e[e.length-1];return t?t.params:{}}function FT(e,t){let{relative:n}=t===void 0?{}:t,{future:o}=x.useContext(uo),{matches:r}=x.useContext(wn),{pathname:i}=Ns(),a=JSON.stringify(Wl(r,o.v7_relativeSplatPath));return x.useMemo(()=>Gl(e,JSON.parse(a),i,n==="path"),[e,a,i,n])}function UT(e,t){return BT(e,t)}function BT(e,t,n,o){Xo()||Ye(!1);let{navigator:r,static:i}=x.useContext(uo),{matches:a}=x.useContext(wn),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=Ns(),f;if(t){var h;let p=typeof t=="string"?lo(t):t;d==="/"||(h=p.pathname)!=null&&h.startsWith(d)||Ye(!1),f=p}else f=u;let _=f.pathname||"/",y=_;if(d!=="/"){let p=d.replace(/^\//,"").split("/");y="/"+_.replace(/^\//,"").split("/").slice(p.length).join("/")}let v=pT(e,{pathname:y}),b=KT(v&&v.map(p=>Object.assign({},p,{params:Object.assign({},l,p.params),pathname:On([d,r.encodeLocation?r.encodeLocation(p.pathname).pathname:p.pathname]),pathnameBase:p.pathnameBase==="/"?d:On([d,r.encodeLocation?r.encodeLocation(p.pathnameBase).pathname:p.pathnameBase])})),a,n,o);return t&&b?x.createElement(Ds.Provider,{value:{location:Qr({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:Tn.Pop}},b):b}function HT(){let e=XT(),t=jT(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r={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:r},n):null,null)}const WT=x.createElement(HT,null);class GT 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(wn.Provider,{value:this.props.routeContext},x.createElement(Vg.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function zT(e){let{routeContext:t,match:n,children:o}=e,r=x.useContext(zl);return r&&r.static&&r.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=n.route.id),x.createElement(wn.Provider,{value:t},o)}function KT(e,t,n,o){var r;if(t===void 0&&(t=[]),n===void 0&&(n=null),o===void 0&&(o=null),e==null){var i;if(!n)return null;if(n.errors)e=n.matches;else if((i=o)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,c=(r=n)==null?void 0:r.errors;if(c!=null){let u=a.findIndex(f=>f.route.id&&c?.[f.route.id]!==void 0);u>=0||Ye(!1),a=a.slice(0,Math.min(a.length,u+1))}let l=!1,d=-1;if(n&&o&&o.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:_}=n,y=f.route.loader&&h[f.route.id]===void 0&&(!_||_[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 _,y=!1,v=null,b=null;n&&(_=c&&f.route.id?c[f.route.id]:void 0,v=f.route.errorElement||WT,l&&(d<0&&h===0?(QT("route-fallback"),y=!0,b=null):d===h&&(y=!0,b=f.route.hydrateFallbackElement||null)));let p=t.concat(a.slice(0,h+1)),A=()=>{let k;return _?k=v:y?k=b:f.route.Component?k=x.createElement(f.route.Component,null):f.route.element?k=f.route.element:k=u,x.createElement(zT,{match:f,routeContext:{outlet:u,matches:p,isDataRoute:n!=null},children:k})};return n&&(f.route.ErrorBoundary||f.route.errorElement||h===0)?x.createElement(GT,{location:n.location,revalidation:n.revalidation,component:v,error:_,children:A(),routeContext:{outlet:null,matches:p,isDataRoute:!0}}):A()},null)}var Yg=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Yg||{}),Xg=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}(Xg||{});function VT(e){let t=x.useContext(zl);return t||Ye(!1),t}function ZT(e){let t=x.useContext(DT);return t||Ye(!1),t}function YT(e){let t=x.useContext(wn);return t||Ye(!1),t}function Jg(e){let t=YT(),n=t.matches[t.matches.length-1];return n.route.id||Ye(!1),n.route.id}function XT(){var e;let t=x.useContext(Vg),n=ZT(),o=Jg();return t!==void 0?t:(e=n.errors)==null?void 0:e[o]}function JT(){let{router:e}=VT(Yg.UseNavigateStable),t=Jg(Xg.UseNavigateStable),n=x.useRef(!1);return Zg(()=>{n.current=!0}),x.useCallback(function(r,i){i===void 0&&(i={}),n.current&&(typeof r=="number"?e.navigate(r):e.navigate(r,Qr({fromRouteId:t},i)))},[e,t])}const Hf={};function QT(e,t,n){Hf[e]||(Hf[e]=!0)}function dL(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function uL(e){let{to:t,replace:n,state:o,relative:r}=e;Xo()||Ye(!1);let{future:i,static:a}=x.useContext(uo),{matches:c}=x.useContext(wn),{pathname:l}=Ns(),d=NT(),u=Gl(t,Wl(c,i.v7_relativeSplatPath),l,r==="path"),f=JSON.stringify(u);return x.useEffect(()=>d(JSON.parse(f),{replace:n,state:o,relative:r}),[d,f,r,n,o]),null}function qT(e){Ye(!1)}function fL(e){let{basename:t="/",children:n=null,location:o,navigationType:r=Tn.Pop,navigator:i,static:a=!1,future:c}=e;Xo()&&Ye(!1);let l=t.replace(/^\/*/,"/"),d=x.useMemo(()=>({basename:l,navigator:i,static:a,future:Qr({v7_relativeSplatPath:!1},c)}),[l,c,i,a]);typeof o=="string"&&(o=lo(o));let{pathname:u="/",search:f="",hash:h="",state:_=null,key:y="default"}=o,v=x.useMemo(()=>{let b=zg(u,l);return b==null?null:{location:{pathname:b,search:f,hash:h,state:_,key:y},navigationType:r}},[l,u,f,h,_,y,r]);return v==null?null:x.createElement(uo.Provider,{value:d},x.createElement(Ds.Provider,{children:n,value:v}))}function pL(e){let{children:t,location:n}=e;return UT(jc(t),n)}new Promise(()=>{});function jc(e,t){t===void 0&&(t=[]);let n=[];return x.Children.forEach(e,(o,r)=>{if(!x.isValidElement(o))return;let i=[...t,r];if(o.type===x.Fragment){n.push.apply(n,jc(o.props.children,i));return}o.type!==qT&&Ye(!1),!o.props.index||!o.props.children||Ye(!1);let a={id:o.props.id||i.join("-"),caseSensitive:o.props.caseSensitive,element:o.props.element,Component:o.props.Component,index:o.props.index,path:o.props.path,loader:o.props.loader,action:o.props.action,errorElement:o.props.errorElement,ErrorBoundary:o.props.ErrorBoundary,hasErrorBoundary:o.props.ErrorBoundary!=null||o.props.errorElement!=null,shouldRevalidate:o.props.shouldRevalidate,handle:o.props.handle,lazy:o.props.lazy};o.props.children&&(a.children=jc(o.props.children,i)),n.push(a)}),n}const Ls=260,Kl=220,Vl=560,Qg=56,Zl=480,hL=8,Yl=44,Xl=400,qg=1200;function Jl(e){return Math.max(0,Math.min(qg,e-Zl))}function $c(e){return Jl(e)>=Xl?"docked":"overlay"}const eC=48,tC=16;function mL(e,t){if($c(e)==="docked")return{mode:"docked",width:Math.min(t,Jl(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,Xl),e-eC));return e-n>=tC?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function gL({capacity:e,min:t,max:n,drawn:o}){const r=e>=t;return r?{resizable:r,value:Math.min(Math.max(o,t),e),minWidth:t,maxWidth:Math.min(n,e)}:{resizable:r,value:o,minWidth:o,maxWidth:o}}function nC(e,t=Ls,n=Yl){return $c(e-e_(t)-n)==="overlay"&&$c(e-Qg-n)==="docked"}function e_(e){return Number.isNaN(e)?Ls:Math.min(Vl,Math.max(Kl,e))}function oC(e,t=Yl){return Math.max(0,Math.min(Vl,e-Zl-t))}function _L(e,t,n=Ls,o=!1,r=Yl){const i=!t&&o&&nC(e,n,r),a=t||i,c=oC(e,r);return{mode:a?"strip":"docked",width:a?Qg:Math.min(e_(n),c),collapsed:a,resizable:!a&&c>=Kl}}function bL(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const vL=e=>e?"⌘B":"Ctrl+B",rC="data-canvas-shortcuts",iC=`[${rC}]`,sC=e=>t_(e,iC),aC='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',yL=e=>t_(e,aC);function t_(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const wL=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&sC(e.target)?"new-file":null},n_="small",cC=["small","medium","large"],o_="before:absolute before:-inset-0.5 before:content-['']",lC={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:o_},medium:{px:28,className:"size-7",glyphClassName:"size-3.5",hitClassName:""},large:{px:36,className:"size-9",glyphClassName:"size-4",hitClassName:""}},dC={small:{px:4,className:"mb-1"},medium:{px:6,className:"mb-1.5"},large:{px:8,className:"mb-2"}},kL={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:o_,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 SL(e){for(const t of cC)if(e===t)return t;return n_}function EL(e){return lC[e].px+dC[e].px}const r_="delegating",Oi=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,ja=e=>Math.max(1,Math.floor(e)),uC=e=>e===r_,i_=e=>e.locality==="remote"&&e.link_down===!0||e.peer_reach==="not-attempted"||e.peer_reach==="unknown";function Ql(e){return i_(e)?!1:typeof e.background_work=="boolean"?e.background_work:e.status?.code===r_}const fC=Intl.ListFormat;let $a=null;const pC=e=>{const t=sn();return $a?.tag!==t&&($a={tag:t,format:new fC(t,{type:"conjunction",style:"narrow"})}),$a.format.format(e)};function IL(e){if(i_(e))return"";const t=Ql(e);if(!t&&typeof e.background_work=="boolean")return"";const n=!uC(e.status?.code),o=[];n&&Oi(e.subagents_running)&&o.push(g("ui.chat.sidebar.row.bg.subagents",{count:ja(e.subagents_running)})),t&&Oi(e.jobs_running)&&o.push(g("ui.chat.sidebar.row.bg.jobs",{count:ja(e.jobs_running)}));const r=[];if(o.length>0&&r.push(g("ui.chat.sidebar.row.bg.running",{items:pC(o)})),n&&Oi(e.subagents_queued)){const i=ja(e.subagents_queued);r.push(o.length>0?g("ui.chat.sidebar.row.bg.queued",{count:i}):g("ui.chat.sidebar.row.bg.subagents_queued",{count:i}))}return t&&r.length===0&&e.status?.code!=="waiting"&&Oi(e.waiting_on)&&r.push(g("ui.chat.sidebar.row.bg.waiting")),r.join(" · ")}const hC=new Set(["idle","recent"]);function AL(e,t){return t!==""&&hC.has(e.status?.code??"recent")&&Ql(e)}const mC=["active","created"],RL={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"},gC=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function Fs(e){return gC.has(e.status?.code??"")||Ql(e)}const _C=new Set(["approval","answer"]);function s_(e){return _C.has(e.status?.code??"")}const bC=24*60*60*1e3,vC=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function ql(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 yC="last_user_at";function wC(e){const t=e[yC],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 kC(e,t,n){if(Fs(e))return"running";const o=ql(e,n);if(o===null)return"older";const r=vC(t);return o>=r?"today":o>=r-6*bC?"week":"older"}function xL(e,t,n){const o={running:[],today:[],week:[],older:[]};for(const r of e)o[kC(r,t,n)].push(r);return o}function a_(e,t,n){const o=ql(e,n);if(o===null)return null;const r=Math.floor(Math.max(0,t-o)/6e4);if(r<1)return{unit:"now",count:0};if(r<60)return{unit:"minute",count:r};const i=Math.floor(r/60);if(i<24)return{unit:"hour",count:i};const a=Math.floor(i/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 TL(e,t,n){const o=a_(e,t,n);return o?g("ui.chat.sidebar_view.relative_short",o):""}function CL(e,t,n){const o=a_(e,t,n);return o?n==="created"?g("ui.chat.sidebar_view.relative_created",o):g("ui.chat.sidebar_view.relative_active",o):""}const Dc=["pinned","running","today","week","older","agents","teams"],OL={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 PL(e){return e==="agents"||e==="teams"}const qr=8;function SC(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function ML(e,t){return{...e,[t]:(e[t]??qr)+qr}}function jL(e,t,n,o,r){const i=!(e[n]??o);return{expanded:{...e,[n]:i},caps:!i&&!r?SC(t,n):t}}function c_(e){return`tag:${e}`}function l_(e,t){return e[c_(t)]===!1}function $L(e,t){const n=c_(t);if(l_(e,t)){const{[n]:o,...r}=e;return r}return{...e,[n]:!1}}function DL(e,t,n){return l_(t,n)?[]:e}function NL(e,t,n,o){return(e||t!=="")&&(o>qr||n.trim()!=="")}const LL="Collapse, then reopen, to restore the compact list";function FL(e){return(e??qr)>qr}const UL=e=>`section-grown-hint-${e}`,BL=e=>g("ui.chat.sidebar.catalogue.show_more",{hidden:e});function HL(e,t){return t==="agents"?g("ui.chat.sidebar.catalogue.show_more_agents",{count:e}):g("ui.chat.sidebar.catalogue.show_more_teams",{count:e})}function WL(e,t){return e.groupBy==="tag"&&!t?"section":e.groupBy}function GL(e){return e.tagsEnabled||e.groupBy==="tag"}const Io={hidden:[],order:[...Dc],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},EC=10,lr=[25,50],IC=50,AC=500,RC=64,xC=2;function zL(e){return e.groupBy==="tag"?Math.max(e.loads,xC):e.loads}function Bo(e){const t=Math.max(0,Math.floor(e));return t===0?EC:t<=lr.length?lr[t-1]:lr[lr.length-1]+(t-lr.length)*IC}function KL(e,t){const n=Bo(e+1)-Bo(e),o=Math.max(0,Math.min(n,t));return g("ui.chat.sidebar.catalogue.show_more_chats",{add:o})}function VL(e,t,n){const o=Bo(t+1)-Bo(t),r=Bo(t),i=Math.min(r+o,e.length);let a=0;for(let l=r;l<i;l+=1)Us(e[l])&&(a+=1);const c=Math.max(0,i-r-a);return c>0?c:Math.max(0,Math.min(o,n))}function ZL(e,t){if(!t)return null;const n=e.filter(o=>Us(o));return n.length===0?null:{row:n.find(o=>s_(o))??n[0],count:n.length}}function Us(e){return Fs(e)}function TC(e){return s_(e)?0:Fs(e)?1:2}function CC(e,t){return Fs(e)?wC(e):ql(e,t)}function OC(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function YL(e,t,n){const o=e.map((r,i)=>({row:r,index:i,lane:t==="active-first"?TC(r):0,at:CC(r,n)}));return o.sort((r,i)=>r.lane-i.lane||OC(r.at,i.at)||r.index-i.index),o.map(r=>r.row)}function XL(e,t){const{limit:n,currentId:o,searching:r=!1}=t;if(r)return{rows:[...e],lifted:!1,remaining:0};const i=[];let a=Math.max(0,n);for(const d of e){if(a>0){i.push(d),a-=1;continue}Us(d)&&i.push(d)}const c=Math.max(0,e.length-i.length);if(!o)return{rows:i,lifted:!1,remaining:c};const l=e.find(d=>d.session_id===o)??null;return l===null||i.includes(l)?{rows:i,lifted:!1,remaining:c}:{rows:[l,...i],lifted:!0,remaining:c}}function JL(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=Bo(t.loads),o=[];let r=n;for(const l of e){if(Us(l)){o.push(l);continue}r>0&&(o.push(l),r-=1)}const i=t.currentId,a=i==null?null:e.find(l=>l.session_id===i)??null,c=a!==null&&!o.includes(a);return{rows:c&&a!==null?[a,...o]:o,lifted:c,hidden:e.length-o.length-(c?1:0),held:e.length}}function QL(e){if(e.add<=0)return null;const t=g("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 PC="mt-4",MC="mt-2";function qL(e){return e?PC:MC}function eF(e,t,n,o){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(o??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function tF(e,t){if(t==="section"||t==="tag")return null;if(t==="flat")return[{key:"all",label:"",rows:[...e]}];const n=new Map;for(const i of e){const a=i.binding?.team||i.binding?.agent||"",c=a||"ungrouped",l=n.get(c)??{key:c,label:a||g("ui.chat.sidebar_view.ungrouped"),rows:[]};l.rows.push(i),n.set(c,l)}const o=[...n.values()],r=o.findIndex(i=>i.key==="ungrouped");return r>0&&o.push(...o.splice(r,1)),o}function jC(e,t){return!e.hidden.includes(t)}function d_(e){return e.order.filter(t=>jC(e,t))}function nF(e,t){const n=e.hidden.includes(t)?e.hidden.filter(o=>o!==t):[...e.hidden,t];return{...e,hidden:n}}function oF(e,t,n){const o=d_(e),r=o.indexOf(t),i=o[r+n];if(r<0||i===void 0)return e;const a=e.order.indexOf(t),c=e.order.indexOf(i),l=[...e.order];return l[a]=i,l[c]=t,{...e,order:l}}const $C=["running","today","week","older"];function Wf(e){return $C.includes(e)}function rF(e,t,n,o){if(!Wf(t)||o&&!o(t))return!1;const r=d_(e),i=r.indexOf(t);if(i<0)return!1;const a=r[i+n];return a===void 0||!Wf(a)?!1:o?o(a):!0}const DC=["section","tag","agent","flat"],NC=["active-first","recent"];function iF(e){if(typeof e!="object"||e===null)return Io;const t=e,n=new Set(Dc),o=[];if(Array.isArray(t.order))for(const h of t.order)typeof h=="string"&&n.has(h)&&(o.includes(h)||o.push(h));for(const h of Dc)o.includes(h)||o.push(h);const r=[];if(Array.isArray(t.hidden))for(const h of t.hidden)typeof h=="string"&&n.has(h)&&(r.includes(h)||r.push(h));const i=DC.includes(t.groupBy)?t.groupBy:Io.groupBy,a=mC.includes(t.basis)?t.basis:Io.basis,c=NC.includes(t.orderBy)?t.orderBy:Io.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(AC,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>=RC)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:r,order:o,groupBy:i,tagsEnabled:typeof t.tagsEnabled=="boolean"?t.tagsEnabled:!1,autoTagForks:typeof t.autoTagForks=="boolean"?t.autoTagForks:Io.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const u_={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},LC=["recent","name","kind","modified","created","size"],FC=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function ed(e){const t=e&&typeof e=="object"?e:{};return{sort:LC.includes(t.sort??"")?t.sort:u_.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=>[ei,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>FC.includes(n)))]:[]}}const ei="Attachments";function sF(e,t){const n=o=>{switch(t.sort){case"name":return o.row.name;case"kind":return`${o.row.kind}\0${o.row.name}`;case"modified":return o.modified;case"created":return o.created;case"size":return o.row.document.sizeBytes??null;default:return o.mentioned}};return[...e].sort((o,r)=>{const i=n(o),a=n(r);if(i===null||a===null)return i===a?0:i===null?1:-1;const c=typeof i=="string"&&typeof a=="string"?i.localeCompare(a,void 0,{numeric:!0}):Number(i)-Number(a);return(t.order==="asc"?c:-c)||o.mentioned-r.mentioned})}const UC=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 aF(e,t,n,o,r=[]){const i=e.filter(l=>l.highlighted),a=e.filter(l=>!l.highlighted),c=[];if(r.length&&c.push({id:ei,label:g("ui.canvas.files.attachments"),items:r,open:n||!o.has(ei),highlights:!1}),i.length&&c.push({id:"Highlights",label:g("ui.canvas.finder_layout.highlights"),items:i,open:n||!o.has("Highlights"),highlights:!0}),i.length&&a.length&&(c.push({id:"Working files",label:g("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:g("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=>UC(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!o.has(l),highlights:!1})}return c}const BC=32,cF=4,f_=32,p_=18;function lF(e){return e.height-f_-(e.kind==="tiles"&&e.section.id===ei?p_:0)}function dF(e,t,n){const o=[],r=new Map,i=Math.max(136,t-16),a=Math.max(1,Math.floor((i+4)/140));let c=0;const l=(d,u,f,h,_=1)=>{h.forEach((y,v)=>r.set(y.row.document.id,{band:o.length,column:v})),o.push({section:d,kind:u,height:f,top:c,items:h,cols:_}),c+=f};for(const d of e)if(l(d,"header",BC,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(d.id===ei){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=(i-4*(a-1))/a,_=Math.round((h-8)*3/4)+f_+p_;for(let y=0;y<f.length;y+=a)l(d,"tiles",_,f.slice(y,y+a),a)}else if(n&&d.id==="Images"){const u=(i-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((i-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:o,height:c,columns:a,positions:r}}function uF(e,t,n,o){const r=Math.max(600,n*.75);let i=0,a=e.bands.length;for(;i<a;){const d=i+a>>>1,u=e.bands[d];u.top+u.height<t-r?i=d+1:a=d}const c=new Set;for(let d=i;d<e.bands.length&&e.bands[d].top<=t+n+r;d++)c.add(d);const l=o?e.positions.get(o):null;return l&&c.add(l.band),[...c].sort((d,u)=>d-u)}function fF(e,t,n,o){const r=e.positions.get(t);if(!r)return null;const i=e.bands[r.band],a=e.bands.filter(u=>u.section.id===i.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 i.items[r.column+(n==="ArrowLeft"?-1:1)]?.row.document.id??null;const c=n==="ArrowUp"||n==="PageUp"?-1:1,l=i.top+(n.startsWith("Page")?o*c:c);let d=r.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(r.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 HC="both",h_="by-turn",WC=[{value:"by-turn"},{value:"by-response"}];function pF(e){for(const t of WC)if(e===t.value)return t.value;return h_}function hF(e){return e==="by-response"?g("ui.settings.appearance.transcript_display_mode_setting.by_response"):g("ui.settings.appearance.transcript_display_mode_setting.by_turn")}const mF="primary+alt+shift+space",GC=/^f([1-9]|1[0-9]|2[0-4])$/;function zC(e){return GC.test(e)}function KC(e,t){const n=VC(e,t);return t==="mac"?n.join(""):n.join("+")}function VC(e,t){const o=t==="mac"?{primary:"⌘",meta:"⌘",ctrl:"⌃",alt:"⌥",shift:"⇧"}:{primary:"Ctrl",meta:t==="win"?"Win":"Super",ctrl:"Ctrl",alt:"Alt",shift:"Shift"},r={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(i=>i.trim().toLowerCase()).filter(i=>i.length>0).map(i=>i in o?o[i]:i in r?r[i]:zC(i)||i.length===1?i.toUpperCase():i)}const Bs=[{id:"panel.console",get label(){return g("ui.settings.shortcuts.action.open_console")},get category(){return g("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return g("ui.settings.shortcuts.action.open_canvas")},get category(){return g("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return g("ui.settings.shortcuts.action.open_run_details")},get category(){return g("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return g("ui.settings.shortcuts.action.open_asks")},get category(){return g("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return g("ui.settings.shortcuts.action.open_browser")},get category(){return g("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return g("ui.settings.shortcuts.action.open_code_review")},get category(){return g("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.projects",get label(){return g("ui.settings.shortcuts.action.open_linked_projects")},get category(){return g("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],ZC=new Map(Bs.map(e=>[e.id,e])),YC=e=>ZC.get(e),XC=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}`),"primary+shift+n"]);class JC 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[o,r]of this)t.call(n,r,o,this)}[Symbol.iterator](){return this.entries()}}const td=new JC([["primary+p",()=>g("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>g("ui.settings.shortcuts.reserved.palette_commands")],["primary+k",()=>g("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>g("ui.settings.shortcuts.reserved.new_chat")],["primary+shift+n",()=>g("ui.settings.shortcuts.new_temporary_chat")],["primary+b",()=>g("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>g("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>g("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>g("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>g("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>g("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>g("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>g("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>g("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>g("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>g("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>g("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>g("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>g("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>g("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>g("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>g("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>g("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>g("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>g("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>g("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>g("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>g("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>g("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>g("ui.settings.shortcuts.reserved.browser_last_tab"):()=>g("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>g("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>g("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>g("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>g("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>g("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>g("ui.settings.shortcuts.reserved.close")],["primary+m",()=>g("ui.settings.shortcuts.reserved.minimise")]]),QC=["primary","alt","shift"],qC={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},eO=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),tO=e=>eO.has(e)||/^[a-z0-9]$/.test(e);function nd(e){if(typeof e!="string")return null;const t=e.toLowerCase().split("+").map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return null;const n=t[t.length-1];if(!tO(n))return null;const o=new Set;for(const i of t.slice(0,-1)){const a=qC[i];if(a===void 0)return null;o.add(a)}return[...QC.filter(i=>o.has(i)),n].join("+")}const m_=e=>e.split("+").includes("primary");function Hs(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!td.has(n)?n:YC(e)?.defaultChord??null}function gF(e){const t=new Map;for(const n of Bs){const o=Hs(n.id,e);o!==null&&!t.has(o)&&t.set(o,n.id)}return t}const nO=e=>e==="mac"?g("ui.settings.shortcuts.capture.needs_modifier_mac"):g("ui.settings.shortcuts.capture.needs_modifier");function oO(e,t,n,o="linux",r=new Map){const i=e===null?null:nd(e);if(i===null)return g("ui.settings.shortcuts.capture.unbindable");if(!m_(i))return nO(o);const a=td.get(i);if(a!==void 0)return a;const c=r.get(i);if(c!==void 0)return g("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of Bs)if(l.id!==t&&Hs(l.id,n)===i)return g("ui.settings.shortcuts.capture.already_assigned",{label:l.label});return null}function rO(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,o={};for(const r of Bs){const i=t[r.id];if(i===null){o[r.id]=null;continue}const a=typeof i=="string"?nd(i):null,c=a!==null&&XC.has(a),l=a!==null&&m_(a)&&(c||!td.has(a)&&!n.has(a))?a:null;l!==null&&(o[r.id]=l);const d=Hs(r.id,o);d!==null&&n.add(d)}return o}function _F(e,t,n){const o=Hs(e,t);return o===null?null:g_(o,n)}function g_(e,t){return KC(e,t)}function bF(e,t){const n=e.split("+"),o=n[n.length-1],r=n.slice(0,-1).map(i=>i==="primary"?t==="mac"?"Meta":"Control":i==="shift"?"Shift":i==="alt"?"Alt":i);return{glyph:g_(e,t),aria:[...r,o.length===1?o.toUpperCase():o].join("+")}}const Gf=e=>{for(const t of[e.role,...e.variants])if(!G_.includes(t))throw new Error(`Unknown accent role: ${t}`);return Object.freeze({...e,variants:Object.freeze(e.variants)})},__=Object.freeze([Gf({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"}),Gf({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"})]),vF=e=>__.some(t=>t.role===e||t.variants.includes(e)),je={strongText:7,text:4.5,nonText:3},zf=new Set(["inkDisabled"]),Ze=["canvas","surface","elevated","sunken"],b_=[["ink",je.strongText],["inkMuted",5.5],["inkDim",5]],hn=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Xt={dark:{canvasMin:9,canvasMax:15,elevatedMax:22},light:{canvasMax:94,sunkenMin:80}},An={canvasSurface:[2.5,5],surfaceElevated:[2,6],canvasSunken:[1.5,6]},iO=2,sO=1.03,od=8,ms=2,Kf=.8,Vf=3,Zf=2,Yf=4,Nc=2.5,Xf=4,Jf=2.5,Qf=2,qf=2,aO=[{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:Ze,fill:"accent",border:"accent",ink:"onAccent"},{name:"primary button (hover)",on:Ze,fill:"accentHover",border:"accentHover",ink:"onAccent"},{name:"primary button (pressed)",on:Ze,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:Ze,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:Ze,fill:"accentWash",border:null,ink:"inkMuted",edge:!1},{name:"input field",on:Ze,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:Ze,fill:"surface",border:"borderControl",ink:"ink"},{name:"browser file-transfer row (refused)",on:Ze,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:Ze,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}],cO=[{name:"context wheel arc against its track",a:["info","warning","danger"],b:"sunken",floor:je.nonText}],lO=[{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:Ze,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"}],dO=[{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}],uO=["borderControl","accent","successBorder","warningBorder","dangerBorder","infoBorder"],fO=["accent","success","warning","danger","info"],pO=[{fg:"surface",on:"accent",floor:je.text,name:"the console terminal's cursor ink on its own cursor (9.1)"}],hO=[],mO=[{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"}],Ao=15,Ro=8,gO=[{theme:"catppuccinMocha",a:"accentAlt",b:"info",floor:Ao,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:Ao,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:Ao,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:Ao,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:Ao,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:Ro,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:Ro,got:0,why:"`info` IS `accent` (`#00EFFF`), the palette's single cyan"},{theme:"obsidian",a:"info",b:"accent",floor:Ro,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:Ro,got:0,why:"`info` IS `accent` (`#91B7E9`), the palette's single steel blue"},{theme:"githubLight",a:"info",b:"accent",floor:Ro,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"}],_O=[],bO=[],vO=["mode",...Ze,"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"],Pi=["success","warning","danger","info"],yO=["success","warning","danger","info","ink"],Po=8,dr="tokenCommand",Mi=Po,wO=["surface","elevated","messageSurface"],kO=[{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."}],dn=15,ti=15,Ar=Po,ct=2,ep=4,SO=.75,tp=.12,np=.1,EO=[["surface","canvas"],["surface","elevated"],["elevated","canvas"]],IO=4,AO=2,RO=2,Da=1,gs=2,Na=2,op=.5,xO=1.5,TO=1.5,v_=5,_s=2.5,y_=.5,bs=5,Lc=4,Fc=24,rp=12,CO=.45,ip=.75,OO=.25,mn=2,w_=2,PO=[{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"}],MO=[{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,ji="surface",sp=2,ap=1.15,jO=({composed:e=!1,capturePairs:t=!1}={})=>{const n={assertions:0,failures:0,composed:e},o=[],r=(R,m)=>e?m>=R-.01:Math.abs(R-m)<.01,i=(R,m,w)=>e?m>=R-w:Math.abs(R-m)<=w,a=new Set,c=(R,m,w,S)=>{const T=mO.find(N=>N.theme===R&&N.role===m&&N.ground===w&&r(N.got,S));return T&&a.add(T),T},l=new Set,d=(R,m,w,S)=>{const T=gO.find(N=>N.theme===R&&N.a===m&&N.b===w&&r(N.got,S));return T&&l.add(T),T},u=new Set,f=new Set,h=new Set,_=(R,m,w)=>`${R} on ${m} in ${w}`,y=[],v=R=>{n.failures++,y.push(`FAIL ${R}`)},b=new Set,p=(R,m,w,S)=>{const T=hO.find(N=>N.theme===R&&N.fg===m&&N.bg===w&&r(N.got,S));return T&&b.add(T),T};return Object.assign(n,{readings:o,pinMatches:r,ledgerHolds:i,log:y,fail:v,exceptionSeen:b,perceptibleSeen:a,pairPinSeen:l,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:h,controlEdgeKey:_,pinClaims:new Set,findException:p,findPerceptibleException:c,findPairPin:d,assertPair:(R,m,w,S,T,N)=>{const Y=m[w],X=m[S];if(!H(Y)||!H(X))return;n.assertions++;const E=re(Y,X);if(t&&o.push({foreground:w,background:S,value:E,floor:T}),E>=T)return;const V=D(E);p(R,w,S,V)||v(`${R}: ${N} — ${w} ${Y} on ${S} ${X} = ${V}:1, need ${T}:1`)},assertIdentityPair:(R,m,w,S,T,N)=>{const Y=m[w],X=m[S];if(!H(Y)||!H(X))return;n.assertions++;const E=D(fe(Y,X));if(E>=T)return;const V=d(R,w,S,E);if(V){V.floor!==T&&v(`${R}: \`${w}\`/\`${S}\` is pinned at floor ${V.floor} but this assertion asks for ${T} — a pin records the bound it was granted under, so the pin and the floor have to be raised together`);return}v(`${R}: ${N} — \`${w}\` ${Y} and \`${S}\` ${X} are ΔE00 ${E} apart (need ${T}) — two roles a reader has to tell apart at this site cannot be one colour at two weights; move the palette value, or pin the palette in \`PAIR_PINS\` with the constraint that refuses it`)},floorUnreachablePin:(R,m)=>PO.find(S=>S.id===R&&S.role===m)??null,shortfallPin:(R,m,w)=>MO.find(T=>T.id===R&&T.role===m&&T.bound===w)??null}),n},$O=(e,t)=>{const{fail:n,assertPair:o,assertIdentityPair:r,findException:i,findPerceptibleException:a,floorUnreachablePin:c,shortfallPin:l,pinClaims:d,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:h,controlEdgeKey:_,pinMatches:y,ledgerHolds:v}=e;for(const{id:b,palette:p}of[t]){for(const m of vO)e.assertions++,m in p||n(`${b}: missing required role \`${m}\``);for(const[m,w]of b_)if(!zf.has(m))for(const S of hn)o(b,p,m,S,w,"body ink");for(let m=0;m<Ze.length;m++)for(let w=m+1;w<Ze.length;w++){const S=p[Ze[m]],T=p[Ze[w]];!H(S)||!H(T)||(e.assertions++,re(S,T)<1.03&&n(`${b}: grounds \`${Ze[m]}\` ${S} and \`${Ze[w]}\` ${T} are indistinguishable (${D(re(S,T))}:1) — elevation is a lightness step here, so they must differ`))}const A=[{role:"rowHover",castFloor:m=>Math.max(_s,y_*m),castCeiling:m=>Math.max(m,_s),stepFloor:xO,stepCeiling:null},{role:"rowSelected",castFloor:m=>Math.max(bs,m),castCeiling:m=>Math.min(Math.max(m+Lc,bs),Fc),stepFloor:TO,stepCeiling:v_}];for(const m of A){const w=m.role,S=p[w];if(!H(S))continue;const[T,N,Y]=se(S),[X,E,V]=se(p.surface),[,G,me]=se(p.accent),z=Math.hypot(G,me),ye=Math.hypot(E,V),be=Math.hypot(N,Y),Ce=m.castFloor(ye),$e=m.castCeiling(ye),_t=ye<mn;e.assertions++;const jt=ye>=mn?{name:"the panel's",hue:Math.atan2(V,E)}:z>=w_?{name:"`accent`'s",hue:Math.atan2(me,G)}:{name:"the panel's",hue:Math.atan2(V,E)},le=Math.atan2(Y,N),ke=Math.abs(((le-jt.hue)*180/Math.PI+540)%360-180);be>=mn&&ke>rp&&n(`${b}: \`${w}\` ${S} sits ${D(ke)} degrees off ${jt.name} hue (the limit is ${rp}) — 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 ${jt.name} and re-author the value at it`),e.assertions++,Ce>$e+1e-9?(d.add(`${b}:${w}:floor`),e.assertions++,c(b,w)||n(`${b}: \`${w}\` ${S} carries C* ${D(be)}, and its cast floor ${D(Ce)} is ABOVE its ceiling ${D($e)} — the panel's own cast is louder than this role is allowed to be, so the value has to sit at the ceiling and \`${b}\`'s \`${w}\` has to be in ROW_STATE_FLOOR_UNREACHABLE naming the constraint that refuses the floor (the flat cap, the rise, or the role's absolute term)`),e.assertions++,be<$e-ip&&n(`${b}: \`${w}\` ${S} carries C* ${D(be)} where its cast floor ${D(Ce)} is above its ceiling ${D($e)} — the floor cannot be held, but the CEILING is reachable and is what the ledger row promises this value sits at`)):be<Ce-CO&&n(`${b}: \`${w}\` ${S} carries C* ${D(be)}, under the cast floor ${D(Ce)} — 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++,be>$e+ip&&n(`${b}: \`${w}\` ${S} carries C* ${D(be)}, past the ${D($e)} 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 ${Fc}. Search the chroma back toward the panel and let the step and the pair's cast rank carry what the fill no longer can`),e.assertions++;const et=T-X,Ne=p.mode==="dark"?et:-et;if(Ne<m.stepFloor-1e-9&&n(`${b}: \`${w}\` ${S} sits ${D(Math.abs(et))} \`L*\` ${p.mode==="dark"?"above":"below"} \`surface\` ${p.surface}, so the step is ${p.mode==="dark"?"LIGHTER":"DARKER"}-by-${D(Ne)} where the floor is ${m.stepFloor} \`L*\` in the mode's raised direction — ΔE00 is a budget a chroma-only step can spend while moving the wrong way in lightness, and the three palettes that did exactly that were the same report answered twice`),m.stepCeiling!==null&&(e.assertions++,Ne>m.stepCeiling+OO+1e-9&&n(`${b}: \`${w}\` ${S} sits ${D(Ne)} \`L*\` from \`surface\`, past the ${m.stepCeiling} \`L*\` ceiling — every L* the row rises is ink headroom spent on the caps drawn inside it, so the step is taken as far as the inks allow and no further`)),w==="rowSelected"&&H(p.rowHover)){const[xe,pt,$t]=se(p.rowHover),bt=p.mode==="dark"?xe-X:X-xe,Jo=Math.hypot(pt,$t);if(e.assertions++,Ne<bt+Da-1e-9){const Fn=l(b,"rowSelected","rank");d.add(`${b}:rowSelected:rank`),e.assertions++,Fn?v(Fn.measured,Ne-bt,.05)||n(`${b}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Fn.measured} and the pair now ranks ${D(Ne-bt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${b}: \`rowSelected\` ${S} is ${D(Ne)} \`L*\` from \`surface\` where \`rowHover\` ${p.rowHover} is ${D(bt)} — the selection has to be at least ${Da} \`L*\` further out than the hover, or a reader scanning sees one mark at two strengths rather than two states. A palette that cannot reach it has its whole legal step consumed by the ink floors, and that is a ledger row rather than a relaxed floor`)}else!e.composed&&l(b,"rowSelected","rank")&&n(`${b}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — the pair ranks ${D(Ne-bt)} \`L*\`, clear of the ${Da} the row claims it misses. Remove the row`);e.assertions++,be<Jo+gs-1e-9&&n(`${b}: \`rowSelected\` ${S} carries C* ${D(be)} where \`rowHover\` ${p.rowHover} carries ${D(Jo)} — the selection has to carry at least ${gs} 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++,bt<op*Ne-1e-9&&n(`${b}: \`rowHover\` ${p.rowHover} takes ${D(bt)} \`L*\` of the ${D(Ne)} the selection takes (${Math.round(bt/Ne*100)}%), under the ${Math.round(op*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 Et=fe(S,p.surface);if(Et<ct-1e-9){const xe=l(b,w,"band");d.add(`${b}:${w}:band`),e.assertions++,xe?v(xe.measured,Et,.05)||n(`${b}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${xe.measured} and the palette now measures ${D(Et)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${b}: \`${w}\` ${S} is ΔE00 ${D(Et)} from \`surface\` ${p.surface} (the field floor is ${ct}) — below this the mark is not findable while scanning, which is the operator's report restated. The band this role used to be held to was 4.0 and is WITHDRAWN because a backdrop-faithful fill cannot reach it on lightness; this floor is what is left, and a palette that misses even it needs a ledger row with the floor that refuses it`)}else!e.composed&&l(b,w,"band")&&n(`${b}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${D(Et)} from \`surface\`, clear of the ${ct} the row claims it misses. Remove the row`);e.assertions++;const ge=fe(S,p.accentWash);if(!_t&&ge<Na){const xe=l(b,w,"wash");d.add(`${b}:${w}:wash`),e.assertions++,xe?v(xe.measured,ge,.05)||n(`${b}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${xe.measured} and the palette now measures ${D(ge)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${b}: \`${w}\` ${S} is ΔE00 ${D(ge)} from \`accentWash\` ${p.accentWash} (need ${Na}) — 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&&!_t&&l(b,w,"wash")&&n(`${b}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${D(ge)} from \`accentWash\`, clear of the ${Na} the row claims it misses. Remove the row`)}if(H(p.rowHover)&&H(p.rowSelected)){e.assertions++;const m=fe(p.rowSelected,p.rowHover),w=RO;m<w-1e-9&&n(`${b}: \`rowHover\` ${p.rowHover} and \`rowSelected\` ${p.rowSelected} are ΔE00 ${D(m)} apart (need ${w}) — the reader sees two marks and cannot rank them. This was the second half of the operator's report: on \`neon\` the shipped pair sat 1.80 ΔE apart while each was ~6.2 ΔE off the panel. The ranking is the fill's now, so a palette that misses this is missing because the two fills are the SAME MARK — give the selection more step or more cast than the hover`)}if(H(p.sunken)&&H(p.rowHover)&&H(p.rowSelected)&&H(p.borderControl))for(const m of["rowHover","rowSelected"]){e.assertions++;const w=fe(p.sunken,p[m]),S=re(p.borderControl,p[m]);w<ct&&S<je.nonText&&n(`${b}: the agents sidebar's avatar plate has no perceivable edge against \`${m}\` — its \`sunken\` fill ${p.sunken} is ΔE00 ${D(w)} from it (need ${ct}) and the plate's \`borderControl\` edge ${p.borderControl} is ${D(S)}:1 against that same fill (need ${je.nonText}:1), so the row's own ${m==="rowHover"?"hover":"selection"} turns the avatar into a disc of the row's fill. Give the plate an edge the row's state cannot overrun, or a fill that state cannot land on`)}if(typeof p.scrim=="string"&&H(p.ink)){const m=p.scrim.match(/rgb\((\d+)\s+(\d+)\s+(\d+)\s*\/\s*([\d.]+)\)/);if(m){const[w,S,T,N]=m.slice(1).map(Number);for(const Y of hn){if(!H(p[Y]))continue;const X=[1,3,5].map(G=>Number.parseInt(p[Y].slice(G,G+2),16)),E=`#${[w,S,T].map((G,me)=>Math.round(G*N+X[me]*(1-N)).toString(16).padStart(2,"0")).join("")}`;e.assertions++;const V=re(p.ink,E);V<je.nonText&&n(`${b}: the lightbox's current-tile ring has no perceivable edge over \`${Y}\` — \`ink\` is ${D(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 m of uO)for(const w of Ze)o(b,p,m,w,je.nonText,"structural edge");const k=[...Ze,"accentWash","messageSurface"];for(const m of fO)for(const w of k)o(b,p,m,w,je.text,"colour as text");o(b,p,"warning","elevated",je.text,"the picker's partial-listing note"),o(b,p,"danger","elevated",je.text,"danger as text on a dialog's ground"),o(b,p,"warning","rowSelected",je.text,"integration status text on a deep-linked row"),o(b,p,"accent","warningWash",je.text,"model-access band links on the warning wash"),o(b,p,"warning","rowHover",je.text,"the partial delivery word on the hovered row's ground"),o(b,p,"dangerBorder","elevated",je.nonText,"the danger control's only edge on a dialog's ground");for(const m of aO)for(const w of m.on){const S=p[w],T=m.fill?p[m.fill]:S,N=p[m.ink],Y=m.border?p[m.border]:null;if(!H(S)||!H(T)||!H(N))continue;e.assertions++;const X=re(N,T);if(X<je.text&&!zf.has(m.ink)&&!i(b,m.ink,m.fill??w,X)&&n(`${b}: ${m.name} on ${w} — ink ${m.ink} ${N} on fill ${T} = ${X}:1, need ${je.text}:1`),m.edge!==!1){e.assertions++;const E=re(T,S),V=H(Y)?re(Y,S):0,G=Math.max(E,V);if(G<je.nonText){const me=bO.find(z=>z.control===m.name&&z.ground===w&&z.theme===b&&y(z.got,D(G)));me?h.add(_(me.control,me.ground,me.theme)):n(`${b}: ${m.name} on ${w} has no perceivable edge — fill ${E}:1, border ${V}:1, need one at ${je.nonText}:1`)}}}for(const m of pO)o(b,p,m.fg,m.on,m.floor,m.name);for(const m of lO)for(const w of m.on)o(b,p,m.fg,w,m.floor??je.nonText,m.name);for(const m of cO){const w=p[m.b];if(H(w))for(const S of m.a){const T=p[S];if(!H(T))continue;e.assertions++;const N=re(T,w);N<m.floor&&!i(b,S,m.b,N)&&n(`${b}: ${m.name} — ${S} ${T} against ${m.b} ${w} = ${N}:1, need ${m.floor}:1`)}}for(const m of dO){const w=p[m.role];if(!H(w))continue;for(const E of m.on){if(!H(p[E]))continue;e.assertions++;const V=fe(w,p[E]);V<m.minDeltaE&&!a(b,m.role,E,D(V))&&n(`${b}: ${m.name} — ${m.role} ${w} on ${E} ${p[E]} is ΔE00 ${D(V)}, need ${m.minDeltaE} to be seen at all`)}if(!m.pairedWith||!m.against)continue;const S=p[m.pairedWith],T=p[m.against];if(!H(S)||!H(T))continue;e.assertions++;const N=re(w,T),Y=re(S,T),X=Math.max(N/Y,Y/N);X>m.maxWeightChange&&n(`${b}: ${m.name} — ${m.role} is ${D(X)}x the weight of ${m.pairedWith} against ${m.against}; one component must not change weight by more than ${m.maxWeightChange}x between states`)}for(let m=0;m<Pi.length;m++)for(let w=m+1;w<Pi.length;w++){const[S,T]=[Pi[m],Pi[w]];if(!H(p[S])||!H(p[T]))continue;e.assertions++;const N=fe(p[S],p[T]);N<dn&&n(`${b}: \`${S}\` ${p[S]} and \`${T}\` ${p[T]} are too close to tell apart (ΔE00 ${D(N)}, need ${dn}) — a semantic a reader cannot distinguish from another semantic is not a semantic`)}if(H(p.accentAlt)){if(H(p.accent)){e.assertions++;const T=fe(p.accentAlt,p.accent);T<dn&&n(`${b}: the second accent \`accentAlt\` ${p.accentAlt} is ΔE00 ${D(T)} from \`accent\` ${p.accent} (need ${dn}) — two accents have to be two accents at the sizes this one is drawn at, and a value that buys its separation by darkening is the same hue at another weight rather than a second hue`)}for(const T of["success","warning","danger"]){if(!H(p[T]))continue;e.assertions++;const N=fe(p.accentAlt,p[T]);N<dn&&n(`${b}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${D(N)} from \`${T}\` ${p[T]} (need ${dn}) — a decorative mark a reader can mistake for "${T==="danger"?"something broke":T}" costs them something real, so the palette moves the hue rather than the assertion`)}if(H(p.info)){e.assertions++;const T=fe(p.accentAlt,p.info);T<Po&&n(`${b}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${D(T)} from \`info\` ${p.info} (need ${Po}) — \`info\` is the family the port mapped the TUI's \`signal\` onto, so the floor here is the reduced one and not ${dn}; below it the two take the same name`)}const[,m,w]=se(p.accentAlt),S=Math.hypot(m,w);e.assertions++,S<ti&&n(`${b}: \`accentAlt\` ${p.accentAlt} is C* ${D(S)} (need ${ti}) — a second accent drained toward the ink passes every separation above and stops being a hue, which is the one way this role fails while the gate stays green`);for(const T of["canvas","surface","sunken"])o(b,p,"accentAlt",T,je.text,"second accent as text");o(b,p,"accentAlt","elevated",je.text,"second accent as text on a row's state ground")}if(r(b,p,"accentAlt","info",Ao,"the tool row's two category inks"),r(b,p,"info","accent",Ro,"the settled read ink against the liveness ink"),H(p.accentAltWash)&&H(p.accentWash)){e.assertions++;const m=fe(p.accentAltWash,p.accentWash);m<ct&&n(`${b}: \`accentAltWash\` ${p.accentAltWash} is ΔE00 ${D(m)} from \`accentWash\` ${p.accentWash} (need ${ct}) — the two washes sit adjacent in mermaid's categorical ramp, so a step the reader cannot see is not a step`)}for(const m of yO){if(!H(p[m])||!H(p.inkDim))continue;e.assertions++;const w=fe(p[m],p.inkDim);w<Po&&n(`${b}: syntax \`${m}\` ${p[m]} sits at ΔE00 ${D(w)} from comment \`${p.inkDim}\` (need ${Po}) — a token the eye cannot separate from the comment beside it is not highlighted`)}if(H(p[dr])&&H(p.ink)){const m=kO.find(w=>w.theme===b);for(const w of wO){if(!H(p[w]))continue;e.assertions++;const S=re(p[dr],p[w]);S<4.5&&n(`${b}: the command token \`tokenCommand\` ${p[dr]} reads ${D(S)}:1 on \`${w}\` (need 4.5) - the token is text a user typed (the composer's leading /word, or the sent \`$skill\` mention), not decoration`)}for(const w of["ink","accent","success"]){if(!H(p[w]))continue;e.assertions++;const S=fe(p[dr],p[w]);if(!!m?.against.includes(w)){y(m.got,S)||n(`${b}: COMMAND_TOKEN_PINNED records ${m.got} for \`command\`/\`${w}\` but it now measures ${D(S)} - re-measure and update the pin (${m.why})`);continue}S<Mi&&n(`${b}: the command token \`tokenCommand\` ${p[dr]} sits at ΔE00 ${D(S)} from \`${w}\` ${p[w]} (need ${Mi}) - the composer paints this run in the same box as that ink, so a reader cannot tell which is which`)}if(H(p.success)){e.assertions++;const w=fe(p.success,p.ink);w<Mi&&n(`${b}: the roster NAME's ink \`success\` ${p.success} sits at ΔE00 ${D(w)} from prose \`ink\` ${p.ink} (need ${Mi}) - a resolved name that reads as prose is not a run`)}}if(H(p.inkMuted)&&H(p.inkDim)){e.assertions++,u.add(b);const m=fe(p.inkMuted,p.inkDim),w=_O.find(S=>S.theme===b);w&&f.add(w),m<Ar?w?y(w.got,m)||n(`${b}: INK_STEP_PINNED records ${w.got} but \`inkMuted\`/\`inkDim\` now measure ${D(m)} - re-measure and update the pin, so the recorded number stays the one in the palette`):n(`${b}: the control ink \`inkMuted\` ${p.inkMuted} sits at ΔE00 ${D(m)} from the readout ink \`inkDim\` ${p.inkDim} (need ${Ar}) - a chip that opens cannot be told from a reading that does not`):w&&!e.composed&&n(`${b}: the ink step is pinned at ${w.got} but now measures ${D(m)}, clearing the ${Ar} floor - delete the pin rather than leaving dead weight in the contract`)}for(const[m,w,S=ct]of[["canvas","surface"],["surface","elevated"],["elevated","sunken"],["accent","accentHover"],["accentHover","accentActive"],["accent","accentActive"],["surface","sunken"],["canvas","elevated",IO]]){if(!H(p[m])||!H(p[w]))continue;e.assertions++;const T=fe(p[m],p[w]);T<S&&n(`${b}: adjacent \`${m}\` and \`${w}\` are ΔE00 ${D(T)} apart (need ${S}) — a step the eye cannot see is not a step`)}{const m=se(p.canvas)[0],w=se(p.surface)[0],S=se(p.elevated)[0],T=se(p.sunken)[0],N=p.mode==="dark";e.composed||(e.assertions++,N&&(m<Xt.dark.canvasMin||m>Xt.dark.canvasMax)&&n(`${b}: dark \`canvas\` ${p.canvas} sits at L* ${D(m)} — the band is [${Xt.dark.canvasMin}, ${Xt.dark.canvasMax}] in L*. Below the floor the three ink weights and the three ladder steps stop fitting above each other without one of them breaking its own floor; above the ceiling the canvas is no longer the darker tone the operator asked for (2026-11-03), and a palette above it was not re-lit by the band's proportional map`),e.assertions++,N&&S>Xt.dark.elevatedMax&&n(`${b}: dark \`elevated\` ${p.elevated} sits at L* ${D(S)} — the ceiling is L* ${Xt.dark.elevatedMax}, because at L* 34 an \`inkDim\` at its floor needs L* 85 and the ink/hover distinction disappears into the top of the ramp`),e.assertions++,!N&&m>Xt.light.canvasMax&&n(`${b}: light \`canvas\` ${p.canvas} sits at L* ${D(m)} — the ceiling is L* ${Xt.light.canvasMax}. \`elevated\` at L* 100 is the end of sRGB's ramp and the minimum canvas-to-elevated spread is 2.5 + 2.5 L*, so a canvas above 95 has no room for both steps; 94 leaves 1 L* for 8-bit rounding`),e.assertions++,!N&&T<Xt.light.sunkenMin&&n(`${b}: light \`sunken\` ${p.sunken} sits at L* ${D(T)} — the floor is L* ${Xt.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[Y,X,E,[V,G],me]of[["canvas -> surface","canvas","surface",An.canvasSurface,w-m],["surface -> elevated","surface","elevated",An.surfaceElevated,S-w],["canvas -> sunken","canvas","sunken",An.canvasSunken,m-T]])if(e.assertions++,(me<V-1e-9||me>G+1e-9)&&n(`${b}: the ${Y} step is ${D(me)} L*, outside [${V}, ${G}] — 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`),o(b,p,X,E,sO,`${Y} step`),X==="canvas"&&E==="sunken"||X==="surface"&&E==="elevated"){e.assertions++;const z=fe(p[X],p[E]),ye=X==="canvas"?iO:AO;z<ye&&n(X==="canvas"?`${b}: \`canvas\` and \`sunken\` are ΔE00 ${D(z)} apart (need ${ye}) — a well nobody can see is not a well, and both blocks that paint one are read inside a trace that sits on the canvas`:`${b}: \`surface\` ${p.surface} and \`elevated\` ${p.elevated} are ΔE00 ${D(z)} apart (need ${ye}) — 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`)}}o(b,p,"ink","canvas",od,"the transcript's body ink");for(const m of hn){if(!H(p.inkDisabled)||!H(p.inkDim)||!H(p[m]))continue;e.assertions++;const w=re(p.inkDisabled,p[m]),S=re(p.inkDim,p[m]);w>Kf*S+1e-9&&n(`${b}: \`inkDisabled\` on ${m} measures ${D(w)}:1 against \`inkDim\`'s ${D(S)}:1 — a factor of ${D(w/S)}, over the ${Kf} ceiling. A disabled control that meets the ink floors does not read as disabled`)}for(const[m,w]of[["inkDim","inkMuted"],["inkMuted","ink"]]){if(!H(p[m])||!H(p[w]))continue;e.assertions++;const S=fe(p[m],p[w]);S<ms&&n(`${b}: \`${w}\` and \`${m}\` are ΔE00 ${D(S)} apart (need ${ms}) — the three weights are a ladder, and a rung the eye cannot see is not a rung`)}{const m=fe(p.sunken,p.elevated);e.assertions++,m<Vf&&n(`${b}: the palette/picker active row (\`sunken\` ${p.sunken}) is ΔE00 ${D(m)} from the dialog ground it is painted on (\`elevated\` ${p.elevated}), need ${Vf} — 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(se(p.sunken)[0]-se(p.elevated)[0]);w<Zf&&n(`${b}: the palette/picker active row sits ${D(w)} L* from \`elevated\`, under the ${Zf} 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(!H(p.messageSurface)){n(`${b}: the user message block's fill \`messageSurface\` ${JSON.stringify(p.messageSurface)} is present but not a flat hex colour, so the role's floor would be silently unmeasured - a malformed value must not switch a floor off`);continue}if(!H(p.canvas))continue;const m=fe(p.messageSurface,p.canvas);e.assertions++,m<Yf&&n(`${b}: the user message block's fill \`messageSurface\` ${p.messageSurface} is ΔE00 ${D(m)} from \`canvas\` ${p.canvas} (need ${Yf}) — the fill IS the block's boundary, and below this band it stops being findable`),e.assertions++;const w=Math.abs(se(p.messageSurface)[0]-se(p.canvas)[0]);w<Nc&&n(`${b}: the user message block's fill sits ${D(w)} L* from \`canvas\`, under the ${Nc} 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(!H(p.mediaSurface)){n(`${b}: the media tile's fill \`mediaSurface\` ${JSON.stringify(p.mediaSurface)} is present but not a flat hex colour, so the role's floor would be silently unmeasured - a malformed value must not switch a floor off`);continue}if(!H(p.canvas))continue;const m=fe(p.mediaSurface,p.canvas);e.assertions++,m<Xf&&n(`${b}: the media tile's fill \`mediaSurface\` ${p.mediaSurface} is ΔE00 ${D(m)} from \`canvas\` ${p.canvas} (need ${Xf}) — the fill IS the borderless tile's extent, and below this band it stops being findable`),e.assertions++;const w=Math.abs(se(p.mediaSurface)[0]-se(p.canvas)[0]);w<Jf&&n(`${b}: the media tile's fill sits ${D(w)} L* from \`canvas\`, under the ${Jf} L* floor — ΔE00 is a budget a chroma-only step can spend while the fill vanishes in a greyscale render, so the lightness half is asserted too`)}for(const m of Ze){if(!H(p.accentWash)||!H(p[m]))continue;e.assertions++;const w=fe(p.accentWash,p[m]);w<Qf&&n(`${b}: the accent wash on ${m} is ΔE00 ${D(w)} (need ${Qf}) — a hover tint the reader cannot see is a hover state the pointer cannot report, and this pair reads 1.00-1.24:1, so no ratio assertion in this file can see it`)}for(const m of["canvas","surface","elevated","accentWash"]){if(!H(p.sunken)||!H(p[m]))continue;e.assertions++;const w=fe(p.sunken,p[m]);w<qf&&n(`${b}: the keycap's ground \`sunken\` ${p.sunken} is ΔE00 ${D(w)} from ${m} ${p[m]} (need ${qf}) — the cap annotates the row the reader has just selected, so its ground has to survive being painted on that row`)}if(H(p.chartBarHover)&&H(p.accent)&&H(p[ji])){e.assertions++;const m=fe(p.chartBarHover,p.accent);m<Uc&&n(`${b}: \`chartBarHover\` ${p.chartBarHover} is ΔE00 ${D(m)} 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=re(p.chartBarHover,p[ji]),S=re(p.accent,p[ji]);w<S&&n(`${b}: \`chartBarHover\` is ${D(w)}:1 on ${ji} where \`accent\` is ${D(S)}:1 — the hovered mark must not recede toward the ground it is drawn on`)}for(const m of Ze){if(!H(p.hairline)||!H(p[m]))continue;e.assertions++;const w=fe(p.hairline,p[m]);w<ep&&n(`${b}: \`hairline\` on \`${m}\` is ΔE00 ${D(w)} (need ${ep}) — a 1px line has no area to integrate over, so a step that reads between two fields disappears in a rule`);const S=re(p.hairline,p[m]);e.assertions++,S<ap&&n(`${b}: \`hairline\` on \`${m}\` is ${D(S)}:1 (need ${ap}) — its ΔE00 is carried in chroma, which a 1px line does not survive`),e.assertions++,S>sp&&n(`${b}: \`hairline\` on \`${m}\` is ${D(S)}:1 (max ${sp}) — past this it is drawing a border, and the system already has one of those`)}for(const[m,w]of EO){if(!H(p.hairline)||!H(p[m])||!H(p[w]))continue;const S=Pa(p.hairline,p[m],SO);e.assertions++;const T=fe(S,p[m]);T<ct&&n(`${b}: the panel seam over \`${m}\` is ΔE00 ${D(T)} from that ground (need ${ct}) — the seam is half the boundary, and half a boundary the reader cannot see is a panel edge that disappears`),e.assertions++;const N=fe(S,p[w]);N<ct&&n(`${b}: the panel seam over \`${m}\` is ΔE00 ${D(N)} from \`${w}\` (need ${ct}) — the seam has to read from the plane it faces as well as the one it sits on`)}const M=Pa(p.accent,p.surface,tp);for(const[m,w,S]of[["inkMuted",je.text,"washed row metadata ink"],["ink",je.text,"washed row body ink"]]){const T=p[m];if(!H(T))continue;e.assertions++;const N=D(re(T,M));N>=w||n(`${b}: ${S} — ${m} ${T} on the arrival band ${M} (accent ${tp} over surface) = ${N}:1, need ${w}:1`)}for(const m of["canvas","surface","elevated","accentWash"]){const w=Pa(p.accent,p[m],np);for(const[S,T,N]of[["inkMuted",je.text,"loading pill label"]]){const Y=p[S];if(!H(Y))continue;e.assertions++;const X=D(re(Y,w));X>=T||n(`${b}: ${N} — ${S} ${Y} on the loading pill ${w} (accent ${np} over ${m}) = ${X}:1, need ${T}:1`)}}const P=re(M,p.surface),W=re(p.rowHover,p.surface),R=re(p.rowSelected,p.surface);e.assertions+=2,P<=W&&n(`${b}: the arrival band is ${D(P)}:1 over the pane and the row hover is ${D(W)}:1 — the mark the reader was TOLD about cannot be drawn more quietly than one their pointer rests on`),P<=R&&n(`${b}: the arrival band is ${D(P)}:1 over the pane and the selected row is ${D(R)}:1 — the arrival must outrank the row the reader is already on, or the landing reads as a selection`)}},DO=Object.freeze({soft:-100,gentle:-50,standard:0,strong:50,high:100}),NO=Object.freeze({dark:Object.freeze({high:5,soft:20}),light:Object.freeze({high:97,soft:89})}),LO=["canvas","surface","elevated","sunken","messageSurface","mediaSurface","rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash","hairline","hairlineStrong","inkDisabled"],FO=new Set(["rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash"]),Wi=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Ct=Wi.slice(0,4),ur=[...Ct,"accentWash","messageSurface"],La={ink:[Wi,7],inkMuted:[Wi,5.5],inkDim:[Wi,5],borderControl:[Ct,3],accent:[[...ur,"warningWash"],4.5],accentHover:[Ct,4.5],accentActive:[Ct,4.5],tokenCommand:[["surface","elevated","messageSurface"],4.5],accentAlt:[Ct,4.5],success:[ur,4.5],warning:[[...ur,"rowSelected","rowHover"],4.5],danger:[ur,4.5],info:[ur,4.5],successBorder:[Ct,3],warningBorder:[Ct,3],dangerBorder:[Ct,3],infoBorder:[Ct,3],chartBarHover:[["surface"],3]},Pt=.05,cp=.3,lp=4.1,UO=.06,BO=/^#[0-9A-Fa-f]{6}$/,it=e=>typeof e=="string"&&BO.test(e),Wt=e=>e.slice(0,7).toUpperCase(),dt=(e,t,n)=>{const o=Math.max(0,Math.min(100,e));for(let r=1;r>=0;r-=.02){const i=hs([o,t*r,n*r]);if(i)return i}return hs([o,0,0])},oo=(e,t,n)=>Math.min(...n.filter(o=>it(e[o])).map(o=>re(t,e[o]))),Bc=(e,t,n,o,r=()=>!0)=>{const i=e[t];if(!it(i)||oo(e,i,n)>=o+Pt&&r(i))return i;const[a,c,l]=se(i),d=e.mode==="dark"?1:-1;for(let u=.25;u<=100;u+=.25){const f=dt(a+d*u,c,l);if(oo(e,f,n)>=o+Pt&&r(f))return f}return i},rd=(e,t)=>{const n=t.filter(it).map(Wt),o=n.find(r=>re(r,e)>=4.5);return o||[...n].sort((r,i)=>re(i,e)-re(r,e))[0]},$i=e=>1+.015*(e-50)**2/Math.sqrt(20+(e-50)**2),ro=e=>{const[,t,n]=se(e);return Math.hypot(t,n)},dp=(e,t)=>{const[n,o,r]=se(e),i=Math.hypot(o,r);return i<1e-6?e:dt(n,o/i*t,r/i*t)},HO=e=>{if(!it(e.rowHover)||!it(e.rowSelected))return;zO(e);const t=ro(e.surface),n=Math.max(_s,y_*t),o=Math.max(t,_s),r=Math.max(bs,t),i=Math.min(Math.max(t+Lc,bs),Fc),a=(f,h,_)=>Math.min(Math.max(f,h),_),c=ro(e.rowHover),l=ro(e.rowSelected);if(c>=n&&c<=o&&l>=r&&l<=i&&l>=c+gs)return;const d=a(c,n+.1,o-.1),u=a(Math.max(l,d+gs+.2),r+.1,i-.1);e.rowHover=dp(e.rowHover,d),e.rowSelected=dp(e.rowSelected,u)},WO=6,GO=e=>{const[,t,n]=se(e);return Math.atan2(n,t)},zO=e=>{const n=ro(e.surface)>=mn?e.surface:ro(e.accent)>=w_?e.accent:e.surface,o=GO(n);for(const r of["rowHover","rowSelected"]){const[i,a,c]=se(e[r]),l=Math.hypot(a,c);l<mn||Math.abs(((Math.atan2(c,a)-o)*180/Math.PI+540)%360-180)<=WO||(e[r]=dt(i,l*Math.cos(o),l*Math.sin(o)))}},KO=e=>{const t=e.mode==="dark"?1:-1,n=(o,r,i,a,c)=>{const l=e[o];if(!it(l))return;const d=_=>oo(e,_,r)>=i+Pt&&(!a||fe(_,e[a])>=c+Pt)&&(o!=="ink"||re(_,e.canvas)>=od+Pt);if(d(l))return;const[u,f,h]=se(l);for(let _=.25;_<=100;_+=.25){const y=dt(u+t*_,f,h);if(d(y)){e[o]=y;return}}};n("inkDim",hn,Gi("inkDim"),null,0),n("inkMuted",hn,Gi("inkMuted"),"inkDim",Ar),n("ink",hn,Gi("ink"),"inkMuted",ms)},Gi=e=>b_.find(([t])=>t===e)[1],VO=.15,k_=.12,ZO=(e,t,n)=>{if(!it(e.ink)||!it(e.canvas))return;const o=Math.abs(n)/100,r=e.mode==="dark"?1:-1;if(n>0){const[l,d,u]=se(e.ink),f=t*(1+VO*o);if(re(e.ink,e.canvas)>=f)return;for(let h=.25;h<=100;h+=.25){const _=l+r*h;if(_<0||_>100)break;const y=dt(_,d,u);if(e.ink=y,re(y,e.canvas)>=f)return}return}const i=t*(1-k_*o),a=["ink","inkMuted","inkDim"].filter(l=>it(e[l])),c=l=>a.every(d=>oo(e,l[d],hn)>=Gi(d)+Pt)&&re(l.ink,e.canvas)>=od&&(!l.inkMuted||fe(l.ink,l.inkMuted)>=ms+Pt)&&(!l.inkMuted||!l.inkDim||fe(l.inkMuted,l.inkDim)>=Ar+Pt);for(const l of[a,a.slice(0,2),a.slice(0,1)]){const d=Object.fromEntries(l.map(u=>[u,se(e[u])]));for(let u=.25;u<=60;u+=.25){if(re(e.ink,e.canvas)<=i)return;const f={...e};for(const h of l){const[_,y,v]=d[h];f[h]=dt(_-r*u,y,v)}if(!c(f))break;for(const h of l)e[h]=f[h]}}},Di=(e,t,n,o,r=()=>!0)=>{const i=e[t];if(!it(i)||!n.split(",").every(f=>it(e[f])))return;const a=f=>n.split(",").every(h=>fe(f,e[h])>=o+Pt)&&r(f);if(a(i))return;const[c,l,d]=se(i),u=e.mode==="dark"?1:-1;for(const f of[u,-u])for(let h=.25;h<=40;h+=.25){const _=dt(c+f*h,l,d);if(a(_)){e[t]=_;return}}},S_=(e,t,{spread:n=1,narrow:o=!1,ease:r=UO,travel:i=1}={})=>{if(t===0)return e;const a=t>0?"high":"soft",c=Math.abs(t)/100,l={...e},d=z=>se(Wt(e[z])),u=d("canvas")[0],f=NO[e.mode][a],h=LO.filter(z=>it(e[z])),_=a==="high"==(e.mode==="light")?1:-1;let y=Math.max(0,(f-u)*_)*_*c*i,v=u+y;const b=a==="soft"?1-.4*c:1,p=$i(v)/$i(u),A=(a==="soft"?p:Math.max(1,p))*n,k=Object.fromEntries(h.map(z=>[z,v+(d(z)[0]-u)*A])),M=e.mode==="dark"?1:-1,P=(z,[,ye],be)=>{const Ce=(d(z)[0]-u)*be,$e=(k[z]-v)*be,_t=Math.max(Ce,ye-.15);$e>_t&&(k[z]=v+be*_t)};P("surface",An.canvasSurface,M),P("sunken",An.canvasSunken,-M);{const z=(d("elevated")[0]-d("surface")[0])*M,ye=(k.elevated-k.surface)*M,be=Math.max(z,An.surfaceElevated[1]-.15);ye>be&&(k.elevated=k.surface+M*be)}const W=d("surface")[0],R=e.mode==="dark"?1:-1,m=(d("rowSelected")[0]-W)*R,w=(d("rowHover")[0]-W)*R,S=m>0?Math.min(A,v_/m):A,T=a==="soft"?S:Math.max(1,S);if(k.rowSelected=k.surface+R*m*T,k.rowHover=k.surface+R*w*T,e.mode==="light"&&a==="high"){const z=u+y,ye=Object.keys(k).filter(Ce=>d(Ce)[0]>u),be=Math.max(0,...ye.map(Ce=>d(Ce)[0]-u));if(be>0){const Ce=ge=>{const xe=Math.min(1,(100-cp-ge)/be),pt={canvas:dt(ge,...d("canvas").slice(1))};for(const $t of ye)pt[$t]=dt(ge+(d($t)[0]-u)*xe,...d($t).slice(1));return pt},$e=[["canvas","surface",ct],["surface","elevated",ct],["canvas","elevated",lp],["canvas","messageSurface",lp]].filter(([ge,xe])=>(ge==="canvas"||ye.includes(ge))&&ye.includes(xe)),_t=[["canvas","surface",An.canvasSurface[0]],["surface","elevated",An.surfaceElevated[0]],["canvas","messageSurface",Nc]].filter(([ge,xe])=>(ge==="canvas"||ye.includes(ge))&&ye.includes(xe)),jt=(ge,xe,pt)=>pt+.02,le=ge=>$e.every(([xe,pt,$t])=>fe(ge[xe],ge[pt])>=jt(xe,pt,$t))&&_t.every(([xe,pt,$t])=>se(ge[pt])[0]-se(ge[xe])[0]>=$t+.15);let ke=z;for(;ke>u&&!le(Ce(ke));)ke=Math.max(u,ke-.25);const et=ke<=u?1:Math.min(1,(100-cp-ke)/be),Ne=Math.max(1,$i(ke)/$i(u))*n,Et={rowHover:k.rowHover-k.surface,rowSelected:k.rowSelected-k.surface};for(const ge of Object.keys(k))k[ge]=ye.includes(ge)?ke+(d(ge)[0]-u)*et:ke+(k[ge]-z)*(Ne/A);for(const ge of["rowHover","rowSelected"])ge in k&&Number.isFinite(Et[ge])&&(k[ge]=k.surface+Et[ge]);v=ke,y=ke-u}}if(a==="soft"&&o){const z=le=>e.mode==="dark"?le>v:le<v,ye=le=>le>8?((le+16)/116)**3:Math.max(0,le)/903.3,be=(le,ke)=>{const[et,Ne]=[ye(le),ye(ke)];return(Math.max(et,Ne)+.05)/(Math.min(et,Ne)+.05)},Ce=hn.filter(le=>le in k&&z(k[le])),_t=Math.max(1,...hn.filter(le=>le in k&&(e.mode==="dark"?d(le)[0]>u:d(le)[0]<u)).map(le=>be(u,d(le)[0])))*(1-r*c),jt=le=>Math.max(1,...Ce.map(ke=>be(v,v+(k[ke]-v)*le)));if(Ce.length>0&&jt(1)>_t){let le=1;for(;le>.3&&jt(le)>_t;)le-=.01;for(const ke of Object.keys(k))z(k[ke])&&(k[ke]=v+(k[ke]-v)*le)}}const N=Math.min(...Object.values(k)),Y=Math.max(...Object.values(k)),X=N<.5?.5-N:Y>100?100-Y:0,E=ro(Wt(e.surface)),V=E>=mn?Math.max(b,Math.min(1,(mn+.4)/E)):b;for(const z of h){const[,ye,be]=d(z),Ce=FO.has(z)?1:z==="surface"?V:b;l[z]=dt(k[z]+X,ye*Ce,be*Ce)}HO(l),y=v+X-u;for(const z of Object.keys(La))it(e[z])&&(l[z]=Wt(e[z]));KO(l),ZO(l,re(Wt(e.ink),Wt(e.canvas)),t);const G=se(l.accent)[0];l.accent=Bc(l,"accent",...La.accent);const me=se(l.accent)[0]-G;for(const z of["accentHover","accentActive"]){if(!it(l[z])||me===0)continue;const[ye,be,Ce]=se(l[z]);l[z]=dt(ye+me,be,Ce)}for(const[z,[ye,be]]of Object.entries(La))z.startsWith("ink")||z==="accent"||(l[z]=Bc(l,z,ye,be));return Di(l,"accentHover","accent",ct,z=>oo(l,z,Ct)>=4.5+Pt),Di(l,"accentActive","accent,accentHover",ct,z=>oo(l,z,Ct)>=4.5+Pt),Di(l,"accentAlt","accent",dn,z=>oo(l,z,Ct)>=4.5+Pt&&ro(z)>=ti),Di(l,"chartBarHover","accent",Uc,z=>re(z,l.surface)>=re(l.accent,l.surface)),l.onAccent=rd(l.accent,[e.onAccent,l.ink,l.canvas,"#FFFFFF","#000000"]),l},vs=(e,t="custom")=>{const n=jO({composed:!0});return $O(n,{id:t,palette:e}),n.log},zi=(e,t)=>{const n=rd(e.accent,[t.onAccent,e.ink,e.canvas,"#FFFFFF","#000000"]);return n===e.onAccent?e:{...e,onAccent:n}},up=new Set(["mode","overlayShadow","scrim","onAccent"]),YO=["rowHover","rowSelected","accentWash","surface"],XO=/\b[a-z][A-Za-z]+\b/g,JO=(e,t)=>{const n=new Map;for(const[r,i]of Object.entries(e))!up.has(r)&&it(i)&&n.set(i.toUpperCase(),r);const o=new Set;for(const r of t){if(r.includes("ROW_STATE_MEASURED_SHORTFALL"))for(const i of YO)o.add(i);for(const[i]of r.matchAll(XO))i in e&&!up.has(i)&&it(e[i])&&o.add(i);for(const[i]of r.matchAll(QO)){const a=n.get(i.toUpperCase());a&&o.add(a)}}return[...o]},QO=/#[0-9A-Fa-f]{6}\b/g,qO=/(?:= |ΔE00 )(\d+(?:\.\d+)?)(?::1)?[\s\S]*?need (\d+(?:\.\d+)?)/,eP=e=>{let t=0;for(const n of e){const o=n.match(qO);if(!o){t+=1;continue}const r=Number(o[1]),i=Number(o[2]);t+=i>0?Math.min(1,Math.max(0,(i-r)/i)):1}return t},fp=e=>e.length*1e3+eP(e),tP=[.5,-.5,1,-1,2,-2,4,-4,7,-7,11,-11],nP=[.7,.85,1.15,1.35],oP=60,E_=(e,t,n=e,{pinned:o=[],maxEvaluations:r=Number.POSITIVE_INFINITY,lightnessOnly:i=!1}={})=>{const a=new Set(o),c=h=>a.has("onAccent")?h:zi(h,n);let l=0,d=c(e),u=vs(d,t),f=fp(u);for(let h=0;h<oP&&u.length>0;h++){let _=null;for(const y of JO(d,u)){if(a.has(y))continue;const[v,b,p]=se(d[y]),A=[...tP.map(k=>dt(v+k,b,p)),...i?[]:nP.map(k=>dt(v,b*k,p*k))];for(const k of A){if(k===d[y])continue;if(++l>r)return{palette:d,findings:u};const M=c({...d,[y]:k}),P=vs(M,t),W=fp(P);W<(_?_.score:f)-1e-9&&(_={next:M,findings:P,score:W})}}if(!_)break;d=_.next,u=_.findings,f=_.score}return{palette:d,findings:u}},rP=5,iP=[1,1.15],sP=[{spread:1,narrow:!0},{spread:1,narrow:!0,ease:0},...iP.map(e=>({spread:e})),{spread:1,travel:.5,soft:!0},{spread:1,travel:0,soft:!0}],pp=.015,aP=(e,t,n)=>{const o=re(Wt(e.ink),Wt(e.canvas)),r=re(t.ink,t.canvas),i=se(Wt(e.canvas))[0],a=se(t.canvas)[0],c=n>0==(e.mode==="light")?1:-1;return n>0?r>=o-pp&&(a-i)*c>=-.05:r<=o+pp},cP=(e,t,n,o)=>{const i=re(Wt(t.ink),Wt(t.canvas))*(1-k_*(Math.abs(n)/100)),a=e.mode==="dark"?-1:1,c=["ink","inkMuted","inkDim"].filter(d=>it(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,se(l[f])]));for(let f=.25;f<=20;f+=.25){if(re(l.ink,l.canvas)<=i)return l;const h={...l};for(const _ of d){const[y,v,b]=u[_];h[_]=dt(y+a*f,v,b)}if(vs(zi(h,t),o).length>0)break;l=zi(h,t)}}for(let d=0;d<6&&re(l.ink,l.canvas)>i;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 v=`#${l.ink.slice(1,1+2*f)}${y.toString(16).padStart(2,"0").toUpperCase()}${l.ink.slice(3+2*f)}`,b=re(v,l.canvas);if(b>=re(l.ink,l.canvas))continue;const p=zi({...l,ink:v},t);vs(p,o).length>0||(!u||b>u.r)&&(u={r:b,next:p})}if(!u)break;l=u.next}return l},lP=(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 o=Math.sign(t);for(let r=t;r!==0;r-=o*Math.min(rP,Math.abs(r)))for(const i of sP){if((i.narrow||i.soft)&&r>0)continue;const a=S_(e,r,i),c=E_(a,n,e);if(r<0&&c.findings.length===0&&(c.palette=cP(c.palette,e,r,n)),c.findings.length===0&&aP(e,c.palette,r))return{palette:c.palette,effectiveContrast:r}}return{palette:e,effectiveContrast:0}},Vn=/^#[0-9A-Fa-f]{6}$/,dP=/^#[0-9A-Fa-f]{3}$/,gt=e=>{if(typeof e!="string")return null;let t=e.trim();return t.startsWith("#")||(t=`#${t}`),dP.test(t)&&(t=`#${[...t.slice(1)].map(n=>n+n).join("")}`),Vn.test(t)?t.toUpperCase():null},uP=["accentHover","accentActive","accentWash","chartBarHover"],Bt=e=>{const[t,n,o]=se(e);return[t,Math.hypot(n,o),Math.atan2(o,n)]},fP=e=>Bt(e)[1],ys=(e,t,n)=>dt(e,Math.max(0,t)*Math.cos(n),Math.max(0,t)*Math.sin(n)),pP=4,hP=(e,t,n)=>{const[o,r,i]=Bt(e),[a,c,l]=Bt(t),[d,u,f]=Bt(n);return r<pP?ys(d+(a-o),c,f):ys(d+(a-o),u*(c/r),f+(l-i))},mP=(e,t,n)=>{if(!e||e.kind==="theme")return null;if(e.kind==="theme-alt")return gt(t.accentAlt);if(e.kind==="palette"){const o=typeof n=="function"?n(e.id):null;return gt(o)}return e.kind==="custom"?gt(e.hex):null},gP=(e,t,{authored:n=e,id:o="custom",paletteAccent:r,preserveSecondary:i=!1}={})=>{const a=mP(t,n,r);if(!a)return{palette:e,applied:!1,adjusted:0,requested:a};const c={...e,accent:a};for(const h of uP)!Vn.test(n[h]??"")||!Vn.test(n.accent??"")||(c[h]=hP(n.accent,n[h],a));if(Vn.test(e.accentWash??"")&&Vn.test(n.accentWash??"")){const h=Bt(e.accentWash)[0],[,_,y]=Bt(c.accentWash);c.accentWash=ys(h,Math.max(_,Bt(n.accentWash)[1]),y)}if(fP(c.surface)<mn){const h=Bt(c.accent)[2];for(const _ of["rowHover","rowSelected"]){if(!Vn.test(c[_]??""))continue;const[y,v]=Bt(c[_]);v>=mn&&(c[_]=ys(y,v,h))}}!i&&t.kind==="theme-alt"?Bt(n.accent)[1]>=ti&&(c.accentAlt=gt(n.accent)):!i&&fe(c.accent,c.accentAlt)<dn&&Bt(n.accent)[1]>=ti&&(c.accentAlt=gt(n.accent));const l=se(c.accent)[0];c.accent=Bc(c,"accent",_P,4.5,h=>fe(h,c.ink)>=3);const d=se(c.accent)[0]-l;if(d!==0)for(const h of["accentHover","accentActive","chartBarHover"]){if(!Vn.test(c[h]??""))continue;const[_,y,v]=se(c[h]);c[h]=dt(_+d,y,v)}c.onAccent=rd(c.accent,[n.onAccent,c.ink,c.canvas,"#FFFFFF","#000000"]);const u=E_(c,o,n);return i&&__.filter(h=>h.storage==="overrides").flatMap(h=>[h.role,...h.variants]).some(h=>u.palette[h]!==e[h])||u.findings.length>0||fe(u.palette.accent,u.palette.ink)<3?{palette:e,applied:!1,adjusted:0,requested:a}:{palette:u.palette,applied:!0,adjusted:fe(a,u.palette.accent),requested:a}},_P=["canvas","surface","elevated","sunken","accentWash","messageSurface","warningWash"],hp=["dark","light"],bP=12,yF=50,wF="custom-themes-storage",vP=60,I_=Object.freeze({dark:0,light:0}),Rn=Object.freeze({kind:"theme"}),A_=Object.freeze({dark:Rn,light:Rn}),Hc=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(-100,Math.min(100,Math.round(e))),R_=e=>!e||typeof e!="object"?I_:{dark:Hc(e.dark),light:Hc(e.light)},Wc=(e,t=()=>!0)=>{if(!e||typeof e!="object")return Rn;switch(e.kind){case"theme":return Rn;case"theme-alt":return{kind:"theme-alt"};case"palette":return typeof e.id=="string"&&t(e.id)?{kind:"palette",id:e.id}:Rn;case"custom":{const n=gt(e.hex);return n?{kind:"custom",hex:n}:Rn}default:return Rn}},x_=(e,t)=>!e||typeof e!="object"?A_:{dark:Wc(e.dark,t),light:Wc(e.light,t)},Vo=e=>{if(!Array.isArray(e))return[];const t=[];for(const n of e){const o=gt(n);if(o&&!t.includes(o)&&t.push(o),t.length===bP)break}return t},yP=(e,t)=>{const n=gt(t);return Vo(n?[n,...Array.isArray(e)?e:[]]:e)},wP=/^custom-[a-z0-9]{1,30}$/,id=e=>typeof e=="string"&&wP.test(e)?e:null,kF=(e,{isThemeName:t,isRole:n})=>{if(!e||typeof e!="object"||e.format!=="local-operator-theme"||e.version!==1)return null;const o=id(e.id);if(!o||!Yc(o)||typeof e.base!="string"||!t(e.base))return null;const r=typeof e.name=="string"&&e.name.trim()?e.name.trim().slice(0,vP):null;if(!r)return null;const i=a=>{const c={};if(!a||typeof a!="object")return c;for(const[l,d]of Object.entries(a)){if(!n(l))continue;const u=gt(d);u&&Xc(u)&&(c[l]=u)}return c};return{format:"local-operator-theme",version:1,id:o,name:r,base:e.base,seeds:i(e.seeds),overrides:i(e.overrides),updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:0}},en=Object.freeze(Object.entries(DO).sort(([,e],[,t])=>e-t).map(([e,t])=>Object.freeze({name:e,value:t}))),mp=5,kP=8,SP=e=>Math.max(-100,Math.min(100,e)),SF=(e,{snap:t=!0}={})=>{if(!Number.isFinite(e))return 0;const n=SP(Math.round(e/mp)*mp);if(!t)return n;for(const{value:o}of en)if(Math.abs(e-o)<=kP)return o;return n},EP=e=>en.find(t=>t.value===e)?.name??null,EF=e=>{let t=en[2];for(const n of en){const o=Math.abs(n.value-e),r=Math.abs(t.value-e);(o<r||o===r&&Math.abs(n.value)<Math.abs(t.value))&&(t=n)}return t.name},IF=e=>{if(EP(e))return null;for(let t=1;t<en.length;t++)if(e<en[t].value)return[en[t-1].name,en[t].name];return null},AF=(e,t)=>{const o=(t>0?en:[...en].reverse()).find(r=>t>0?r.value>e:r.value<e);return o?o.value:e},IP=[[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"]],sd=8,ad=e=>{const[t,n,o]=se(e),r=Math.atan2(o,n)*180/Math.PI;return{L:t,C:Math.hypot(n,o),h:r<0?r+360:r}},RF=e=>{const{C:t,h:n}=ad(e);if(t<sd)return"neutral";for(const[o,r]of IP)if(n<o)return r;return"pink"},xF=(e,t,n)=>{const o=e.find(l=>l.id===n)?.palette.accent,r=e.filter(l=>l.palette.mode===t&&l.id!==n&&typeof l.palette.accent=="string"&&l.palette.accent.toUpperCase()!==o?.toUpperCase()),i=new Map;let a=null;for(const l of r){const{C:d,h:u}=ad(l.palette.accent);if(d<sd){(!a||d<a.C)&&(a={...l,C:d});continue}const f=Math.floor(u/36),h=Math.abs(u-(f*36+18)),_=i.get(f);(!_||h<_.off||h===_.off&&l.id<_.id)&&i.set(f,{...l,off:h})}const c=[...i.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},TF=(e,t)=>{const n=new Set,o=[];for(const i of e){if(i.palette.mode!==t)continue;const a=String(i.palette.accent).toUpperCase();n.has(a)||(n.add(a),o.push({id:i.id,hex:a}))}const r=i=>{const{C:a,h:c}=ad(i);return a<sd?1e3:c};return o.sort((i,a)=>r(i.hex)-r(a.hex))},AP=40,Ki=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return{};const n={};for(const o of Array.isArray(t)?t:[]){const r=e[o];if(typeof r!="string")continue;const i=[...r].map(a=>{const c=a.codePointAt(0)??0;return c<32||c===127?" ":a}).join("").replace(/\s+/g," ").trim().slice(0,AP);i&&(n[o]=i)}return n},CF=Object.freeze({strip:"lo-preview",chip:e=>`lo-preview-${e}`}),OF=(e,t,n=null)=>{const o=[];for(const{id:r,contrast:i}of t){if(!Yc(r))continue;const a=i===0?e:S_(e,i),c=n?{...a,...n}:a;Object.entries(c).every(([d,u])=>d==="mode"||Xc(u))&&o.push(Ip(r,c))}return o.join(`
|
|
65
|
+
`)},PF=e=>{const[t,n,o]=se(e),r=Math.atan2(o,n)*180/Math.PI;return{l:t,c:Math.hypot(n,o),h:r<0?r+360:r}},MF=({l:e,c:t,h:n})=>{const o=Math.max(0,Math.min(100,e)),r=n*Math.PI/180;for(let i=Math.max(0,t);i>=0;i-=1){const a=hs([o,i*Math.cos(r),i*Math.sin(r)]);if(a)return a}return hs([o,0,0])??"#000000"},jF=e=>{const t=re("#FFFFFF",e),n=re("#000000",e);return t>=n?{ink:"#FFFFFF",ratio:t}:{ink:"#000000",ratio:n}},$F=Object.freeze(["accent","accentHover","accentActive","accentWash","onAccent","chartBarHover","accentAlt","accentAltWash"]),gp=64,Gc=["canvas","run","browser","console","code"],RP={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function T_(e){return typeof e=="string"&&Gc.includes(e)}function cd(e){return e.startsWith("draft:")}function li(e,t){for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(o[0]===t)return o[1]}}function ld(e){return e.length>gp?e.slice(e.length-gp):e}function C_(e,t,n){return ld([...e.filter(([o])=>o!==t),[t,n]])}function xP(e,t,n){return li(e,t)!==n?e:e.filter(([o])=>o!==t)}function TP(e,t){return li(e,t)===void 0?e:e.filter(([n])=>n!==t)}function CP(e,t,n){const o=li(e,t);return o===void 0?e:ld([...e.filter(([r])=>r!==t&&r!==n),[n,o]])}const _p=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function bp(e,t,n){if(n||typeof t!="string")return _p;const o=li(e,t);return o===void 0?_p:{isCanvasOpen:o==="canvas",isRunPanelOpen:o==="run",isBrowserPaneOpen:o==="browser",isConsolePaneOpen:o==="console",isCodeReviewPaneOpen:o==="code"}}function OP(e){if(!Array.isArray(e))return[];const t=new Map;for(const n of e){if(!Array.isArray(n)||n.length!==2)continue;const[o,r]=n;typeof o!="string"||o===""||cd(o)||T_(r)&&(t.delete(o),t.set(o,r))}return ld([...t.entries()])}function DF(e){const t=new Set(Object.keys(e.forgotten));for(const[n,o]of Object.entries(e.archiveFacts))o?.archived===!0&&o.answered===!0&&t.add(n);return t}function vp(e){return RP[e]}let PP=0;const MP=()=>`console-command:${++PP}`,jP={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},di=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,Ws=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,$P=e=>{const t=di(e);return t===null||t==="ask"?null:jP[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:C_(e.rightSlotMemory,n,t)}},fr=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const o=xP(e.rightSlotMemory,n,t);return o===e.rightSlotMemory?{}:{rightSlotMemory:o}},DP=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=TP(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},NP=Object.freeze({mounted:!1,session:!1}),O_=Object.freeze([]);function NF(e,t){const n=di(t);if(n===null||!Ws(n,t))return 0;let o;switch(n){case"canvas":case"ask":o=pr(Xl,t.rightSlotWidth);break;case"run":o=pr(wp,t.rightSlotWidth);break;case"browser":o=pr(HP,t.rightSlotWidth);break;case"console":o=pr(WP,t.rightSlotWidth);break;case"code":o=pr(wp,t.rightSlotWidth);break}return e<=0?o:n==="canvas"||n==="ask"?Math.min(o,Jl(e)):Math.min(o,Math.max(0,e-Zl))}function pr(e,t){return Math.min(qg,Math.max(e,t||LP))}function LF(e){const t=di(e);return t!==null&&Ws(t,e)}function FF(e){const t=di(e);return t!==null&&Ws(t,e)?t:null}function UF(e){const t=di(e);return(t==="canvas"||t==="ask")&&Ws(t,e)}const LP=640,yp=Ls,FP=20,UP=4,BP=20,wp=320,HP=480,WP=480,GP=5e3,BF=(e,t)=>e.some(n=>n.surface===t),HF=(e,t=Date.now())=>e.some(n=>t-n.at<GP),zP=[],KP=5,VP=["chatMeasureWidth"],WF=ri()(Is((e,t)=>({finderFiles:u_,setFinderFiles:n=>e({finderFiles:ed({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:h_,agentAvatarSize:n_,themeName:B_,contrast:I_,accent:A_,customAccents:[],customAccentNames:{},customThemeId:null,setContrast:(n,o)=>e(r=>({contrast:{...r.contrast,[n]:Hc(o)}})),setAccent:(n,o)=>e(r=>({accent:{...r.accent,[n]:Wc(o,Vc)}})),addCustomAccent:(n,o)=>e(r=>{const i=yP(r.customAccents,n),a=gt(n),c=Ki(r.customAccentNames,i);return!o||!a?{customAccents:i,customAccentNames:c}:{customAccents:i,customAccentNames:c,accent:{...r.accent,[o]:{kind:"custom",hex:a}}}}),removeCustomAccent:n=>e(o=>{const r=gt(n),i={...o.accent};for(const c of hp){const l=i[c];l.kind==="custom"&&l.hex===r&&(i[c]=Rn)}const a={...o.customAccentNames};return r&&delete a[r],{customAccents:o.customAccents.filter(c=>c!==r),customAccentNames:a,accent:i}}),renameCustomAccent:(n,o)=>e(r=>{const i=gt(n);return!i||!r.customAccents.includes(i)?{}:{customAccentNames:Ki({...r.customAccentNames,[i]:o},r.customAccents)}}),replaceCustomAccent:(n,o)=>e(r=>{const i=gt(n),a=gt(o);if(!i||!a||i===a)return{};if(r.customAccents.indexOf(i)<0)return{};const l=r.customAccents.filter(h=>h!==a);l.splice(l.indexOf(i),1,a);const d=Vo(l),u={...r.customAccentNames};u[i]!==void 0&&u[a]===void 0&&(u[a]=u[i]),delete u[i];const f={...r.accent};for(const h of hp){const _=f[h];_.kind==="custom"&&_.hex===i&&(f[h]={kind:"custom",hex:a})}return{customAccents:d,customAccentNames:Ki(u,d),accent:f}}),rightSlotWidth:0,chatSidebarWidth:yp,chatSidebarRegions:HC,chatSidebarView:Io,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:O_,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:NP,consoleOpenIntent:null,consoleCommandIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:zP,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(o=>({isCommandPaletteOpen:!o.isCommandPaletteOpen,commandPaletteQuery:o.isCommandPaletteOpen?o.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(o=>n?{...En("isCanvasOpen"),...Wn(o,"canvas")}:{isCanvasOpen:!1,...fr(o,"canvas")})},setRunPanelOpen:n=>{e(o=>n?{...En("isRunPanelOpen"),...Wn(o,"run")}:{isRunPanelOpen:!1,...fr(o,"run")})},setBrowserPaneOpen:n=>{e(o=>n?{...En("isBrowserPaneOpen"),...Wn(o,"browser")}:{isBrowserPaneOpen:!1,...fr(o,"browser")})},setConsolePaneOpen:n=>{e(o=>n?{...En("isConsolePaneOpen"),...Wn(o,"console")}:{isConsolePaneOpen:!1,...fr(o,"console")})},setCodeReviewPaneOpen:n=>{e(o=>n?{...En("isCodeReviewPaneOpen"),...Wn(o,"code")}:{isCodeReviewPaneOpen:!1,...fr(o,"code")})},clearCodeReviewReveal:n=>{e(o=>o.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...En("isCodeReviewPaneOpen"),...Wn(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,o,r)=>{e(i=>{const a=typeof i.rightSlotKey=="string";if(n)return{...En("isAskDrawerOpen"),askDrawerScope:o,askDrawerEvictedPane:a?null:$P(i),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?r?.dismissSlot?{...c,...DP(i)}:{...c,...bp(i.rightSlotMemory,i.rightSlotKey,!1)}:i.rightSlotKey===null?r?.dismissSlot?{...c,rightSlotLegacySeed:null}:c:r?.dismissSlot?{...c,rightSlotLegacySeed:null}:{...c,...i.askDrawerEvictedPane===null?null:{[i.askDrawerEvictedPane]:!0}}})},requestAskOpen:(n,o="menu")=>{e({askOpenIntent:{scope:n,via:o}})},clearAskOpenIntent:n=>{e(o=>o.askOpenIntent?.scope===n?{askOpenIntent:null}:{})},setConsoleActiveSurface:n=>{e({consoleActiveSurface:n})},requestConsoleOpen:n=>{e({consoleOpenIntent:n})},requestConsoleCommand:n=>{const o={sessionId:n.sessionId,command:n.command,submit:n.submit===!0,nonce:MP(),filedAt:Date.now(),...n.askId===void 0?{}:{askId:n.askId},...n.questionId===void 0?{}:{questionId:n.questionId}};return e({consoleCommandIntent:o}),o},clearConsoleCommandIntent:n=>{e(o=>o.consoleCommandIntent?.nonce===n?{consoleCommandIntent:null}:{})},clearConsoleOpenIntent:n=>{e(o=>o.consoleOpenIntent===n?{consoleOpenIntent:null}:{})},setConsoleLiveSurface:(n,o)=>{e(r=>{if(n===null||o<=0)return r.consoleLiveSurface===null?{}:{consoleLiveSurface:null};const i=r.consoleLiveSurface;return i?.sessionId===n&&i.count===o?{}:{consoleLiveSurface:{sessionId:n,count:o}}})},markConsoleUnseen:(n,o)=>{e(r=>r.consoleUnseen.some(i=>i.surface===o)?{}:{consoleUnseen:[...r.consoleUnseen,{sessionId:n,surface:o,at:Date.now()}]})},clearConsoleUnseen:n=>{const o=Array.isArray(n)?n:[n];e(r=>{const i=r.consoleUnseen.filter(a=>!o.includes(a.surface));return i.length===r.consoleUnseen.length?{}:{consoleUnseen:i}})},setRightSlotWidth:n=>{e({rightSlotWidth:n})},restoreDefaultRightSlotWidth:()=>{e({rightSlotWidth:0})},bindRightSlotKey:(n,o)=>{e(r=>{let i=r.rightSlotMemory,a=r.rightSlotLegacySeed;const c=o?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(i=CP(i,c,n)),n===null||(cd(n)?a=null:a!==null&&li(i,n)===void 0&&(i=C_(i,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:i,rightSlotLegacySeed:a,...bp(i,n,r.isAskDrawerOpen)}})},setRightSlotRoute:n=>{const o=t().rightSlotRoute;o.mounted===n.mounted&&o.session===n.session||e({rightSlotRoute:{...n}})},setShortcutBinding:(n,o,r)=>{if(o===null){e(a=>{const c={...a.shortcutBindings};return delete c[n],{shortcutBindings:c}});return}const i=nd(o);i!==null&&oO(i,n,t().shortcutBindings,"linux",r)===null&&e(a=>({shortcutBindings:{...a.shortcutBindings,[n]:i}}))},clearShortcutBinding:n=>{e(o=>({shortcutBindings:{...o.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(o=>({...En("isRunPanelOpen"),...Wn(o,"run"),runPanelReveal:{section:n,nonce:(o.runPanelReveal?.nonce??0)+1}}))},clearRunPanelReveal:n=>{e(o=>o.runPanelReveal?.nonce===n?{runPanelReveal:null}:{})},setChatSidebarWidth:n=>{e({chatSidebarWidth:Math.min(Vl,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:yp})},rememberMention:(n,o)=>{e(r=>{const i=r.mentionRecents,a=i?.cwd===n?i.paths:[],c=[o,...a.filter(l=>l!==o)].slice(0,FP);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,o)=>{e(r=>({profileRecents:{...r.profileRecents,[n]:ZP(r.profileRecents[n]??[],o)}}))},rememberConversation:n=>{e(o=>{const r=JP(o.conversationRecents),i=YP(r,n);return i.length===r.length&&i.every((a,c)=>a===r[c])?o:{conversationRecents:i}})}}),{name:"ui-preferences-storage",version:KP,migrate:tM,partialize:QP,merge:eM}));function ZP(e,t){return[t,...e.filter(n=>n!==t)].slice(0,UP)}function YP(e,t){return[t,...e.filter(n=>n!==t)].slice(0,BP)}const XP=[];function JP(e){return Array.isArray(e)?e:XP}function QP(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:o,consoleCommandIntent:r,consoleLiveSurface:i,askOpenIntent:a,isAskDrawerOpen:c,askDrawerScope:l,askDrawerEvictedPane:d,rightSlotRoute:u,isCanvasOpen:f,isRunPanelOpen:h,isBrowserPaneOpen:_,isConsolePaneOpen:y,isCodeReviewPaneOpen:v,rightSlotKey:b,...p}=e;return{...p,rightSlotMemory:qP(e.rightSlotMemory)}}function qP(e){return(e??O_).filter(([t])=>!cd(t))}function eM(e,t){const n=e??{},{isCanvasOpen:o,isRunPanelOpen:r,isBrowserPaneOpen:i,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:ed(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:OP(n.rightSlotMemory),rightSlotLegacySeed:T_(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:rO(n.shortcutBindings),contrast:R_(n.contrast),accent:x_(n.accent,Vc),customAccents:Vo(n.customAccents),customAccentNames:Ki(n.customAccentNames,Vo(n.customAccents)),customThemeId:id(n.customThemeId)}}function tM(e,t){const n={...e??{}};if(t<1&&nM(n),t<2)for(const o of VP)delete n[o];if(t<3){let o=null;for(const r of Gc)if(n[vp(r)]===!0){o=r;break}o!==null&&(n.rightSlotLegacySeed=o);for(const r of Gc)delete n[vp(r)]}return t<4&&(n.finderFiles=ed(n.finderFiles)),t<5&&(n.contrast=R_(n.contrast),n.accent=x_(n.accent,Vc),n.customAccents=Vo(n.customAccents),n.customThemeId=id(n.customThemeId)),n}function nM(e){const t=[["canvasWidth",800],["runPanelWidth",420],["browserPanelWidth",640],["consolePanelWidth",796]];let n=0;for(const[o,r]of t){const i=e[o];if(typeof i=="number"&&i>0&&i!==r){n=i;break}}for(const[o]of t)delete e[o];e.rightSlotWidth=n}const zc=e=>e.replace(/\\/g,"/"),P_=()=>window.location.hash?zc(window.location.hash.substring(1)):zc(window.location.pathname),GF=(e,t)=>{if(t!==null&&(e===t||e.startsWith(`${t}/`)||e.startsWith(`${t}\\`))){const o=e.substring(t.length);return o.startsWith("/")||o.startsWith("\\")||o===""?`~${o.replace(/\\/g,"/")}`:`~/${o.replace(/\\/g,"/")}`}return e==="~"?"~":e.replace(/\\/g,"/")},zF=(e,t)=>{if(e.length<=t)return e;const n=e.split("/"),o=n[n.length-1]??"";if(o.length+1>=t)return`…${o.slice(-39)}`;const r=n[0]==="~"||n[0]==="",i=r?n.slice(0,2):n.slice(0,1),a=n.slice(i.length),c=y=>{const v=t-y.length-(y?3:2);let b=[];for(let p=a.length-1;p>=0;p-=1){const A=[a[p],...b];if(A.join("/").length>v)break;b=A}return b},l=(y,v)=>y?`${y}/…/${v.join("/")}`:`…/${v.join("/")}`,d=i.join("/"),u=c(d);if(u.length>0)return u.length===a.length?e:l(d,u);const f=r?n[0]:"",h=c(f);if(h.length>0)return l(f,h);const _=t-(f?`${f}/…/`.length:2);return _>0?l(f,[o.slice(-_)]):"…"},KF=(e,t)=>zc(e).includes(t);function oM(e,t){const n=Je.getState();if(n.activeSessionId===e&&!n.activeDraftKey)return null;const o=Uo.begin(e,t);return dR(Uo,o,()=>Je.getState(),Je.subscribe),o}let kp=!1;function rM(){if(kp||typeof window>"u"||typeof window.addEventListener!="function")return;kp=!0;const e=()=>{const t=_0();t&&(P_().split("/").includes(t)||b0(t))};window.addEventListener("hashchange",e),window.addEventListener("popstate",e)}function VF(e,t,n="open"){const o=oM(t,n);if(o!==null){Uo.note(t,"request",o,{fallback:!0});const c=Je.getState();try{v0(t,{remoteOwned:Tg(c.sessions,c.placementFacts,t)}),rM()}catch{}}const i=Je.getState().openSession(t),a=`/chat/${t}`;return e(a),i.then(c=>{if(c||P_()!==a)return;const l=Je.getState();if(l.activeDraftKey){e("/chat",{replace:!0});return}const d=l.activeSessionId;e(d?`/chat/${d}`:"/chat",{replace:!0})}),i}const Kc=e=>{const t=JSON.stringify(Object.keys(e).sort().map(o=>[o,e[o]]));let n=2166136261;for(let o=0;o<t.length;o++)n^=t.charCodeAt(o),n=Math.imul(n,16777619)>>>0;return n.toString(36).padStart(7,"0").slice(-8)},iM=(e,{contrast:t=0,accent:n={kind:"theme"},id:o,paletteAccent:r,preserveSecondary:i=!1}={})=>{const a=!n||n.kind==="theme";if(t===0&&a)return{identity:!0,palette:e,id:o,effectiveContrast:0,requestedContrast:0,accentApplied:!0,accentAdjusted:0};const c=lP(e,t,{id:o});let l=c.palette,d=!0,u=0;if(!a){const f=gP(l,n,{authored:e,id:o,paletteAccent:r,preserveSecondary:i});l=f.palette,d=f.applied,u=f.adjusted}return l===e?{identity:!0,palette:e,id:o,effectiveContrast:0,requestedContrast:t,accentApplied:d,accentAdjusted:u}:{identity:!1,palette:l,id:`lo-${Kc(l)}`,effectiveContrast:c.effectiveContrast,requestedContrast:t,accentApplied:d,accentAdjusted:u}},Sp="lo-composed-theme",sM=4,Gn=new Map,aM=(e,t)=>{const n=Gn.get(e);if(n)return Gn.delete(e),Gn.set(e,n),n;const o=H_(t);if(Gn.set(e,o),Gn.size>sM){const r=Gn.keys().next().value;r!==void 0&&Gn.delete(r)}return o},cM=e=>Zc(e)?.palette.accent,lM=16,wo=new Map,dM=(e,t,n)=>{const o=Ep(e.themeName),r=Zc(o.id);if(!r)throw new Error(`no palette for theme ${o.id}`);const i=t??r.palette,a=i.mode,c=n??o.id,l=e.contrast[a]??0,d=e.accent[a],u=JSON.stringify([o.id,n??null,t?Kc(t):null,l,d??null]);let f=wo.get(u);if(f?wo.delete(u):f=iM(i,{contrast:l,accent:d,id:c,preserveSecondary:t!==void 0,paletteAccent:cM}),wo.set(u,f),wo.size>lM){const _=wo.keys().next().value;_!==void 0&&wo.delete(_)}if(f.identity&&!n)return{...f,id:o.id,muiTheme:o.theme};const h=`lo-${Kc(f.palette)}`;return{...f,id:h,identity:!1,muiTheme:aM(h,f.palette)}},uM=(e,t)=>Yc(e)&&Object.entries(t).every(([n,o])=>n==="mode"||Xc(o))&&(t.mode==="dark"||t.mode==="light"),ZF=(e,t=document,n,o,r=i=>dM(i,n,o))=>{let i=r(e);if(!i.identity&&!uM(i.id,i.palette)){console.error(`[theme] refused to publish composed theme ${JSON.stringify(i.id).slice(0,60)}: an id or value is outside the CSS grammar; showing the built-in theme`);const l=Ep(e.themeName),d=Zc(l.id);if(!d)throw new Error(`no palette for theme ${l.id}`);i={identity:!0,palette:d.palette,id:l.id,effectiveContrast:0,requestedContrast:i.requestedContrast,accentApplied:!1,accentAdjusted:0,muiTheme:l.theme}}const a=t.documentElement,c=t.getElementById(Sp);if(i.identity)c?.remove();else{const l=c??t.createElement("style");l.id=Sp,l.textContent=Ip(i.id,i.palette),c||t.head.appendChild(l)}return dT(t,i.identity?null:i.palette),a.dataset.theme=i.id,a.classList.toggle("dark",i.palette.mode==="dark"),i},YF=e=>({themeName:e.themeName,customThemeId:e.customThemeId??null,contrast:e.contrast,accent:e.accent}),XF=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{mg as $,Je as A,HN as B,VN as C,mF as D,m1 as E,p1 as F,ZF as G,YF as H,WF as I,lt as J,VC as K,XF as L,dM as M,s as N,mh as O,du as P,Ae as Q,D$ as R,mt as S,N$ as T,wg as U,Vx as V,Zx as W,IN as X,hg as Y,yN as Z,kN as _,gj as a,bP as a$,wN as a0,_N as a1,EN as a2,vN as a3,SN as a4,uL as a5,Qm as a6,Rg as a7,YN as a8,XN as a9,zc as aA,Ik as aB,TM as aC,Hj as aD,MM as aE,ty as aF,PM as aG,jM as aH,bM as aI,Cp as aJ,Zs as aK,ol as aL,gM as aM,Xv as aN,Yv as aO,mR as aP,$x as aQ,SD as aR,ID as aS,AD as aT,ng as aU,SL as aV,cC as aW,kL as aX,lC as aY,dC as aZ,gt as a_,Ns as aa,yL as ab,JP as ac,bD as ad,yn as ae,st as af,Yo as ag,Bc as ah,mM as ai,E0 as aj,Vy as ak,Zy as al,gu as am,NM as an,lN as ao,JD as ap,FM as aq,K_ as ar,We as as,ec as at,Is as au,Ny as av,wr as aw,hj as ax,aj as ay,ch as az,dj as b,uj as b$,RF as b0,jF as b1,AP as b2,iL as b3,EP as b4,EF as b5,en as b6,CF as b7,mp as b8,SF as b9,Nd as bA,Cb as bB,Ld as bC,Tb as bD,Rb as bE,rL as bF,P1 as bG,ZN as bH,NN as bI,P_ as bJ,KF as bK,Kv as bL,xM as bM,RM as bN,AM as bO,IM as bP,OM as bQ,Yp as bR,Ut as bS,Er as bT,u$ as bU,f$ as bV,Ey as bW,R0 as bX,pj as bY,tj as bZ,fj as b_,IF as ba,AF as bb,xF as bc,TF as bd,OF as be,$F as bf,MS as bg,I1 as bh,mj as bi,__ as bj,iM as bk,PF as bl,vF as bm,WC as bn,pF as bo,_D as bp,YD as bq,ni as br,rt as bs,Rp as bt,gb as bu,yb as bv,Sb as bw,xb as bx,Ib as by,Ab as bz,_j as c,NL as c$,FF as c0,_F as c1,_n as c2,Vd as c3,il as c4,rw as c5,Ss as c6,th as c7,bN as c8,ae as c9,ON as cA,GF as cB,WL as cC,GL as cD,jC as cE,Wf as cF,PL as cG,nF as cH,oF as cI,rF as cJ,OL as cK,uD as cL,cf as cM,pD as cN,fD as cO,hD as cP,xg as cQ,oL as cR,iF as cS,zL as cT,YL as cU,XL as cV,KL as cW,VL as cX,Io as cY,xL as cZ,d_ as c_,gN as ca,Eo as cb,Ic as cc,Ac as cd,hN as ce,mN as cf,dN as cg,uN as ch,fN as ci,bF as cj,HF as ck,GP as cl,BF as cm,lh as cn,nj as co,ZM as cp,uh as cq,f0 as cr,py as cs,tb as ct,hy as cu,ql as cv,JM as cw,Cf as cx,oj as cy,E1 as cz,la as d,HP as d$,eF as d0,qr as d1,qL as d2,gD as d3,tF as d4,Bo as d5,Mf as d6,FL as d7,LL as d8,UL as d9,cF as dA,Ni as dB,ei as dC,lF as dD,fF as dE,LM as dF,$M as dG,wL as dH,zF as dI,hF as dJ,VA as dK,mD as dL,EM as dM,kR as dN,yj as dO,LF as dP,$c as dQ,NP as dR,pr as dS,NF as dT,mL as dU,gL as dV,hL as dW,Xl as dX,Jl as dY,ej as dZ,qM as d_,HL as da,BL as db,ML as dc,JL as dd,QL as de,IL as df,AL as dg,AN as dh,xN as di,TL as dj,RN as dk,Fs as dl,CL as dm,JN as dn,l_ as dp,ZL as dq,$L as dr,DL as ds,jL as dt,RL as du,sF as dv,aF as dw,dF as dx,uF as dy,BC as dz,lL as e,e_ as e$,qg as e0,WP as e1,wp as e2,vD as e3,Zl as e4,yD as e5,wD as e6,qN as e7,QN as e8,eL as e9,Af as eA,LN as eB,sC as eC,WN as eD,pN as eE,WM as eF,zM as eG,GM as eH,sj as eI,Bs as eJ,Hs as eK,g_ as eL,oO as eM,td as eN,eN as eO,um as eP,To as eQ,L$ as eR,Nn as eS,no as eT,uy as eU,gF as eV,Xa as eW,vL as eX,oM as eY,pL as eZ,qT as e_,nL as ea,tL as eb,V0 as ec,ai as ed,lj as ee,GN as ef,Np as eg,js as eh,_x as ei,TD as ej,iN as ek,sN as el,Ig as em,b1 as en,Uo as eo,Ms as ep,zN as eq,KN as er,Pk as es,XD as et,PD as eu,DN as ev,Ex as ew,u1 as ex,Eg as ey,l1 as ez,NT as f,RD as f$,bj as f0,vj as f1,lb as f2,KC as f3,kM as f4,cd as f5,DF as f6,jd as f7,wM as f8,yM as f9,Yl as fA,_L as fB,Qg as fC,oC as fD,Kl as fE,KM as fF,Jd as fG,Uw as fH,VM as fI,by as fJ,QD as fK,UD as fL,BD as fM,BM as fN,HM as fO,FD as fP,og as fQ,bR as fR,Rm as fS,h_ as fT,Qh as fU,Gw as fV,YM as fW,kD as fX,ED as fY,OD as fZ,CD as f_,Ua as fa,Rr as fb,pb as fc,Eb as fd,Ob as fe,vM as ff,zE as fg,sL as fh,uo as fi,zg as fj,cL as fk,FT as fl,Hg as fm,aL as fn,dL as fo,fL as fp,ij as fq,cj as fr,Es as fs,kt as ft,mb as fu,fh as fv,k1 as fw,Xo as fx,UF as fy,bL as fz,M0 as g,e$ as g$,gR as g0,$D as g1,jD as g2,Co as g3,QM as g4,rj as g5,XM as g6,Tj as g7,ml as g8,ul as g9,T$ as gA,M$ as gB,j$ as gC,P$ as gD,O$ as gE,g$ as gF,yE as gG,vE as gH,Hr as gI,b$ as gJ,m$ as gK,p$ as gL,s$ as gM,Bu as gN,d$ as gO,v$ as gP,l$ as gQ,c$ as gR,a$ as gS,o$ as gT,Xj as gU,n$ as gV,Gj as gW,zj as gX,Vj as gY,Kj as gZ,qh as g_,Dn as ga,nn as gb,vs as gc,yF as gd,kF as ge,MF as gf,rd as gg,jO as gh,$O as gi,E_ as gj,wF as gk,id as gl,wE as gm,_$ as gn,h$ as go,R$ as gp,x$ as gq,$$ as gr,C$ as gs,k$ as gt,S$ as gu,E$ as gv,w$ as gw,I$ as gx,A$ as gy,y$ as gz,Pb as h,dD as h$,Nk as h0,lD as h1,eS as h2,zx as h3,t$ as h4,kI as h5,nD as h6,wm as h7,rD as h8,q$ as h9,Mu as hA,F$ as hB,Mj as hC,Qj as hD,tE as hE,Jh as hF,Lh as hG,Nj as hH,qd as hI,nd as hJ,zC as hK,vk as hL,Yj as hM,QS as hN,qj as hO,r$ as hP,i$ as hQ,Jj as hR,Qk as hS,$j as hT,Gk as hU,Lj as hV,Fj as hW,Bj as hX,Uj as hY,Wj as hZ,Zj as h_,eD as ha,oD as hb,vI as hc,ma as hd,tD as he,SI as hf,X$ as hg,B$ as hh,Z$ as hi,sD as hj,U$ as hk,Y$ as hl,Q$ as hm,cD as hn,aD as ho,J$ as hp,H$ as hq,W$ as hr,G$ as hs,z$ as ht,K$ as hu,V$ as hv,iD as hw,my as hx,gy as hy,_y as hz,V_ as i,FN as i$,EL as i0,zD as i1,WD as i2,MR as i3,VD as i4,GD as i5,HD as i6,KD as i7,ZD as i8,jj as i9,Wr as iA,Oj as iB,uk as iC,Th as iD,fl as iE,Ih as iF,J0 as iG,Q0 as iH,xj as iI,ly as iJ,Rj as iK,Sj as iL,Ij as iM,xu as iN,kj as iO,wj as iP,Aj as iQ,Tu as iR,Ej as iS,ih as iT,Pj as iU,Cj as iV,BN as iW,MD as iX,LD as iY,DD as iZ,ND as i_,Dj as ia,vc as ib,Qn as ic,MN as id,jN as ie,TN as ig,CN as ih,$N as ii,Ql as ij,hC as ik,UM as il,bc as im,xD as io,tN as ip,nN as iq,rN as ir,hR as is,oN as it,aN as iu,jx as iv,cN as iw,D0 as ix,PN as iy,xh as iz,Ge as j,UN as j0,Jv as j1,Qd as j2,qD as j3,ns as k,_M as l,Dp as m,I0 as n,VF as o,DM as p,My as q,x0 as r,jy as s,$y as t,vb as u,Dy as v,ri as w,CM as x,SM as y,Tg as z};
|