local-operator-ui 0.54.4 → 0.54.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.
Files changed (95) hide show
  1. package/out/renderer/assets/{_basePickBy-B3xt3Hm3.js → _basePickBy-DZaFrUMm.js} +1 -1
  2. package/out/renderer/assets/{_baseUniq-1pJjxjt2.js → _baseUniq-DqCgwxpO.js} +1 -1
  3. package/out/renderer/assets/{agent-details-page-BhFyhOGB.js → agent-details-page-t7-pZk2W.js} +1 -1
  4. package/out/renderer/assets/{agent-hub-page-BFvHoklr.js → agent-hub-page-DoFvojYM.js} +1 -1
  5. package/out/renderer/assets/{agents-page-B4zlrdr_.js → agents-page-DbU68lGa.js} +3 -3
  6. package/out/renderer/assets/{appearance-C0lPtfkY.js → appearance-CB5X23Pc.js} +35 -35
  7. package/out/renderer/assets/{arc-DsmiYIPI.js → arc-BMRMvVxq.js} +1 -1
  8. package/out/renderer/assets/{architectureDiagram-IEHRJDOE-l-eL9acY.js → architectureDiagram-IEHRJDOE-D-KJMV11.js} +1 -1
  9. package/out/renderer/assets/{avatar-cropper-pHmeKLyi.js → avatar-cropper-B0SvTl8W.js} +1 -1
  10. package/out/renderer/assets/{blockDiagram-JOT3LUYC-xQ3Xse8W.js → blockDiagram-JOT3LUYC-CMfOx4K5.js} +1 -1
  11. package/out/renderer/assets/{book-open-CurIwRfe.js → book-open-CjfQcb_6.js} +1 -1
  12. package/out/renderer/assets/browser-page-WgEm1Xnj.js +1 -0
  13. package/out/renderer/assets/{browser-webauthn-prompt-DSn7BuqK.js → browser-webauthn-prompt-DEq582Iy.js} +1 -1
  14. package/out/renderer/assets/{c4Diagram-VJAJSXHY-DK3mZwLN.js → c4Diagram-VJAJSXHY-DFZQpr6B.js} +1 -1
  15. package/out/renderer/assets/channel-biJ1kQzU.js +1 -0
  16. package/out/renderer/assets/{chunk-4BMEZGHF-BxS694e8.js → chunk-4BMEZGHF-BS36jJLt.js} +1 -1
  17. package/out/renderer/assets/{chunk-A2AXSNBT-DhazzPck.js → chunk-A2AXSNBT-hZaV-sxd.js} +1 -1
  18. package/out/renderer/assets/{chunk-AEK57VVT-DAzMOtBv.js → chunk-AEK57VVT-aTLD2maD.js} +1 -1
  19. package/out/renderer/assets/{chunk-D6G4REZN-DQ0Y9bJZ.js → chunk-D6G4REZN-BFayHuJJ.js} +1 -1
  20. package/out/renderer/assets/{chunk-RZ5BOZE2-ByJtdR6O.js → chunk-RZ5BOZE2-VgkA_iSV.js} +1 -1
  21. package/out/renderer/assets/{chunk-XZIHB7SX-DDCRuqfN.js → chunk-XZIHB7SX-Bvcutn92.js} +1 -1
  22. package/out/renderer/assets/classDiagram-GIVACNV2-ZQSWLdsu.js +1 -0
  23. package/out/renderer/assets/classDiagram-v2-COTLJTTW-ZQSWLdsu.js +1 -0
  24. package/out/renderer/assets/clone-DlCgJMd-.js +1 -0
  25. package/out/renderer/assets/{console-mirror-DNf7G2I0.js → console-mirror-XM_5bSKF.js} +1 -1
  26. package/out/renderer/assets/{consoleCapture-4P65rdq4.js → consoleCapture-Bn1Se_Qu.js} +1 -1
  27. package/out/renderer/assets/{conversation-input-sync-uyyuExNW.js → conversation-input-sync-Btmg29tU.js} +185 -185
  28. package/out/renderer/assets/{dagre-OKDRZEBW-DMkRFzm8.js → dagre-OKDRZEBW-D3hmNQbR.js} +1 -1
  29. package/out/renderer/assets/{diagram-SSKATNLV-4BGyMBO2.js → diagram-SSKATNLV-Bo5ny4Px.js} +1 -1
  30. package/out/renderer/assets/{diagram-VNBRO52H-DE1S-9qp.js → diagram-VNBRO52H-BsbyAzN9.js} +1 -1
  31. package/out/renderer/assets/{erDiagram-Q7BY3M3F-BOWvsXlh.js → erDiagram-Q7BY3M3F-BTP2_iSu.js} +1 -1
  32. package/out/renderer/assets/{error-boundary-VQD4FYpL.js → error-boundary-CHZZV6GH.js} +1 -1
  33. package/out/renderer/assets/{flowDiagram-4HSFHLVR-DvlZwtKD.js → flowDiagram-4HSFHLVR-Ud_0FNud.js} +1 -1
  34. package/out/renderer/assets/{ganttDiagram-APWFNJXF-Nq3e8H0P.js → ganttDiagram-APWFNJXF-BNqH0XOA.js} +1 -1
  35. package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-Jy8L5k7r.js → gitGraphDiagram-7IBYFJ6S-D8aBZ0Km.js} +1 -1
  36. package/out/renderer/assets/{graph-DPEEIY8Z.js → graph-DPAIIwRY.js} +1 -1
  37. package/out/renderer/assets/{heart-oZzzojv0.js → heart-DULszDIp.js} +1 -1
  38. package/out/renderer/assets/index-4MqHfoFs.css +1 -0
  39. package/out/renderer/assets/{index-DKfxb0W8.js → index-8UdhbmJT.js} +1 -1
  40. package/out/renderer/assets/{index-DngV7CIb.js → index-DprObCAh.js} +1 -1
  41. package/out/renderer/assets/index-_Gw7RTII.js +812 -0
  42. package/out/renderer/assets/infoDiagram-PH2N3AL5-cBpoGRcb.js +2 -0
  43. package/out/renderer/assets/{inline-error-boundary-PRBq4Lqq.js → inline-error-boundary-PXvAlMsd.js} +1 -1
  44. package/out/renderer/assets/{installer-DS58Bksf.js → installer-Co-o1h4D.js} +1 -1
  45. package/out/renderer/assets/{journeyDiagram-U35MCT3I-DwaiHfaH.js → journeyDiagram-U35MCT3I-DTzB73Ea.js} +1 -1
  46. package/out/renderer/assets/{kanban-definition-NDS4AKOZ-htfXUeZE.js → kanban-definition-NDS4AKOZ-1Xh0pBhh.js} +1 -1
  47. package/out/renderer/assets/{layout-DvTgSYYH.js → layout-DK-wlGb7.js} +1 -1
  48. package/out/renderer/assets/{legacy-agents-page-r1Y-kucK.js → legacy-agents-page-DKqjGO62.js} +1 -1
  49. package/out/renderer/assets/{library-page-BDCo022s.js → library-page-Cw50EiPO.js} +3 -3
  50. package/out/renderer/assets/{log-in-D0YxNJPh.js → log-in-zdV-V-md.js} +1 -1
  51. package/out/renderer/assets/{mermaid.core-BlHNEBaL.js → mermaid.core-D0jgYait.js} +5 -5
  52. package/out/renderer/assets/{mesh-page-DB5MLSgb.js → mesh-page-DYLY4u02.js} +1 -1
  53. package/out/renderer/assets/{mindmap-definition-ALO5MXBD-BSjLrA1R.js → mindmap-definition-ALO5MXBD-BYoEyGWU.js} +1 -1
  54. package/out/renderer/assets/{mini-3O_1fVj2.js → mini-BU9tnv5T.js} +1 -1
  55. package/out/renderer/assets/{notebook-pen-DDEgcfZg.js → notebook-pen-8ebpH8lM.js} +1 -1
  56. package/out/renderer/assets/{notifications-page-RZypnGHj.js → notifications-page-LZJYoumt.js} +1 -1
  57. package/out/renderer/assets/{org-access-BMbZPErU.js → org-access-DxK2DWEw.js} +1 -1
  58. package/out/renderer/assets/{org-surface-gate-CoL4bFMI.js → org-surface-gate-BfmgsJlA.js} +1 -1
  59. package/out/renderer/assets/{page-header-B8wJOF6S.js → page-header-D6f_9LyG.js} +1 -1
  60. package/out/renderer/assets/{pieDiagram-IB7DONF6-ZPW8fXB0.js → pieDiagram-IB7DONF6-CDWzyqOF.js} +1 -1
  61. package/out/renderer/assets/{project-markdown-C7oljPaw.js → project-markdown-XWo6y3uc.js} +1 -1
  62. package/out/renderer/assets/{projects-page-CI9lrQGZ.js → projects-page-n8lpgytN.js} +1 -1
  63. package/out/renderer/assets/{publication-validation-CASp138d.js → publication-validation-DguACpdw.js} +1 -1
  64. package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-CNkizv5T.js → quadrantDiagram-7GDLP6J5-CpgfH2XB.js} +1 -1
  65. package/out/renderer/assets/{radar-MK3ICKWK-BV48_bSd.js → radar-MK3ICKWK-AP9ZUX29.js} +1 -1
  66. package/out/renderer/assets/{radient-auth-buttons-Bj7oxOXt.js → radient-auth-buttons-BxfXvDEx.js} +1 -1
  67. package/out/renderer/assets/{requirementDiagram-KVF5MWMF-Dq3xa1rx.js → requirementDiagram-KVF5MWMF-BBtc7gSJ.js} +1 -1
  68. package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-z5QAURtH.js → sankeyDiagram-QLVOVGJD-r7BhZc0f.js} +1 -1
  69. package/out/renderer/assets/{schedules-page-ZPRVVT5B.js → schedules-page-DGiVl8mF.js} +1 -1
  70. package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-C6Y-stRE.js → sequenceDiagram-X6HHIX6F-CkNyv10e.js} +1 -1
  71. package/out/renderer/assets/{settings-page-1tmm-IEy.js → settings-page-xgfLf7N7.js} +1 -1
  72. package/out/renderer/assets/{smartart-C2NxGaUI.js → smartart-BmcJjsFr.js} +1 -1
  73. package/out/renderer/assets/{stateDiagram-DGXRK772-C3KntpLD.js → stateDiagram-DGXRK772-kRpoDgVb.js} +1 -1
  74. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-BQDla68w.js +1 -0
  75. package/out/renderer/assets/{team-bridge-page-CkVWtil3.js → team-bridge-page-zJNV9h6-.js} +1 -1
  76. package/out/renderer/assets/{team-bridge-scope-preference-DXWQxPWW.js → team-bridge-scope-preference-B9T6Qfv4.js} +1 -1
  77. package/out/renderer/assets/{timeline-definition-BDJGKUSR-Dx9fTROE.js → timeline-definition-BDJGKUSR-Bjyd4RWc.js} +1 -1
  78. package/out/renderer/assets/{use-download-agent-mutation-CqJJZFQx.js → use-download-agent-mutation-C1BhoJl3.js} +1 -1
  79. package/out/renderer/assets/{use-session-snapshot-31ExJ3hP.js → use-session-snapshot-DutdCMMH.js} +1 -1
  80. package/out/renderer/assets/{xychartDiagram-VJFVF3MP-BczgRDpX.js → xychartDiagram-VJFVF3MP-1TFByBzX.js} +1 -1
  81. package/out/renderer/console-capture.html +5 -5
  82. package/out/renderer/index.html +7 -7
  83. package/out/renderer/installer.html +4 -4
  84. package/out/renderer/mini.html +7 -7
  85. package/package.json +1 -1
  86. package/out/renderer/assets/browser-page-DG87TZbD.js +0 -1
  87. package/out/renderer/assets/channel-CVH_R33H.js +0 -1
  88. package/out/renderer/assets/classDiagram-GIVACNV2-BmyF-xYp.js +0 -1
  89. package/out/renderer/assets/classDiagram-v2-COTLJTTW-BmyF-xYp.js +0 -1
  90. package/out/renderer/assets/clone-T1tJd2zj.js +0 -1
  91. package/out/renderer/assets/index-Gls4i-Rf.js +0 -812
  92. package/out/renderer/assets/index-WCL2AOPk.css +0 -1
  93. package/out/renderer/assets/infoDiagram-PH2N3AL5-CZznGhUy.js +0 -2
  94. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-Bm1UW0iD.js +0 -1
  95. /package/out/renderer/assets/{index-nXNEayCN.js → index-kEyWW56d.js} +0 -0
@@ -1,49 +1,49 @@
1
- import{r as R,j as s_,b as od,D as i_,l as Oc,m as tp,n as Pc,o as a_}from"./index-nXNEayCN.js";import{c as nn,t as _,a as c_}from"./messages-CUhxkxii.js";import{P as l_,i as Mc,a as jc,p as np}from"./roles-D1pcbxAx.js";const sd=new Map,id=new Map,ad=new Map,cd=new Map;function $c(e){return e===void 0?"":JSON.stringify(e)}function Nc(e,t){const n=`${e}\0${$c(t)}`;let r=sd.get(n);return r===void 0&&(r=new Intl.DateTimeFormat(e,t),sd.set(n,r)),r}function d_(e,t){const n=`${e}\0${$c(t)}`;let r=id.get(n);return r===void 0&&(r=new Intl.NumberFormat(e,t),id.set(n,r)),r}function YO(e,t,n){return Nc(n??nn(),t).format(e)}function JO(e,t,n){return Nc(n??nn(),t).format(e)}function QO(e,t,n){return Nc(n??nn(),t).format(e)}function u_(e,t,n){return d_(n??nn(),t).format(e)}function XO(e,t,n,r){const o=r??nn(),s=`${o}\0${$c(n)}`;let a=ad.get(s);return a===void 0&&(a=new Intl.RelativeTimeFormat(o,n),ad.set(s,a)),a.format(e,t)}const f_={B:"byte",KB:"kilobyte",MB:"megabyte",GB:"gigabyte",TB:"terabyte",PB:"petabyte"},ld=new Map,dd=new Map;function p_(e){return e.split("-")[0]?.toLowerCase()==="en"}function h_(e,t){if(e==="KiB"||e==="MiB"||e==="GiB"||p_(t))return e;const n=`${t}\0${e}`;let r=ld.get(n);if(r===void 0){r=e;try{r=new Intl.NumberFormat(t,{style:"unit",unit:f_[e],unitDisplay:"narrow"}).formatToParts(1).find(s=>s.type==="unit")?.value??e}catch{}ld.set(n,r)}return r}function m_(e){let t=dd.get(e);if(t===void 0){t=" ";try{t=new Intl.NumberFormat(e,{style:"unit",unit:"kilobyte",unitDisplay:"short"}).formatToParts(1).find(r=>r.type==="literal")?.value??" "}catch{}dd.set(e,t)}return t}function mo(e,t,n,r){const o=nn();return`${u_(e,{useGrouping:!1,...n},o)}${m_(o)}${h_(t,o)}`}function Ts(e,t){const n=nn();let r=cd.get(n);return r===void 0&&(r=new Intl.ListFormat(n,{type:"conjunction",style:"narrow"}),cd.set(n,r)),r.format(e)}const g_={zh:";",ja:";",ur:"؛ ",ar:"؛ "};function qO(e,t){const n=nn().split("-")[0]?.toLowerCase();return e.join(g_[n??""]??"; ")}var Yo=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(){}},sr=typeof window>"u"||"Deno"in globalThis;function Tt(){}function __(e,t){return typeof e=="function"?e(t):e}function Ia(e){return typeof e=="number"&&e>=0&&e!==1/0}function rp(e,t){return Math.max(e+(t||0)-Date.now(),0)}function xr(e,t){return typeof e=="function"?e(t):e}function Ut(e,t){return typeof e=="function"?e(t):e}function ud(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:s,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==Dc(a,t.options))return!1}else if(!So(t.queryKey,a))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||o&&o!==t.state.fetchStatus||s&&!s(t))}function fd(e,t){const{exact:n,status:r,predicate:o,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(ko(t.options.mutationKey)!==ko(s))return!1}else if(!So(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Dc(e,t){return(t?.queryKeyHashFn||ko)(e)}function ko(e){return JSON.stringify(e,(t,n)=>xa(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function So(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>So(e[n],t[n])):!1}function op(e,t){if(e===t)return e;const n=pd(e)&&pd(t);if(n||xa(e)&&xa(t)){const r=n?e:Object.keys(e),o=r.length,s=n?t:Object.keys(t),a=s.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:s[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=op(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return o===a&&l===o?e:c}return t}function Ra(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 xa(e){if(!hd(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!hd(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function hd(e){return Object.prototype.toString.call(e)==="[object Object]"}function b_(e){return new Promise(t=>{setTimeout(t,e)})}function Ta(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?op(e,t):t}function v_(e){return e}function y_(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function w_(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Lc=Symbol();function sp(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Lc?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var k_=class extends Yo{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!sr&&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"}},Fc=new k_,S_=class extends Yo{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!sr&&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}},Fs=new S_;function Ca(){let e,t;const n=new Promise((o,s)=>{e=o,t=s});n.status="pending",n.catch(()=>{});function r(o){Object.assign(n,o),delete n.resolve,delete n.reject}return n.resolve=o=>{r({status:"fulfilled",value:o}),e(o)},n.reject=o=>{r({status:"rejected",reason:o}),t(o)},n}function E_(e){return Math.min(1e3*2**e,3e4)}function ip(e){return(e??"online")==="online"?Fs.isOnline():!0}var ap=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Di(e){return e instanceof ap}function cp(e){let t=!1,n=0,r=!1,o;const s=Ca(),a=b=>{r||(h(new ap(b)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>Fc.isFocused()&&(e.networkMode==="always"||Fs.isOnline())&&e.canRun(),u=()=>ip(e.networkMode)&&e.canRun(),f=b=>{r||(r=!0,e.onSuccess?.(b),o?.(),s.resolve(b))},h=b=>{r||(r=!0,e.onError?.(b),o?.(),s.reject(b))},m=()=>new Promise(b=>{o=v=>{(r||d())&&b(v)},e.onPause?.()}).then(()=>{o=void 0,r||e.onContinue?.()}),y=()=>{if(r)return;let b;const v=n===0?e.initialPromise:void 0;try{b=v??e.fn()}catch(p){b=Promise.reject(p)}Promise.resolve(b).then(f).catch(p=>{if(r)return;const A=e.retry??(sr?0:3),k=e.retryDelay??E_,C=typeof k=="function"?k(n,p):k,L=A===!0||typeof A=="number"&&n<A||typeof A=="function"&&A(n,p);if(t||!L){h(p);return}n++,e.onFail?.(n,p),b_(C).then(()=>d()?void 0:m()).then(()=>{t?h(p):y()})})};return{promise:s,cancel:a,continue:()=>(o?.(),s),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?y():m().then(y),s)}}var A_=e=>setTimeout(e,0);function I_(){let e=[],t=0,n=c=>{c()},r=c=>{c()},o=A_;const s=c=>{t?e.push(c):o(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&o(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{s(()=>{c(...l)})},schedule:s,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{o=c}}}var ot=I_(),lp=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ia(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(sr?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},R_=class extends lp{#t;#e;#n;#r;#o;#a;#i;constructor(e){super(),this.#i=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=x_(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#o?.promise}setOptions(e){this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const n=Ta(this.state.data,e,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#s({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#o?.promise;return this.#o?.cancel(e),t?t.then(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=>Ut(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Lc||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||!rp(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#o?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#o?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#o&&(this.#i?this.#o.cancel({revert:!0}):this.#o.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#o)return this.#o.continueRetry(),this.#o.promise}if(e&&this.setOptions(e),!this.options.queryFn){const c=this.observers.find(l=>l.options.queryFn);c&&this.setOptions(c.options)}const n=new AbortController,r=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},o=()=>{const c=sp(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(l),this.#i=!1,this.options.persister?this.options.persister(c,l,this):c(l)},s={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:o};r(s),this.options.behavior?.onFetch(s,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#s({type:"fetch",meta:s.fetchOptions?.meta});const a=c=>{Di(c)&&c.silent||this.#s({type:"error",error:c}),Di(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#o=cp({initialPromise:t?.initialPromise,fn:s.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){a(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){a(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:a,onFail:(c,l)=>{this.#s({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0}),this.#o.start()}#s(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...dp(n.data,this.options),fetchMeta:e.meta??null};case"success":return{...n,data:e.data,dataUpdateCount:n.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const r=e.error;return Di(r)&&r.revert&&this.#e?{...this.#e,fetchStatus:"idle"}:{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),ot.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function dp(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ip(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function x_(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var T_=class extends Yo{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,o=t.queryHash??Dc(r,t);let s=this.get(o);return s||(s=new R_({client:e,queryKey:r,queryHash:o,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(s)),s}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){ot.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=>ud(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ud(e,n)):t}notify(e){ot.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){ot.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){ot.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},C_=class extends lp{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||O_(),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=cp({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(r,o)=>{this.#r({type:"failed",failureCount:r,error:o})},onPause:()=>{this.#r({type:"pause"})},onContinue:()=>{this.#r({type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#e.canRun(this)});const t=this.state.status==="pending",n=!this.#n.canStart();try{if(!t){this.#r({type:"pending",variables:e,isPaused:n}),await this.#e.config.onMutate?.(e,this);const o=await this.options.onMutate?.(e);o!==this.state.context&&this.#r({type:"pending",context:o,variables:e,isPaused:n})}const r=await this.#n.start();return await this.#e.config.onSuccess?.(r,e,this.state.context,this),await this.options.onSuccess?.(r,e,this.state.context),await this.#e.config.onSettled?.(r,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(r,null,e,this.state.context),this.#r({type:"success",data:r}),r}catch(r){try{throw await this.#e.config.onError?.(r,e,this.state.context,this),await this.options.onError?.(r,e,this.state.context),await this.#e.config.onSettled?.(void 0,r,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,r,e,this.state.context),r}finally{this.#r({type:"error",error:r})}}finally{this.#e.runNext(this)}}#r(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),ot.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#e.notify({mutation:this,type:"updated",action:e})})}};function O_(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var P_=class extends Yo{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#e=new Map,this.#n=0}#t;#e;#n;build(e,t,n){const r=new C_({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=as(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=as(e);if(typeof t=="string"){const n=this.#e.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#e.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=as(e);if(typeof t=="string"){const r=this.#e.get(t)?.find(o=>o.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=as(e);return typeof t=="string"?this.#e.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){ot.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=>fd(t,n))}findAll(e={}){return this.getAll().filter(t=>fd(e,t))}notify(e){ot.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return ot.batch(()=>Promise.all(e.map(t=>t.continue().catch(Tt))))}};function as(e){return e.options.scope?.id}function md(e){return{onFetch:(t,n)=>{const r=t.options,o=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},h=sp(t.options,t.fetchOptions),m=async(y,b,v)=>{if(u)return Promise.reject();if(b==null&&y.pages.length)return Promise.resolve(y);const p={client:t.client,queryKey:t.queryKey,pageParam:b,direction:v?"backward":"forward",meta:t.options.meta};f(p);const A=await h(p),{maxPages:k}=t.options,C=v?w_:y_;return{pages:C(y.pages,A,k),pageParams:C(y.pageParams,b,k)}};if(o&&s.length){const y=o==="backward",b=y?up:Oa,v={pages:s,pageParams:a},p=b(r,v);c=await m(v,p,y)}else{const y=e??s.length;do{const b=l===0?a[0]??r.initialPageParam:Oa(r,c);if(l>0&&b==null)break;c=await m(c,b),l++}while(l<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function Oa(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function up(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function eP(e,t){return t?Oa(e,t)!=null:!1}function tP(e,t){return!t||!e.getPreviousPageParam?!1:up(e,t)!=null}var M_=class{#t;#e;#n;#r;#o;#a;#i;#s;constructor(e={}){this.#t=e.queryCache||new T_,this.#e=e.mutationCache||new P_,this.#n=e.defaultOptions||{},this.#r=new Map,this.#o=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#i=Fc.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#s=Fs.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#i?.(),this.#i=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#t.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(xr(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=this.#t.get(r.queryHash)?.state.data,a=__(t,s);if(a!==void 0)return this.#t.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return ot.batch(()=>this.#t.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;ot.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return ot.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=ot.batch(()=>this.#t.findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Tt).catch(Tt)}invalidateQueries(e,t={}){return ot.batch(()=>(this.#t.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=ot.batch(()=>this.#t.findAll(e).filter(o=>!o.isDisabled()).map(o=>{let s=o.fetch(void 0,n);return n.throwOnError||(s=s.catch(Tt)),o.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).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(xr(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=md(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Tt).catch(Tt)}ensureInfiniteQueryData(e){return e.behavior=md(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Fs.isOnline()?this.#e.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#t}getMutationCache(){return this.#e}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(ko(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{So(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#o.set(ko(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(r=>{So(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Dc(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===Lc&&(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()}},j_=class extends Yo{constructor(e,t){super(),this.options=t,this.#t=e,this.#s=null,this.#i=Ca(),this.options.experimental_prefetchInRender||this.#i.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#r=void 0;#o;#a;#i;#s;#m;#f;#p;#l;#d;#c;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),gd(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Pa(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Pa(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#y(),this.#w(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,n=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ut(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#k(),this.#e.setOptions(this.options),t._defaulted&&!Ra(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&_d(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||Ut(this.options.enabled,this.#e)!==Ut(t.enabled,this.#e)||xr(this.options.staleTime,this.#e)!==xr(t.staleTime,this.#e))&&this.#g();const o=this.#_();r&&(this.#e!==n||Ut(this.options.enabled,this.#e)!==Ut(t.enabled,this.#e)||o!==this.#c)&&this.#b(o)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return N_(this,n)&&(this.#r=n,this.#a=this.options,this.#o=this.#e.state),n}getCurrentResult(){return this.#r}trackResult(e,t){const n={};return Object.keys(e).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(r),t?.(r),e[r])})}),n}trackProp(e){this.#h.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),n=this.#t.getQueryCache().build(this.#t,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#u({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#u(e){this.#k();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Tt)),t}#g(){this.#y();const e=xr(this.options.staleTime,this.#e);if(sr||this.#r.isStale||!Ia(e))return;const n=rp(this.#r.dataUpdatedAt,e)+1;this.#l=setTimeout(()=>{this.#r.isStale||this.updateResult()},n)}#_(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#b(e){this.#w(),this.#c=e,!(sr||Ut(this.options.enabled,this.#e)===!1||!Ia(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||Fc.isFocused())&&this.#u()},this.#c))}#v(){this.#g(),this.#b(this.#_())}#y(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){this.#d&&(clearInterval(this.#d),this.#d=void 0)}createResult(e,t){const n=this.#e,r=this.options,o=this.#r,s=this.#o,a=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,h;if(t._optimisticResults){const g=this.hasListeners(),w=!g&&gd(e,t),S=g&&_d(e,n,t,r);(w||S)&&(u={...u,...dp(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:b}=u;h=u.data;let v=!1;if(t.placeholderData!==void 0&&h===void 0&&b==="pending"){let g;o?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(g=o.data,v=!0):g=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,g!==void 0&&(b="success",h=Ta(o?.data,g,t),f=!0)}if(t.select&&h!==void 0&&!v)if(o&&h===s?.data&&t.select===this.#m)h=this.#f;else try{this.#m=t.select,h=t.select(h),h=Ta(o?.data,h,t),this.#f=h,this.#s=null}catch(g){this.#s=g}this.#s&&(m=this.#s,h=this.#f,y=Date.now(),b="error");const p=u.fetchStatus==="fetching",A=b==="pending",k=b==="error",C=A&&p,L=h!==void 0,I={status:b,fetchStatus:u.fetchStatus,isPending:A,isSuccess:b==="success",isError:k,isInitialLoading:C,isLoading:C,data:h,dataUpdatedAt:u.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:p,isRefetching:p&&!A,isLoadingError:k&&!L,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:k&&L,isStale:Uc(e,t),refetch:this.refetch,promise:this.#i};if(this.options.experimental_prefetchInRender){const g=x=>{I.status==="error"?x.reject(I.error):I.data!==void 0&&x.resolve(I.data)},w=()=>{const x=this.#i=I.promise=Ca();g(x)},S=this.#i;switch(S.status){case"pending":e.queryHash===n.queryHash&&g(S);break;case"fulfilled":(I.status==="error"||I.data!==S.value)&&w();break;case"rejected":(I.status!=="error"||I.error!==S.reason)&&w();break}}return I}updateResult(){const e=this.#r,t=this.createResult(this.#e,this.options);if(this.#o=this.#e.state,this.#a=this.options,this.#o.data!==void 0&&(this.#p=this.#e),Ra(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,o=typeof r=="function"?r():r;if(o==="all"||!o&&!this.#h.size)return!0;const s=new Set(o??this.#h);return this.options.throwOnError&&s.add("error"),Object.keys(this.#r).some(a=>{const c=a;return this.#r[c]!==e[c]&&s.has(c)})};this.#S({listeners:n()})}#k(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#S(e){ot.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function $_(e,t){return Ut(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function gd(e,t){return $_(e,t)||e.state.data!==void 0&&Pa(e,t,t.refetchOnMount)}function Pa(e,t,n){if(Ut(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Uc(e,t)}return!1}function _d(e,t,n,r){return(e!==t||Ut(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Uc(e,n)}function Uc(e,t){return Ut(t.enabled,e)!==!1&&e.isStaleByTime(xr(t.staleTime,e))}function N_(e,t){return!Ra(e.getCurrentResult(),t)}var Bc=R.createContext(void 0),D_=e=>{const t=R.useContext(Bc);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},nP=({client:e,children:t})=>(R.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),s_.jsx(Bc.Provider,{value:e,children:t})),fp=R.createContext(!1),L_=()=>R.useContext(fp);fp.Provider;function F_(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var U_=R.createContext(F_()),B_=()=>R.useContext(U_);function H_(e,t){return typeof e=="function"?e(...t):!!e}function bd(){}var W_=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},G_=e=>{R.useEffect(()=>{e.clearReset()},[e])},z_=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(o&&e.data===void 0||H_(n,[e.error,r])),K_=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)))},V_=(e,t)=>e.isLoading&&e.isFetching&&!t,Z_=(e,t)=>e?.suspense&&t.isPending,vd=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Y_(e,t,n){const r=D_(n),o=L_(),s=B_(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=o?"isRestoring":"optimistic",K_(a),W_(a,s),G_(s);const c=!r.getQueryCache().get(a.queryHash),[l]=R.useState(()=>new t(r,a)),d=l.getOptimisticResult(a),u=!o&&e.subscribed!==!1;if(R.useSyncExternalStore(R.useCallback(f=>{const h=u?l.subscribe(ot.batchCalls(f)):bd;return l.updateResult(),h},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),R.useEffect(()=>{l.setOptions(a)},[a,l]),Z_(a,d))throw vd(a,l,s);if(z_({result:d,errorResetBoundary:s,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw d.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!sr&&V_(d,o)&&(c?vd(a,l,s):r.getQueryCache().get(a.queryHash)?.promise)?.catch(bd).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function pp(e,t){return Y_(e,j_,t)}const J_=()=>{const e=R.useContext(Bc)??null,t=R.useMemo(()=>new M_({defaultOptions:{queries:{enabled:!1,retry:!1,gcTime:0}}}),[]);return R.useEffect(()=>{if(!e)return()=>t.clear()},[e,t]),R.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function rP(e){return e!=="detached"&&e!=="wedged"}function hp(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function oP(e){if(!e)return{title:"Not connected to a Local Operator server.",detail:null,retry:!0};const t=e.addressSubstitution??null;if(t&&e.state!=="detached"&&e.state!=="wedged")return t.kind==="substituted"?{title:`Serving on ${t.serving}, not the address this app is configured for.`,detail:t.holder?`${t.holder}. The app uses ${t.serving} while that holds.${t.reclaim?` ${t.reclaim}`:""} It is back on ${t.configured} on its next launch or recovery.`:`The daemon this app is using was already running, so it did not start one. It looks for ${t.configured} again on its next launch or recovery.`,retry:!0}:{title:`Back on ${t.configured}, the address this app is configured for.`,detail:`It served on ${t.serving} while the configured address was held; it is on the address it was told to use again.`,retry:!1,dismiss:!0};const n=e.detail?.trim()?e.detail.trim():null,r=hp(e.pairing?.cause??null);switch(e.state){case"wedged":return{title:"A Local Operator server is running on this machine and this app is not attached to it.",detail:n,retry:r};case"detached":return e.reconnecting?{title:r?"Not connected to a Local Operator server. If one is still running, the app reconnects to it on its own.":"Not connected to a Local Operator server.",detail:n,retry:r}:{title:r?"The Local Operator server stopped. The app keeps looking for one and attaches to it when it appears.":"Not connected to a Local Operator server. The app keeps looking for one.",detail:n,retry:r};default:return null}}var be;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(const c of s)a[c]=o[c];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(be||(be={}));var Ma;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ma||(Ma={}));const H=be.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ln=e=>{switch(typeof e){case"undefined":return H.undefined;case"string":return H.string;case"number":return isNaN(e)?H.nan:H.number;case"boolean":return H.boolean;case"function":return H.function;case"bigint":return H.bigint;case"symbol":return H.symbol;case"object":return Array.isArray(e)?H.array:e===null?H.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?H.promise:typeof Map<"u"&&e instanceof Map?H.map:typeof Set<"u"&&e instanceof Set?H.set:typeof Date<"u"&&e instanceof Date?H.date:H.object;default:return H.unknown}},$=be.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Q_=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class At extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){const d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return o(this),r}static assert(t){if(!(t instanceof At))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,be.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}At.create=e=>new At(e);const $r=(e,t)=>{let n;switch(e.code){case $.invalid_type:e.received===H.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case $.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,be.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:n=`Unrecognized key(s) in object: ${be.joinValues(e.keys,", ")}`;break;case $.invalid_union:n="Invalid input";break;case $.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${be.joinValues(e.options)}`;break;case $.invalid_enum_value:n=`Invalid enum value. Expected ${be.joinValues(e.options)}, received '${e.received}'`;break;case $.invalid_arguments:n="Invalid function arguments";break;case $.invalid_return_type:n="Invalid function return type";break;case $.invalid_date:n="Invalid date";break;case $.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:be.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case $.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 $.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 $.custom:n="Invalid input";break;case $.invalid_intersection_types:n="Intersection results could not be merged";break;case $.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case $.not_finite:n="Number must be finite";break;default:n=t.defaultError,be.assertNever(e)}return{message:n}};let mp=$r;function X_(e){mp=e}function Us(){return mp}const Bs=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="";const l=r.filter(d=>!!d).slice().reverse();for(const d of l)c=d(a,{data:t,defaultError:c}).message;return{...o,path:s,message:c}},q_=[];function U(e,t){const n=Us(),r=Bs({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===$r?void 0:$r].filter(o=>!!o)});e.common.issues.push(r)}class dt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return q;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const s=await o.key,a=await o.value;r.push({key:s,value:a})}return dt.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return q;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}}const q=Object.freeze({status:"aborted"}),Er=e=>({status:"dirty",value:e}),ut=e=>({status:"valid",value:e}),ja=e=>e.status==="aborted",$a=e=>e.status==="dirty",ir=e=>e.status==="valid",Eo=e=>typeof Promise<"u"&&e instanceof Promise;function Hs(e,t,n,r){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function gp(e,t,n,r,o){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var K;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(K||(K={}));var ao,co;class en{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const yd=(e,t)=>{if(ir(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 At(e.common.issues);return this._error=n,this._error}}};function le(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,c)=>{var l,d;const{message:u}=e;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??r)!==null&&l!==void 0?l:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??n)!==null&&d!==void 0?d:c.defaultError}},description:o}}class de{get description(){return this._def.description}_getType(t){return ln(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ln(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new dt,ctx:{common:t.parent.common,data:t.data,parsedType:ln(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Eo(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n?.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ln(t)},s=this._parseSync({data:t,path:o.path,parent:o});return yd(o,s)}"~validate"(t){var n,r;const o={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ln(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:o});return ir(s)?{value:s.value}:{issues:o.common.issues}}catch(s){!((r=(n=s?.message)===null||n===void 0?void 0:n.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),o.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:o}).then(s=>ir(s)?{value:s.value}:{issues:o.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ln(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Eo(o)?o:Promise.resolve(o));return yd(r,s)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{const a=t(o),c=()=>s.addIssue({code:$.custom,...r(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new zt({schema:this,typeName: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 Xt.create(this,this._def)}nullable(){return Nn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Wt.create(this)}promise(){return Dr.create(this,this._def)}or(t){return xo.create([this,t],this._def)}and(t){return To.create(this,t,this._def)}transform(t){return new zt({...le(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new jo({...le(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new Hc({typeName:Q.ZodBranded,type:this,...le(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new $o({...le(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 Jo.create(this,t)}readonly(){return No.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const eb=/^c[^\s-]{8,}$/i,tb=/^[0-9a-z]+$/,nb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,rb=/^[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,ob=/^[a-z0-9_-]{21}$/i,sb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ib=/^[-+]?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)?)??$/,ab=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,cb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Li;const lb=/^(?:(?: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])$/,db=/^(?:(?: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])$/,ub=/^(([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]))$/,fb=/^(([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])$/,pb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_p="((\\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])))",mb=new RegExp(`^${_p}$`);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 gb(e){return new RegExp(`^${bp(e)}$`)}function vp(e){let t=`${_p}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 _b(e,t){return!!((t==="v4"||!t)&&lb.test(e)||(t==="v6"||!t)&&ub.test(e))}function bb(e,t){if(!sb.test(e))return!1;try{const[n]=e.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||!o.typ||!o.alg||t&&o.alg!==t)}catch{return!1}}function vb(e,t){return!!((t==="v4"||!t)&&db.test(e)||(t==="v6"||!t)&&fb.test(e))}class Ht extends de{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==H.string){const s=this._getOrReturnCtx(t);return U(s,{code:$.invalid_type,expected:H.string,received:s.parsedType}),q}const r=new dt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,c=t.data.length<s.value;(a||c)&&(o=this._getOrReturnCtx(t,o),a?U(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&U(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")ab.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"email",code:$.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Li||(Li=new RegExp(cb,"u")),Li.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"emoji",code:$.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")rb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"uuid",code:$.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")ob.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"nanoid",code:$.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")eb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid",code:$.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")tb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid2",code:$.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")nb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ulid",code:$.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),U(o,{validation:"url",code:$.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"regex",code:$.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),U(o,{code:$.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:$.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:$.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?vp(s).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:$.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?mb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:$.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?gb(s).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:$.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?ib.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"duration",code:$.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?_b(t.data,s.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ip",code:$.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?bb(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"jwt",code:$.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?vb(t.data,s.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cidr",code:$.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?pb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64",code:$.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?hb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64url",code:$.invalid_string,message:s.message}),r.dirty()):be.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:$.invalid_string,...K.errToObj(r)})}_addCheck(t){return new Ht({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...K.errToObj(t)})}url(t){return this._addCheck({kind:"url",...K.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...K.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...K.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...K.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...K.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...K.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...K.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...K.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...K.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...K.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...K.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...K.errToObj(t)})}datetime(t){var n,r;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(n=t?.offset)!==null&&n!==void 0?n:!1,local:(r=t?.local)!==null&&r!==void 0?r:!1,...K.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...K.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...K.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...K.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...K.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...K.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...K.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...K.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...K.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...K.errToObj(n)})}nonempty(t){return this.min(1,K.errToObj(t))}trim(){return new Ht({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ht({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ht({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}Ht.create=e=>{var t;return new Ht({checks:[],typeName:Q.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...le(e)})};function yb(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=parseInt(e.toFixed(o).replace(".","")),a=parseInt(t.toFixed(o).replace(".",""));return s%a/Math.pow(10,o)}class Mn extends de{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==H.number){const s=this._getOrReturnCtx(t);return U(s,{code:$.invalid_type,expected:H.number,received:s.parsedType}),q}let r;const o=new dt;for(const s of this._def.checks)s.kind==="int"?be.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:$.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:$.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:$.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?yb(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),U(r,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:$.not_finite,message:s.message}),o.dirty()):be.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,K.toString(n))}gt(t,n){return this.setLimit("min",t,!1,K.toString(n))}lte(t,n){return this.setLimit("max",t,!0,K.toString(n))}lt(t,n){return this.setLimit("max",t,!1,K.toString(n))}setLimit(t,n,r,o){return new Mn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new Mn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:K.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:K.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:K.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:K.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:K.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:K.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:K.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:K.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:K.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&be.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}}Mn.create=e=>new Mn({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...le(e)});class jn extends de{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==H.bigint)return this._getInvalidInput(t);let r;const o=new dt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:$.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:$.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),U(r,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):be.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return U(n,{code:$.invalid_type,expected:H.bigint,received:n.parsedType}),q}gte(t,n){return this.setLimit("min",t,!0,K.toString(n))}gt(t,n){return this.setLimit("min",t,!1,K.toString(n))}lte(t,n){return this.setLimit("max",t,!0,K.toString(n))}lt(t,n){return this.setLimit("max",t,!1,K.toString(n))}setLimit(t,n,r,o){return new jn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new jn({...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}}jn.create=e=>{var t;return new jn({checks:[],typeName:Q.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...le(e)})};class Ao extends de{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==H.boolean){const r=this._getOrReturnCtx(t);return U(r,{code:$.invalid_type,expected:H.boolean,received:r.parsedType}),q}return ut(t.data)}}Ao.create=e=>new Ao({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...le(e)});class ar extends de{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==H.date){const s=this._getOrReturnCtx(t);return U(s,{code:$.invalid_type,expected:H.date,received:s.parsedType}),q}if(isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return U(s,{code:$.invalid_date}),q}const r=new dt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:$.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:$.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):be.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new ar({...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}}ar.create=e=>new ar({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...le(e)});class Ws extends de{_parse(t){if(this._getType(t)!==H.symbol){const r=this._getOrReturnCtx(t);return U(r,{code:$.invalid_type,expected:H.symbol,received:r.parsedType}),q}return ut(t.data)}}Ws.create=e=>new Ws({typeName:Q.ZodSymbol,...le(e)});class Io extends de{_parse(t){if(this._getType(t)!==H.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:$.invalid_type,expected:H.undefined,received:r.parsedType}),q}return ut(t.data)}}Io.create=e=>new Io({typeName:Q.ZodUndefined,...le(e)});class Ro extends de{_parse(t){if(this._getType(t)!==H.null){const r=this._getOrReturnCtx(t);return U(r,{code:$.invalid_type,expected:H.null,received:r.parsedType}),q}return ut(t.data)}}Ro.create=e=>new Ro({typeName:Q.ZodNull,...le(e)});class Nr extends de{constructor(){super(...arguments),this._any=!0}_parse(t){return ut(t.data)}}Nr.create=e=>new Nr({typeName:Q.ZodAny,...le(e)});class Qn extends de{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ut(t.data)}}Qn.create=e=>new Qn({typeName:Q.ZodUnknown,...le(e)});class hn extends de{_parse(t){const n=this._getOrReturnCtx(t);return U(n,{code:$.invalid_type,expected:H.never,received:n.parsedType}),q}}hn.create=e=>new hn({typeName:Q.ZodNever,...le(e)});class Gs extends de{_parse(t){if(this._getType(t)!==H.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:$.invalid_type,expected:H.void,received:r.parsedType}),q}return ut(t.data)}}Gs.create=e=>new Gs({typeName:Q.ZodVoid,...le(e)});class Wt extends de{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==H.array)return U(n,{code:$.invalid_type,expected:H.array,received:n.parsedType}),q;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,c=n.data.length<o.exactLength.value;(a||c)&&(U(n,{code:a?$.too_big:$.too_small,minimum:c?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(U(n,{code:$.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(U(n,{code:$.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>o.type._parseAsync(new en(n,a,n.path,c)))).then(a=>dt.mergeArray(r,a));const s=[...n.data].map((a,c)=>o.type._parseSync(new en(n,a,n.path,c)));return dt.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new Wt({...this._def,minLength:{value:t,message:K.toString(n)}})}max(t,n){return new Wt({...this._def,maxLength:{value:t,message:K.toString(n)}})}length(t,n){return new Wt({...this._def,exactLength:{value:t,message:K.toString(n)}})}nonempty(t){return this.min(1,t)}}Wt.create=(e,t)=>new Wt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...le(t)});function br(e){if(e instanceof Be){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Xt.create(br(r))}return new Be({...e._def,shape:()=>t})}else return e instanceof Wt?new Wt({...e._def,type:br(e.element)}):e instanceof Xt?Xt.create(br(e.unwrap())):e instanceof Nn?Nn.create(br(e.unwrap())):e instanceof tn?tn.create(e.items.map(t=>br(t))):e}class Be extends de{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=be.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==H.object){const d=this._getOrReturnCtx(t);return U(d,{code:$.invalid_type,expected:H.object,received:d.parsedType}),q}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof hn&&this._def.unknownKeys==="strip"))for(const d in o.data)a.includes(d)||c.push(d);const l=[];for(const d of a){const u=s[d],f=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new en(o,f,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof hn){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(d==="strict")c.length>0&&(U(o,{code:$.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const u of c){const f=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new en(o,f,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of l){const f=await u.key,h=await u.value;d.push({key:f,value:h,alwaysSet:u.alwaysSet})}return d}).then(d=>dt.mergeObjectSync(r,d)):dt.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return K.errToObj,new Be({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,s,a,c;const l=(a=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=K.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new Be({...this._def,unknownKeys:"strip"})}passthrough(){return new Be({...this._def,unknownKeys:"passthrough"})}extend(t){return new Be({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Be({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 Be({...this._def,catchall:t})}pick(t){const n={};return be.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Be({...this._def,shape:()=>n})}omit(t){const n={};return be.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Be({...this._def,shape:()=>n})}deepPartial(){return br(this)}partial(t){const n={};return be.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Be({...this._def,shape:()=>n})}required(t){const n={};return be.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Xt;)s=s._def.innerType;n[r]=s}}),new Be({...this._def,shape:()=>n})}keyof(){return yp(be.objectKeys(this.shape))}}Be.create=(e,t)=>new Be({shape:()=>e,unknownKeys:"strip",catchall:hn.create(),typeName:Q.ZodObject,...le(t)});Be.strictCreate=(e,t)=>new Be({shape:()=>e,unknownKeys:"strict",catchall:hn.create(),typeName:Q.ZodObject,...le(t)});Be.lazycreate=(e,t)=>new Be({shape:e,unknownKeys:"strip",catchall:hn.create(),typeName:Q.ZodObject,...le(t)});class xo extends de{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const a=s.map(c=>new At(c.ctx.common.issues));return U(n,{code:$.invalid_union,unionErrors:a}),q}if(n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of r){const d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const c=a.map(l=>new At(l));return U(n,{code:$.invalid_union,unionErrors:c}),q}}get options(){return this._def.options}}xo.create=(e,t)=>new xo({options:e,typeName:Q.ZodUnion,...le(t)});const sn=e=>e instanceof Oo?sn(e.schema):e instanceof zt?sn(e.innerType()):e instanceof Po?[e.value]:e instanceof $n?e.options:e instanceof Mo?be.objectValues(e.enum):e instanceof jo?sn(e._def.innerType):e instanceof Io?[void 0]:e instanceof Ro?[null]:e instanceof Xt?[void 0,...sn(e.unwrap())]:e instanceof Nn?[null,...sn(e.unwrap())]:e instanceof Hc||e instanceof No?sn(e.unwrap()):e instanceof $o?sn(e._def.innerType):[];class pi extends de{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==H.object)return U(n,{code:$.invalid_type,expected:H.object,received:n.parsedType}),q;const r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(U(n,{code:$.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const s of n){const a=sn(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of a){if(o.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);o.set(c,s)}}return new pi({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...le(r)})}}function Na(e,t){const n=ln(e),r=ln(t);if(e===t)return{valid:!0,data:e};if(n===H.object&&r===H.object){const o=be.objectKeys(t),s=be.objectKeys(e).filter(c=>o.indexOf(c)!==-1),a={...e,...t};for(const c of s){const l=Na(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===H.array&&r===H.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],c=t[s],l=Na(a,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===H.date&&r===H.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class To extends de{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(s,a)=>{if(ja(s)||ja(a))return q;const c=Na(s.value,a.value);return c.valid?(($a(s)||$a(a))&&n.dirty(),{status:n.value,value:c.data}):(U(r,{code:$.invalid_intersection_types}),q)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}To.create=(e,t,n)=>new To({left:e,right:t,typeName:Q.ZodIntersection,...le(n)});class tn extends de{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==H.array)return U(r,{code:$.invalid_type,expected:H.array,received:r.parsedType}),q;if(r.data.length<this._def.items.length)return U(r,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),q;!this._def.rest&&r.data.length>this._def.items.length&&(U(r,{code:$.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new en(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>dt.mergeArray(n,a)):dt.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new tn({...this._def,rest:t})}}tn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new tn({items:e,typeName:Q.ZodTuple,rest:null,...le(t)})};class Co extends de{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==H.object)return U(r,{code:$.invalid_type,expected:H.object,received:r.parsedType}),q;const o=[],s=this._def.keyType,a=this._def.valueType;for(const c in r.data)o.push({key:s._parse(new en(r,c,r.path,c)),value:a._parse(new en(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?dt.mergeObjectAsync(n,o):dt.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof de?new Co({keyType:t,valueType:n,typeName:Q.ZodRecord,...le(r)}):new Co({keyType:Ht.create(),valueType:t,typeName:Q.ZodRecord,...le(n)})}}class zs extends de{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==H.map)return U(r,{code:$.invalid_type,expected:H.map,received:r.parsedType}),q;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:o._parse(new en(r,c,r.path,[d,"key"])),value:s._parse(new en(r,l,r.path,[d,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of a){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return q;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const l of a){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return q;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}zs.create=(e,t,n)=>new zs({valueType:t,keyType:e,typeName:Q.ZodMap,...le(n)});class cr extends de{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==H.set)return U(r,{code:$.invalid_type,expected:H.set,received:r.parsedType}),q;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(U(r,{code:$.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(U(r,{code:$.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return q;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>s._parse(new en(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new cr({...this._def,minSize:{value:t,message:K.toString(n)}})}max(t,n){return new cr({...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)}}cr.create=(e,t)=>new cr({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...le(t)});class Tr extends de{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==H.function)return U(n,{code:$.invalid_type,expected:H.function,received:n.parsedType}),q;function r(c,l){return Bs({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Us(),$r].filter(d=>!!d),issueData:{code:$.invalid_arguments,argumentsError:l}})}function o(c,l){return Bs({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Us(),$r].filter(d=>!!d),issueData:{code:$.invalid_return_type,returnTypeError:l}})}const s={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Dr){const c=this;return ut(async function(...l){const d=new At([]),u=await c._def.args.parseAsync(l,s).catch(m=>{throw d.addIssue(r(l,m)),d}),f=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(f,s).catch(m=>{throw d.addIssue(o(f,m)),d})})}else{const c=this;return ut(function(...l){const d=c._def.args.safeParse(l,s);if(!d.success)throw new At([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,s);if(!f.success)throw new At([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Tr({...this._def,args:tn.create(t).rest(Qn.create())})}returns(t){return new Tr({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Tr({args:t||tn.create([]).rest(Qn.create()),returns:n||Qn.create(),typeName:Q.ZodFunction,...le(r)})}}class Oo extends de{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Oo.create=(e,t)=>new Oo({getter:e,typeName:Q.ZodLazy,...le(t)});class Po extends de{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return U(n,{received:n.data,code:$.invalid_literal,expected:this._def.value}),q}return{status:"valid",value:t.data}}get value(){return this._def.value}}Po.create=(e,t)=>new Po({value:e,typeName:Q.ZodLiteral,...le(t)});function yp(e,t){return new $n({values:e,typeName:Q.ZodEnum,...le(t)})}class $n extends de{constructor(){super(...arguments),ao.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{expected:be.joinValues(r),received:n.parsedType,code:$.invalid_type}),q}if(Hs(this,ao)||gp(this,ao,new Set(this._def.values)),!Hs(this,ao).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{received:n.data,code:$.invalid_enum_value,options:r}),q}return ut(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 $n.create(t,{...this._def,...n})}exclude(t,n=this._def){return $n.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}ao=new WeakMap;$n.create=yp;class Mo extends de{constructor(){super(...arguments),co.set(this,void 0)}_parse(t){const n=be.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==H.string&&r.parsedType!==H.number){const o=be.objectValues(n);return U(r,{expected:be.joinValues(o),received:r.parsedType,code:$.invalid_type}),q}if(Hs(this,co)||gp(this,co,new Set(be.getValidEnumValues(this._def.values))),!Hs(this,co).has(t.data)){const o=be.objectValues(n);return U(r,{received:r.data,code:$.invalid_enum_value,options:o}),q}return ut(t.data)}get enum(){return this._def.values}}co=new WeakMap;Mo.create=(e,t)=>new Mo({values:e,typeName:Q.ZodNativeEnum,...le(t)});class Dr extends de{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==H.promise&&n.common.async===!1)return U(n,{code:$.invalid_type,expected:H.promise,received:n.parsedType}),q;const r=n.parsedType===H.promise?n.data:Promise.resolve(n.data);return ut(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Dr.create=(e,t)=>new Dr({type:e,typeName:Q.ZodPromise,...le(t)});class zt extends de{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{U(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return q;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?q:l.status==="dirty"||n.value==="dirty"?Er(l.value):l});{if(n.value==="aborted")return q;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?q:c.status==="dirty"||n.value==="dirty"?Er(c.value):c}}if(o.type==="refinement"){const a=c=>{const l=o.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?q:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?q:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ir(a))return a;const c=o.transform(a.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>ir(a)?Promise.resolve(o.transform(a.value,s)).then(c=>({status:n.value,value:c})):a);be.assertNever(o)}}zt.create=(e,t,n)=>new zt({schema:e,typeName:Q.ZodEffects,effect:t,...le(n)});zt.createWithPreprocess=(e,t,n)=>new zt({schema:t,effect:{type:"preprocess",transform:e},typeName:Q.ZodEffects,...le(n)});class Xt extends de{_parse(t){return this._getType(t)===H.undefined?ut(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Xt.create=(e,t)=>new Xt({innerType:e,typeName:Q.ZodOptional,...le(t)});class Nn extends de{_parse(t){return this._getType(t)===H.null?ut(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Nn.create=(e,t)=>new Nn({innerType:e,typeName:Q.ZodNullable,...le(t)});class jo extends de{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===H.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}jo.create=(e,t)=>new jo({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...le(t)});class $o extends de{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Eo(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new At(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new At(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}$o.create=(e,t)=>new $o({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...le(t)});class Ks extends de{_parse(t){if(this._getType(t)!==H.nan){const r=this._getOrReturnCtx(t);return U(r,{code:$.invalid_type,expected:H.nan,received:r.parsedType}),q}return{status:"valid",value:t.data}}}Ks.create=e=>new Ks({typeName:Q.ZodNaN,...le(e)});const wb=Symbol("zod_brand");class Hc extends de{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Jo extends de{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?q:s.status==="dirty"?(n.dirty(),Er(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?q:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new Jo({in:t,out:n,typeName:Q.ZodPipeline})}}class No extends de{_parse(t){const n=this._def.innerType._parse(t),r=o=>(ir(o)&&(o.value=Object.freeze(o.value)),o);return Eo(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}No.create=(e,t)=>new No({innerType:e,typeName:Q.ZodReadonly,...le(t)});function wd(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function wp(e,t={},n){return e?Nr.create().superRefine((r,o)=>{var s,a;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=wd(t,r),h=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;o.addIssue({code:"custom",...f,fatal:h})}});if(!c){const l=wd(t,r),d=(a=(s=l.fatal)!==null&&s!==void 0?s:n)!==null&&a!==void 0?a:!0;o.addIssue({code:"custom",...l,fatal:d})}}):Nr.create()}const kb={object:Be.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 Sb=(e,t={message:`Input not instance of ${e.name}`})=>wp(n=>n instanceof e,t),kp=Ht.create,Sp=Mn.create,Eb=Ks.create,Ab=jn.create,Ep=Ao.create,Ib=ar.create,Rb=Ws.create,xb=Io.create,Tb=Ro.create,Cb=Nr.create,Ob=Qn.create,Pb=hn.create,Mb=Gs.create,jb=Wt.create,$b=Be.create,Nb=Be.strictCreate,Db=xo.create,Lb=pi.create,Fb=To.create,Ub=tn.create,Bb=Co.create,Hb=zs.create,Wb=cr.create,Gb=Tr.create,zb=Oo.create,Kb=Po.create,Vb=$n.create,Zb=Mo.create,Yb=Dr.create,kd=zt.create,Jb=Xt.create,Qb=Nn.create,Xb=zt.createWithPreprocess,qb=Jo.create,ev=()=>kp().optional(),tv=()=>Sp().optional(),nv=()=>Ep().optional(),rv={string:e=>Ht.create({...e,coerce:!0}),number:e=>Mn.create({...e,coerce:!0}),boolean:e=>Ao.create({...e,coerce:!0}),bigint:e=>jn.create({...e,coerce:!0}),date:e=>ar.create({...e,coerce:!0})},ov=q;var i=Object.freeze({__proto__:null,defaultErrorMap:$r,setErrorMap:X_,getErrorMap:Us,makeIssue:Bs,EMPTY_PATH:q_,addIssueToContext:U,ParseStatus:dt,INVALID:q,DIRTY:Er,OK:ut,isAborted:ja,isDirty:$a,isValid:ir,isAsync:Eo,get util(){return be},get objectUtil(){return Ma},ZodParsedType:H,getParsedType:ln,ZodType:de,datetimeRegex:vp,ZodString:Ht,ZodNumber:Mn,ZodBigInt:jn,ZodBoolean:Ao,ZodDate:ar,ZodSymbol:Ws,ZodUndefined:Io,ZodNull:Ro,ZodAny:Nr,ZodUnknown:Qn,ZodNever:hn,ZodVoid:Gs,ZodArray:Wt,ZodObject:Be,ZodUnion:xo,ZodDiscriminatedUnion:pi,ZodIntersection:To,ZodTuple:tn,ZodRecord:Co,ZodMap:zs,ZodSet:cr,ZodFunction:Tr,ZodLazy:Oo,ZodLiteral:Po,ZodEnum:$n,ZodNativeEnum:Mo,ZodPromise:Dr,ZodEffects:zt,ZodTransformer:zt,ZodOptional:Xt,ZodNullable:Nn,ZodDefault:jo,ZodCatch:$o,ZodNaN:Ks,BRAND:wb,ZodBranded:Hc,ZodPipeline:Jo,ZodReadonly:No,custom:wp,Schema:de,ZodSchema:de,late:kb,get ZodFirstPartyTypeKind(){return Q},coerce:rv,any:Cb,array:jb,bigint:Ab,boolean:Ep,date:Ib,discriminatedUnion:Lb,effect:kd,enum:Vb,function:Gb,instanceof:Sb,intersection:Fb,lazy:zb,literal:Kb,map:Hb,nan:Eb,nativeEnum:Zb,never:Pb,null:Tb,nullable:Qb,number:Sp,object:$b,oboolean:nv,onumber:tv,optional:Jb,ostring:ev,pipeline:qb,preprocess:Xb,promise:Yb,record:Bb,set:Wb,strictObject:Nb,string:kp,symbol:Rb,transformer:kd,tuple:Ub,undefined:xb,union:Db,unknown:Ob,void:Mb,NEVER:ov,ZodIssueCode:$,quotelessJson:Q_,ZodError:At});const Sd=i.enum(["app_start","sign_in","window_focus","surface_open"]),Ap=i.object({id:i.string().min(1),state:i.enum(["active","paused","disabled"])}).passthrough(),sv=i.object({tenant_id:i.string().min(1),tenant_name:i.string().optional(),eligible:i.boolean(),endpoint:Ap.nullable()}).passthrough(),iv=i.object({code:i.string(),message:i.string(),details:i.record(i.unknown()).optional(),retry_after_seconds:i.number().optional()}).passthrough(),av=i.object({code:i.string().min(1),count:i.number().int().nonnegative(),session:i.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),cv=i.object({in_force:i.boolean(),notice_pending:i.boolean().catch(!1)}).passthrough().optional().catch(void 0),sP=i.object({capability:i.number(),consent_account_guard:i.boolean().optional(),state:i.enum(["ready","signed_out","unavailable","update_required"]),account_id:i.string().nullable(),tenant_id:i.string().nullable(),surface_state:i.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:i.object({settings:i.boolean(),inbox:i.boolean(),account_door:i.boolean(),onboarding:i.boolean()}),update_required:i.boolean(),local:i.object({enabled:i.boolean(),onboarding:i.string(),session:i.string()}),status:i.object({tenants:i.array(sv)}).passthrough().nullable(),consent:i.object({version:i.string().min(1).max(128),text:i.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:i.enum(["served","cached","embedded"])}).nullable(),error:iv.nullable(),state_note:i.string().nullable().optional(),read_only:i.boolean().optional(),trial_ended:i.object({tenant_id:i.string().min(1),trial_ended_at:i.string().min(1)}).passthrough().nullable().optional().catch(null),delivery_hold:av,default_on:cv}).passthrough(),lv=i.object({version:i.string().min(1),consented_at:i.string().min(1),consented_via:i.string().min(1),current:i.boolean()}).passthrough(),iP=i.object({endpoint:Ap.extend({tenant_id:i.string().min(1),label:i.string().optional(),consent:lv.nullable().optional(),created_at:i.string().optional(),updated_at:i.string().optional()}).nullable(),settings:i.object({tenant_id:i.string().min(1),eligible:i.boolean(),consent_version:i.string().optional(),consent_required:i.boolean()}).passthrough(),default_on:i.boolean().optional().catch(void 0),share_typing:i.boolean().optional().catch(void 0)}).passthrough(),dv=i.object({kind:i.enum(["endpoint","account"]).optional(),endpoint_id:i.string().min(1).optional(),account_id:i.string().min(1).optional()}).passthrough().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id").refine(e=>e.kind===void 0||(e.kind==="endpoint"?e.endpoint_id!==void 0:e.account_id!==void 0),"An allowlist target's kind must agree with the id it carries"),Ed=i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:dv,id:i.string().optional()}).passthrough(),Ad=i.object({mode:i.enum(["class_default","listed_only"]),allow:i.number(),deny:i.number()}).passthrough(),aP=i.object({allowlist:i.object({tenant_id:i.string().min(1),entries:i.array(Ed)}).passthrough(),view:i.object({tenant_id:i.string().nullable(),entries:i.array(Ed),directions:i.object({send:Ad,receive:Ad}),class_default:i.literal("cos_cos"),cues:i.object({allow_entry_switches_direction_to_listed_only:i.boolean(),listed_only_affects:i.string(),removing_allow_does_not_stop_open_thread:i.boolean(),deny_stops_pair_both_directions:i.boolean()}).passthrough()}).passthrough()}).passthrough(),cP=i.object({onboarding:i.literal("seen")}).passthrough();function uv(e){return e?.default_on?.in_force===!0}function lP(e,t){const n=fv(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function dP(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function uP(e,t){if(!e||!t||uv(e)||e.account_id!==t||e.capability<1||e.state!=="ready"||e.update_required||e.surface_state!=="B"||!e.visibility.onboarding||!e.tenant_id)return null;const n=e.status?.tenants.filter(r=>r.tenant_id===e.tenant_id);return n?.length!==1||n[0].eligible!==!0||n[0].endpoint!==null?null:{accountId:t,tenantId:e.tenant_id}}function fv(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const pv=8,Da=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],hv=6*1024,mv=512;function Vs(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const o=[];for(const s of n){if(o.length===mv)break;const c=new URLSearchParams({order_ids:s}).toString().length+1;if(r+c>hv)break;e.append("order_ids",s),o.push(s),r+=c}return o}function gv(e,t,n){return Vs(new URLSearchParams(n),t,e)}const fP=3,_v=4096,pP=128,hP=/^[0-9a-f]{32}$/,bv=/^\.+$/,vv=new RegExp("\\p{Cf}","u"),yv=/[/\\:]/,E=i.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),wv=i.string().min(1).max(128),cs=i.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),ls=i.string().min(1).max(32768),kv=/^[a-f0-9]{12}$/,B=i.string().regex(kv),Fi=i.string().regex(/^[a-f0-9]{12}$/),Ui=i.string().min(1).max(128),Sv=i.string().min(1).max(4096),Vr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),Bi=i.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),ds=i.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),Id=i.string().regex(/^[a-f0-9]{32}$/),Ev=/^(\/|[A-Za-z]:[\\/])/,Hi=i.string().min(1).max(4096).regex(Ev),Rd=/^[a-f0-9]{32}$/,fe=i.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),xd=i.string().min(1).max(512).nullish(),mr=i.string().regex(/^[A-Za-z0-9_-]{1,128}$/),Zr=i.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),Av=["credential_finite_share","credential_inheritance"],Zs=/^sha256:[0-9a-f]{64}$/,Td={operation:i.enum(Av),requestDigest:i.string().regex(Zs),disclosureDigest:i.string().regex(Zs)},Yr=i.string().regex(/^la_[0-9a-f]{16}$/),Jr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),Cd=i.object({data_b64:i.string().min(1).max(1e6),mime_type:i.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:i.string().max(4096).optional()}).strict(),Iv=i.object({digest:i.string().regex(/^[0-9a-f]{32}$/),name:i.string().max(1024).optional(),mime_type:i.string().max(255).optional(),bytes:i.number().int().min(0).optional(),path:i.string().max(4096).optional()}).strict(),Od=2e5,Pd=8,Rv=256,xv=100,Md=16,Tv=256,Cv=100,Ov=200,Pv=1e6,Mv=i.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),rt=i.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),us=i.object({kind:i.enum(["agent","team"]),name:rt}).strict(),Ip=i.enum(["claude","codex","omp"]),jv=i.record(i.string(),i.array(i.string().min(1).max(512)).max(5e3)),jd={sources:i.array(Ip).max(3).optional(),sessionIds:jv.optional(),all:i.boolean().optional(),includeSubagents:i.boolean().optional(),includeClearedSegments:i.boolean().optional(),includeMemory:i.boolean().optional(),includeInstructions:i.boolean().optional(),maxSessions:i.number().int().min(1).max(5e3).optional()},Wi=i.object({provider:i.string().min(1).max(128),model_id:i.string().min(1).max(512),reasoning_effort:i.string().min(1).max(64).nullable(),fast_mode:i.boolean().nullable().optional()}).strict(),$d=i.object({kind:i.enum(["role","specialist"]).optional(),description:i.string().max(8e3).optional(),instructions:i.string().max(8e3).optional(),tools:i.array(i.string().min(1).max(128)).max(256).optional(),effort:i.string().max(64).optional(),delegate:i.boolean().optional(),action_class:i.enum(["reactive","proactive"]).optional()}).strict(),Nd=i.object({name:i.string().min(1).max(64).optional(),description:i.string().max(8e3).optional(),manager:rt.optional(),members:i.array(i.object({role:rt,count:i.number().int().min(1).max(16),kind:i.enum(["agent","team"]),tier:i.enum(["lo","med","hi"]).nullable().optional(),effort:Mv.nullable().optional()}).strict()).max(128).optional(),instructions:i.string().max(8e3).optional(),project:i.string().max(8e3).optional()}).strict(),$v=i.record(i.array(i.string().max(1024)).max(100)),Gi=i.array(E).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),Nv=i.array(i.object({kind:i.enum(["human","agent"]),account_id:E,endpoint_id:E.optional()}).strict()).max(50).refine(e=>new Set(e.map(t=>`${t.kind}:${t.account_id}:${t.endpoint_id??""}`)).size===e.length,"Duplicate mention"),Dd=i.enum(["minutes","hours","days"]);function Dv(e){return!bv.test(e)}const mP=e=>Cs.safeParse(e).success,Cs=i.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(Dv),Ld=i.enum(["str","int","float","bool","list","dict"]),Fd=i.string().max(16384),Lv=2e3,Ud=i.string().min(1).max(Lv),Bd=i.string().min(1).max(64),Fv=i.string().min(1).max(64),Uv=i.string().min(1).max(64),Hd=i.object({is_active:i.boolean().nullish(),one_time:i.boolean().nullish(),start_time_utc:i.string().max(64).nullish(),end_time_utc:i.string().max(64).nullish()}).strict(),Bv=i.object({conversation_length:i.number().int().optional(),detail_length:i.number().int().optional(),max_learnings_history:i.number().int().optional(),hosting:i.string().max(256).optional(),model_name:i.string().max(1024).optional(),auto_save_conversation:i.boolean().optional()}).strict(),La=128,Wd=2e3,Gd=8e3,zd=64,Kd=64,hi=e=>[...e].length,Fa=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,Hv=e=>e===9||e===10||e===11||e===12||e===13||e===133,Wv=e=>e<=31||e>=127&&e<=159,Gv=e=>vv.test(String.fromCodePoint(e)),zv=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,fs=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},Rp=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&Fa(t[n].codePointAt(0)??0);)n++;for(;r>n&&Fa(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},Kv=e=>{let t="",n=!1;for(const r of e){if(Fa(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function Vv(e){const t=Rp(e);if(!t)return"must not be empty";if(hi(t)>La)return`must be at most ${La} characters`;if(yv.test(t))return'must not contain "/", "\\" or ":"';if(fs(t,zv))return"must not contain Unicode bidirectional override characters";if(fs(t,Hv))return"must not contain whitespace";if(fs(t,Wv))return"must not contain control characters";if(fs(t,Gv))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 gP(e){return Kv(Rp(e).normalize("NFKC").toLowerCase())}function Zv(e){return e.trim()?hi(e)>Wd?`must be at most ${Wd} characters`:null:"must not be empty"}function Yv(e){return e.trim()?hi(e)>Gd?`must be at most ${Gd} characters`:null:"must not be empty"}function Jv(e){if(e.length>Kd)return`must hold at most ${Kd} items`;for(const t of e)if(!t.trim()||hi(t)>zd)return`must hold items of 1 to ${zd} characters`;return null}const Qv=e=>Vv(e)===null,Xv=i.string().refine(Qv,{message:"That is not a name the hub can publish."}),qv=i.string().refine(e=>Yv(e)===null,{message:"That instruction body cannot be published."}),ey=i.string().refine(e=>Zv(e)===null,{message:"That description cannot be published."}),ty=i.array(i.string()).refine(e=>Jv(e)===null,{message:"That tool list cannot be published."}),zi={requestId:fe.optional(),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()},Vd=i.object({name:Xv,description:ey,instructions:qv,kind:i.enum(["role","specialist"]),when_to_use:i.string(),tools:ty,effort:i.string(),delegate:i.boolean(),version:i.string(),categories:i.array(i.string()),tags:i.array(i.string())}).partial().strict(),ny=i.enum(["team","agent"]),ry=i.string().min(1).max(64),oy=i.string().min(1).max(256),xp=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ki=i.string().regex(xp,{message:"Letters, digits, dot, underscore and dash; no spaces."}),sy=["planning","active","qa","validation","done","paused","archived"],Zd=i.enum(sy),ps=i.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),Yd=i.array(i.string().min(1).max(24)).max(8),En=i.string().min(1).max(64),iy=1e3,Jd=240,Qd=80,ay=256,cy=100,ly=200,dy=/^[a-z0-9][a-z0-9_-]{0,23}$/;function _P(e){return e?xp.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 bP(e){return dy.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const hs=i.enum(["agent","team","skill"]),Vi=i.string().min(1).max(128).regex(/\S/),Xd=i.enum(Da),uy=i.object({visible:i.array(Xd).max(Da.length),more:i.array(Xd).max(Da.length)}).strict(),dn=i.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),qd=i.object({selectionToken:i.string().min(1).max(512),reconcileIds:i.array(dn).max(500).optional(),excludedIds:i.array(dn).max(500).optional()}).strict(),fy=i.object({operationToken:i.string().min(1).max(512),reconcileIds:i.array(dn).max(500).optional()}).strict(),eu=i.union([i.object({throughSeq:i.number().int().min(0).optional(),receipt:i.literal(!0).optional(),reconcileIds:i.array(dn).max(500).optional(),items:i.array(i.object({id:dn,revision:i.number().int().min(1)}).strict()).min(1).max(500)}).strict(),i.object({sessionId:B,throughSeq:i.number().int().min(0),observed:i.array(i.object({id:dn,revision:i.number().int().min(1)}).strict()).max(500)}).strict(),i.object({all:i.literal(!0),throughSeq:i.number().int().min(0),observed:i.array(i.object({id:dn,revision:i.number().int().min(1)}).strict()).max(500)}).strict()]),py={pointer:"pointerdown",key:"keydown",wheel:"wheel"},hy=i.discriminatedUnion("op",[i.object({op:i.literal("capabilities")}).strict(),i.object({op:i.literal("runtimes.list")}).strict(),i.object({op:i.literal("profiles.list")}).strict(),i.object({op:i.literal("profiles.get"),name:rt}).strict(),i.object({op:i.literal("imports.sources")}).strict(),i.object({op:i.literal("imports.sessions"),source:Ip,includeSubagents:i.boolean().optional()}).strict(),i.object({op:i.literal("imports.preview"),...jd}).strict(),i.object({op:i.literal("imports.start"),...jd}).strict(),i.object({op:i.literal("imports.status"),jobId:i.string().min(1).max(128)}).strict(),i.object({op:i.literal("imports.cancel"),jobId:i.string().min(1).max(128)}).strict(),i.object({op:i.literal("profiles.update"),name:rt,requestId:fe,fields:$d,expectedDefinitionRevision:xd.optional()}).strict(),i.object({op:i.literal("profiles.install"),name:rt,requestId:fe}).strict(),i.object({op:i.literal("profiles.create"),name:rt,requestId:fe,fields:$d.extend({description:i.string().max(8e3),instructions:i.string().min(1).max(8e3)})}).strict(),i.object({op:i.literal("hub.updates")}).strict(),i.object({op:i.literal("hub.skillPull"),requestId:fe,hubId:E,hubSource:i.string().min(1).max(2048),visibility:i.enum(["public","org"]),tenantId:E.nullable(),localAlias:rt,subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional(),dryRun:i.boolean().optional(),adoptionStrategy:i.enum(["merge","keep-local","take-hub"]).optional(),allowLlm:i.boolean().optional(),confirm:i.boolean().optional(),adoptionReceipt:i.string().min(16).max(128).optional()}).strict(),i.object({op:i.literal("hub.skillSubscribe"),requestId:fe,hubId:E,hubSource:i.string().min(1).max(2048),visibility:i.enum(["public","org"]),tenantId:E.nullable(),localAlias:rt}).strict(),i.object({op:i.literal("hub.skillUnpull"),requestId:fe,linkId:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("hub.skillPublish"),requestId:fe,dryRun:i.boolean(),sourceSkill:rt,localAlias:rt,visibility:i.enum(["public","org"]),tenantId:E.nullable(),subscribe:i.boolean(),autoPush:i.boolean(),confirmPublicEgress:i.boolean(),previewReceipt:i.string().min(1).max(4096).optional(),confirmPublish:i.literal(!0).optional()}).strict(),i.object({op:i.literal("hub.links"),kind:i.enum(["agent","team","skill"]).optional()}).strict(),i.object({op:i.literal("hub.policy"),requestId:fe,linkId:i.string().min(1).max(256),expectedPolicyRevision:i.string().min(1).max(256),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()}).strict(),i.object({op:i.literal("hub.check"),requestId:fe,kind:hs.optional(),name:rt.optional(),localId:Vi.optional()}).strict(),i.object({op:i.literal("hub.apply"),requestId:fe,kind:hs.optional(),name:rt.optional(),localId:Vi.optional(),prefer:i.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:i.boolean().optional(),dryRun:i.boolean().optional(),resolveSource:i.literal(!0).optional(),hubSource:i.string().min(1).max(2048).optional(),visibility:i.enum(["public","org"]).optional(),tenantId:i.string().min(1).max(128).nullable().optional()}).strict(),i.object({op:i.literal("hub.applyAll"),requestId:fe,kind:hs.optional()}).strict(),i.object({op:i.literal("hub.retry"),requestId:fe,kind:hs.optional(),name:rt.optional(),localId:Vi.optional()}).strict(),i.object({op:i.literal("hub.push"),requestId:fe,linkId:i.string().min(1).max(256),direction:i.literal("push"),dryRun:i.boolean(),previewReceipt:i.string().min(1).max(4096).optional(),confirmPublish:i.literal(!0).optional()}).strict(),i.object({op:i.literal("teams.list")}).strict(),i.object({op:i.literal("teams.get"),name:rt}).strict(),i.object({op:i.literal("teams.effective"),name:rt}).strict(),i.object({op:i.literal("teams.update"),name:rt,requestId:fe,fields:Nd,expectedDefinitionRevision:xd.optional()}).strict(),i.object({op:i.literal("teams.create"),requestId:fe,fields:Nd.extend({name:i.string().min(1).max(64)})}).strict(),i.object({op:i.literal("sessions.list"),limit:i.number().int().min(1).max(500).optional(),include_archived:i.boolean().optional(),include_peers:i.boolean().optional(),scope_kind:ny.optional(),scope_name:ry.optional(),cursor:oy.optional(),with_counts:i.boolean().optional(),sort:i.literal("activity").optional()}).strict(),i.object({op:i.literal("delegated_cleanup_notice.ack")}).strict(),i.object({op:i.literal("sessions.search"),q:i.string().min(1).max(Rv),limit:i.number().int().min(1).max(500).optional(),include_archived:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.archive"),sessionId:B,archived:i.boolean()}).strict(),i.object({op:i.literal("sessions.delete"),sessionId:B,confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.create"),requestId:fe,cwd:i.string().min(1).max(4096).optional(),target:us.optional(),purpose:i.literal("agents-config").optional(),model:Wi.optional(),draftId:B.optional(),peer:mr.optional()}).strict(),i.object({op:i.literal("sessions.preview"),requestId:fe,cwd:i.string().min(1).max(4096),target:us.optional(),model:Wi.optional()}).strict(),i.object({op:i.literal("sessions.draft"),requestId:fe,cwd:i.string().min(1).max(4096),target:us.optional(),model:Wi.optional()}).strict(),i.object({op:i.literal("sessions.get"),sessionId:B,journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.files"),sessionId:B,scope:i.enum(["family","self"]).optional(),kind:i.string().max(256).optional(),q:i.string().max(256).optional(),sort:i.enum(["recent","name","kind","modified","created","size"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(8192).optional()}).strict(),i.object({op:i.literal("sessions.files.materialise"),sessionId:B,fileId:i.string().regex(/^[a-f0-9]{16}$/)}).strict(),i.object({op:i.literal("sessions.userAttachments"),sessionId:B}).strict(),i.object({op:i.literal("sessions.userAttachments.materialise"),sessionId:B,digest:i.string().regex(/^[a-f0-9]{32}$/)}).strict(),i.object({op:i.literal("sessions.history"),sessionId:B,beforeId:E.optional(),limit:i.number().int().min(1).max(500).optional(),openFrame:i.boolean().optional(),journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional(),sourceRead:i.enum(["metadata","payload"]).optional(),expectedJournalGeneration:i.string().min(1).max(128).optional()}).strict(),i.object({op:i.literal("sessions.checkpoints"),sessionId:B}).strict(),i.object({op:i.literal("sessions.checkpoints.warm"),sessionId:B,ids:i.array(E).max(Md).optional(),limit:i.number().int().min(1).max(Md).optional()}).strict(),i.object({op:i.literal("sessions.find"),sessionId:B,q:i.string().min(1).max(Tv),limit:i.number().int().min(1).max(Ov).optional()}).strict(),i.object({op:i.literal("subagents.transcript"),sessionId:B,childId:B,beforeId:E.optional(),entryId:i.string().min(1).max(128).regex(/^[a-zA-Z0-9_:-]+$/).optional(),limit:i.number().int().min(1).max(500).optional()}).strict(),i.object({op:i.literal("sessions.message"),sessionId:B,requestId:fe,text:i.string().max(Od),images:i.array(Cd).max(Pd).optional(),files:i.array(Iv).max(pv).optional(),mode:i.enum(["prompt","steer"]).optional(),inputMode:i.enum(["typed","dictated","mixed"]).optional(),inputPath:i.string().max(1024).optional()}).strict(),i.object({op:i.literal("sessions.command"),sessionId:B,requestId:fe,command:i.string().regex(/^\/?[A-Za-z]+$/).max(64),args:i.string().max(Od).optional(),images:i.array(Cd).max(Pd).optional()}).strict(),i.object({op:i.literal("sessions.move"),sessionId:B,requestId:fe,cwd:i.string().min(1).max(4096)}).strict(),i.object({op:i.literal("settingsIntents.list"),sessionId:B.optional()}).strict(),i.object({op:i.literal("settingsIntents.submit"),sessionId:B,requestId:fe,kind:i.enum(["model","effort","fast","cwd"]),value:i.union([i.string().min(1).max(4096),i.boolean()]),effort:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("settingsIntents.dismiss"),sessionId:B,kind:i.enum(["model","effort","fast","cwd"]),generation:i.number().int().nonnegative()}).strict(),i.object({op:i.literal("sessions.profileActionStatus"),sessionId:B,actionId:i.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),receiptId:i.string().min(1).max(160),profileKind:i.enum(["agent","team"]),profileName:i.string().min(1).max(128),toolCallId:i.string().min(1).max(160)}).strict(),i.object({op:i.literal("sessions.answer"),sessionId:B,epoch:E.optional(),requestId:E.optional(),value:i.string().max(32768).optional(),approved:i.boolean().optional(),questionIndex:i.number().int().min(0).optional(),askId:E.optional(),answers:i.record(i.string(),i.array(i.string().max(32768))).optional(),decline:i.boolean().optional(),revise:i.boolean().optional(),dismiss:i.boolean().optional(),reason:i.enum(["answered_in_chat","moot"]).optional()}).strict(),i.object({op:i.literal("sessions.seen"),sessionId:B,completionToken:i.string().uuid()}).strict(),i.object({op:i.literal("attention.seen"),items:i.array(i.object({sessionId:B,completionToken:i.string().uuid()}).strict()).min(1).max(500)}).strict(),i.object({op:i.literal("sessions.notified"),sessionId:B,completionToken:i.string().uuid()}).strict(),i.object({op:i.literal("tags.list")}).strict(),i.object({op:i.literal("tags.replace"),tags:i.array(i.object({id:i.string().optional(),name:i.string()}).strict())}).strict(),i.object({op:i.literal("sessions.tags"),expected_revision:i.string().optional(),sessionId:B,tags:i.array(i.string()),primary:i.string().nullable()}).strict(),i.object({op:i.literal("sessions.pin"),sessionId:B,pinned:i.boolean()}).strict(),i.object({op:i.literal("sessions.watch"),sessionId:B,subscriptionId:i.string().regex(Rd),visible:i.boolean(),canNotify:i.boolean()}).strict(),i.object({op:i.literal("sessions.warm"),sessionId:B}).strict(),i.object({op:i.literal("sessions.interrupt"),sessionId:B,requestId:fe}).strict(),i.object({op:i.literal("supplements.cancel"),sessionId:B,job:Fi,anchor:Ui}).strict(),i.object({op:i.literal("supplements.restart"),sessionId:B,job:Fi,anchor:Ui}).strict(),i.object({op:i.literal("supplements.steer"),sessionId:B,job:Fi,anchor:Ui,text:i.string().min(1).max(500)}).strict(),i.object({op:i.literal("sessions.variables.list"),sessionId:B}).strict(),i.object({op:i.literal("sessions.variables.create"),sessionId:B,key:Cs,value:Fd,type:Ld}).strict(),i.object({op:i.literal("sessions.variables.update"),sessionId:B,key:Cs,value:Fd,type:Ld}).strict(),i.object({op:i.literal("sessions.variables.delete"),sessionId:B,key:Cs}).strict(),i.object({op:i.literal("sessions.presence"),subscriptionId:i.string().regex(/^[a-f0-9]{1,64}$/),canNotify:i.boolean(),canNotifyKinds:i.array(i.enum(["complete","error"])).max(4),sessionId:i.string().regex(/^([a-f0-9]{12})?$/),window:i.object({exists:i.boolean(),focused:i.boolean(),visible:i.boolean(),minimized:i.boolean()}).strict()}).strict(),i.object({op:i.literal("legacy.models"),provider:i.string().max(128).optional(),sort:i.enum(["id","name","provider","recommended"]).optional(),direction:i.enum(["ascending","descending"]).optional()}).strict(),i.object({op:i.literal("legacy.models.providers")}).strict(),i.object({op:i.literal("auth.probe"),provider:E}).strict(),i.object({op:i.literal("legacy.agent.upload"),agentId:E}).strict(),i.object({op:i.literal("agent.publish"),agentId:E,document:Vd.optional(),...zi,visibility:i.literal("org").optional(),tenantId:E.optional()}).strict(),i.object({op:i.literal("agent.republish"),agentId:E,hubAgentId:E,expectedRemoteRevision:i.string().min(1).max(512).optional(),document:Vd.optional(),...zi,visibility:i.literal("org").optional(),tenantId:E.optional()}).strict(),i.object({op:i.literal("team.publish"),teamId:E,...zi,visibility:i.literal("org").optional(),tenantId:E.optional()}).strict(),i.object({op:i.literal("team.pull"),teamId:E,tenantId:E.optional()}).strict(),i.object({op:i.literal("agent.nameAvailability"),name:i.string().min(1).max(La)}).strict(),i.object({op:i.literal("legacy.agents.list"),page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(500).optional(),name:i.string().max(256).optional(),sort:i.string().max(64).optional(),direction:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("legacy.agent.get"),agentId:E}).strict(),i.object({op:i.literal("legacy.agent.history"),agentId:E,page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(500).optional()}).strict(),i.object({op:i.literal("legacy.jobs.list"),agentId:E.optional(),status:i.string().max(64).optional()}).strict(),i.object({op:i.literal("legacy.job.get"),jobId:E}).strict(),i.object({op:i.literal("legacy.schedules.list"),page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("legacy.agent.schedules.list"),agentId:E,page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("legacy.agent.schedule.create"),agentId:E,schedule:Hd.extend({prompt:i.string().max(64e3),interval:i.number().int().min(1),unit:Dd})}).strict(),i.object({op:i.literal("legacy.schedule.get"),scheduleId:E}).strict(),i.object({op:i.literal("legacy.schedule.edit"),scheduleId:E,schedule:Hd.extend({prompt:i.string().max(64e3).nullish(),interval:i.number().int().min(1).nullish(),unit:Dd.nullish()})}).strict(),i.object({op:i.literal("legacy.schedule.remove"),scheduleId:E}).strict(),i.object({op:i.literal("legacy.agent.create"),agent:i.record(i.unknown())}).strict(),i.object({op:i.literal("legacy.agent.update"),agentId:E,update:i.record(i.unknown())}).strict(),i.object({op:i.literal("legacy.agent.delete"),agentId:E}).strict(),i.object({op:i.literal("legacy.agent.conversation.clear"),agentId:E}).strict(),i.object({op:i.literal("legacy.agent.systemPrompt.get"),agentId:E}).strict(),i.object({op:i.literal("legacy.agent.systemPrompt.update"),agentId:E,systemPrompt:i.string().max(Pv)}).strict(),i.object({op:i.literal("legacy.agent.download"),agentId:E}).strict(),i.object({op:i.literal("legacy.job.cancel"),jobId:E}).strict(),i.object({op:i.literal("commands.list")}).strict(),i.object({op:i.literal("commands.entities"),sessionId:B,command:E,name:i.string().max(128).optional()}).strict(),i.object({op:i.literal("models.catalogue"),live:i.boolean().optional(),scope:i.enum(["usable","all"]).optional()}).strict(),i.object({op:i.literal("usage.get"),provider:E.optional(),live:i.boolean().optional(),refresh:i.boolean().optional()}).strict(),i.object({op:i.literal("usage.reset"),provider:E,credentialRef:wv.optional(),identity:i.string().min(1).max(256).optional(),redeemRequestId:i.string().uuid()}).strict(),i.object({op:i.literal("quota.notice"),provider:E.optional(),model:i.string().min(1).max(200).optional(),refresh:i.boolean().optional()}).strict(),i.object({op:i.literal("analytics.get"),sessionId:B.optional(),sinceMs:i.number().int().nonnegative().optional(),untilMs:i.number().int().nonnegative().optional(),days:i.number().int().min(1).max(366).optional()}).strict(),i.object({op:i.literal("analytics.models"),sessionId:B.optional(),sinceMs:i.number().int().nonnegative().optional(),untilMs:i.number().int().nonnegative().optional(),days:i.number().int().min(1).max(366).optional()}).strict(),i.object({op:i.literal("info.get")}).strict(),i.object({op:i.literal("sessions.report"),sessionId:B,recentLimit:i.number().int().min(0).max(50).optional()}).strict(),i.object({op:i.literal("skills.list"),sessionId:B.optional(),cwd:Sv.optional(),name:Vr.optional()}).strict(),i.object({op:i.literal("skills.create"),requestId:fe,name:Vr,copyFrom:Vr}).strict(),i.object({op:i.literal("skills.update"),requestId:fe,name:Vr,expectedFingerprint:i.string().regex(/^[a-f0-9]{64}$/),files:i.array(i.object({path:i.string().min(1).max(240),content:i.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),i.object({op:i.literal("skills.remove"),requestId:fe,name:Vr,discardLocalChanges:i.boolean()}).strict(),i.object({op:i.literal("sessions.failovers"),sessionId:B}).strict(),i.object({op:i.literal("sessions.credential"),sessionId:B,action:i.enum(["list","store","forget"]),key:cs.optional(),value:ls.optional(),confirmed:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.fork"),sessionId:B,requestId:fe,message:i.string().max(2e5).optional(),boundary:i.enum(["next_safe","at_entry"]).optional(),entryId:i.string().max(128).optional(),autoTag:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.stop"),requestId:fe,targets:i.array(B).min(1).max(100),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside"),sessionId:B,requestId:fe,text:i.string().min(1).max(32768),asideId:fe.optional(),subscriptionId:i.string().regex(Rd).optional()}).strict(),i.object({op:i.literal("sessions.adopt"),sessionId:B,requestId:fe,asideId:fe,confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside.get"),sessionId:B,asideId:fe}).strict(),i.object({op:i.literal("sessions.aside.close"),sessionId:B,asideId:fe}).strict(),i.object({op:i.literal("wakes.list"),limit:i.number().int().min(1).max(500).optional(),includeDormant:i.boolean().optional()}).strict(),i.object({op:i.literal("wakes.create"),requestId:fe,sessionId:B.optional(),cwd:i.string().min(1).max(4096).optional(),target:us.optional(),message:Ud,in:i.string().min(1).max(64).optional(),at:i.string().min(1).max(64).optional(),every:i.string().min(1).max(64).optional(),until:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).optional(),title:i.string().min(1).max(200).optional()}).strict(),i.object({op:i.literal("wakes.edit"),sessionId:B,wakeId:Bd,message:Ud.optional(),in:i.string().min(1).max(64).optional(),at:i.string().min(1).max(64).optional(),every:i.string().min(1).max(64).optional(),until:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).optional()}).strict(),i.object({op:i.literal("wakes.remove"),sessionId:B,wakeId:Bd}).strict(),i.object({op:i.literal("monitors.cancel"),sessionId:B,monitorId:Fv}).strict(),i.object({op:i.literal("jobs.cancel"),sessionId:B,jobId:Uv}).strict(),i.object({op:i.literal("mcp.list"),sessionId:B}).strict(),i.object({op:i.literal("mcp.credentials.store"),sessionId:B,name:i.string().min(1).max(256),values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("mcp.control"),sessionId:B,control:i.object({action:i.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:Bi.optional(),scope:i.enum(["global","project"]).optional(),command:i.string().min(1).max(4096).optional(),args:i.array(i.string().max(8192)).max(128).optional(),env:i.record(ds).optional(),url:i.string().max(4096).optional(),headers:i.record(ds).optional(),oauth:i.boolean().optional(),confirmed:i.boolean().optional(),operation_id:Id.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog"),cwd:Hi.optional(),sessionId:B.optional()}).strict(),i.object({op:i.literal("mcp.catalog.control"),cwd:Hi.optional(),control:i.object({action:i.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:Bi.optional(),scope:i.enum(["global","project"]).optional(),command:i.string().min(1).max(4096).optional(),args:i.array(i.string().max(8192)).max(128).optional(),env:i.record(ds).optional(),url:i.string().max(4096).optional(),headers:i.record(ds).optional(),confirmed:i.boolean().optional(),operation_id:Id.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog.credentials"),header:i.string().min(1).max(128).optional(),cwd:Hi.optional(),name:Bi,values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("radient.request"),control:i.object({operation:i.enum(["account","prices","credits","usage","provision","application.create","agents.list","agents.get","agents.create","agents.update","agents.delete","agents.like","agents.unlike","agents.liked","agents.like_count","agents.favourite","agents.unfavourite","agents.favourited","agents.favourite_count","agents.download_count","agents.statuses","comments.list","comments.create","comments.update","comments.delete","account.agents","memberships.list","org_agents.list","org_team.get","org_teams.list","org_skills.list","org_skill.get","signup.resend","team_trial.eligibility","team_trial.start","team_trial.status"]),request_id:fe.optional(),tenant_id:E.optional(),account_id:E.optional(),agent_id:E.optional(),comment_id:E.optional(),team_id:E.optional(),skill_id:E.optional(),query:i.record(i.union([i.string().max(1024),i.number().int()])).optional(),payload:i.record(i.unknown()).optional(),confirmed:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("providers.list")}).strict(),i.object({op:i.literal("accounts.list")}).strict(),i.object({op:i.literal("accounts.remove"),accountId:i.number().int().positive(),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("tunnel.setup.read"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.plan"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.run"),credentialId:i.number().int().positive(),acceptMonthlyPrice:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("auth.start"),provider:E}).strict(),i.object({op:i.literal("auth.status"),id:E}).strict(),i.object({op:i.literal("auth.input"),id:E,promptId:E,value:ls}).strict(),i.object({op:i.literal("auth.cancel"),id:E}).strict(),i.object({op:i.literal("auth.key"),provider:E,value:ls}).strict(),i.object({op:i.literal("auth.logout"),provider:E}).strict(),i.object({op:i.literal("agent_messages.status"),boundary:Sd}).strict(),i.object({op:i.literal("agent_messages.enable"),expected_account_id:E,tenant_id:E,state:i.literal("active"),consent_version:i.string().min(1).max(128),consented_via:i.literal("dialog")}).strict(),i.object({op:i.literal("agent_messages.settings"),tenant_id:E.optional()}).strict(),i.object({op:i.literal("agent_messages.settings.put"),expected_account_id:E,tenant_id:E.optional(),consent_version:i.string().min(1).max(128).optional(),consented_via:i.enum(["dialog","settings"]).optional(),label:i.string().min(1).max(128).optional(),state:i.enum(["active","paused","disabled"])}).strict(),i.object({op:i.literal("agent_messages.onboarding.dismiss")}).strict(),i.object({op:i.literal("agent_messages.allowlist.get"),tenant_id:E.optional()}).strict(),i.object({op:i.literal("agent_messages.allowlist.put"),expected_account_id:E,tenant_id:E.optional(),entries:i.array(i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:i.object({endpoint_id:E.optional(),account_id:E.optional()}).strict().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id")}).strict()).max(200)}).strict(),i.object({op:i.literal("team_bridge.conversations.list"),scope:i.literal("account").optional(),tenant_id:E.optional(),limit:i.number().int().min(1).max(100).optional(),cursor:i.string().min(1).max(512).optional(),before:i.string().min(1).max(64).optional(),status:i.enum(["open","archived"]).optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.get"),conversation_id:E,tenant_id:E.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.create"),expected_account_id:E.optional(),tenant_id:E.optional(),kind:i.enum(["dm","group","channel"]),name:i.string().min(1).max(128).optional(),topic:i.string().min(1).max(512).optional(),visibility:i.enum(["private","tenant"]).optional(),agent_capable:i.boolean().optional(),members:i.array(i.object({account_id:E,kind:i.enum(["human","agent"]),endpoint_id:E.optional(),display_label:i.string().min(1).max(64)}).strict()).max(500)}).strict(),i.object({op:i.literal("team_bridge.conversations.lifecycle"),expected_account_id:E.optional(),tenant_id:E.optional(),conversation_id:E,action:i.enum(["archive","unarchive","join","leave"])}).strict(),i.object({op:i.literal("team_bridge.conversations.join"),expected_account_id:E.optional(),conversation_id:E,tenant_id:E.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.leave"),expected_account_id:E.optional(),conversation_id:E,tenant_id:E.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.notify"),expected_account_id:E.optional(),conversation_id:E,tenant_id:E.optional(),notify:i.enum(["all","mention","mute"])}).strict(),i.object({op:i.literal("team_bridge.conversations.agent_notify"),expected_account_id:E.optional(),conversation_id:E,tenant_id:E.optional(),notify:i.enum(["all","mention","mute"])}).strict(),i.object({op:i.literal("team_bridge.conversations.members.add"),expected_account_id:E.optional(),conversation_id:E,tenant_id:E.optional(),members:i.array(i.object({account_id:E,kind:i.enum(["human","agent"]),endpoint_id:E.optional(),display_label:i.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),i.object({op:i.literal("team_bridge.conversations.members.remove"),expected_account_id:E.optional(),tenant_id:E.optional(),conversation_id:E,account_id:E}).strict(),i.object({op:i.literal("team_bridge.conversations.delete"),expected_account_id:E.optional(),tenant_id:E.optional(),conversation_id:E}).strict(),i.object({op:i.literal("team_bridge.conversations.consent"),expected_account_id:E.optional(),conversation_id:E,account_id:E,decision:i.enum(["accept","decline","withdraw"]),consent_version:i.string().min(1).max(128).optional(),endpoint_id:E.optional(),tenant_id:E.optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.conversations"),expected_account_id:E,tenant_id:E,limit:i.number().int().min(1).max(100).optional(),cursor:i.string().min(1).optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.messages"),expected_account_id:E,tenant_id:E,conversation_id:E,limit:i.number().int().min(1).max(100).optional(),before_seq:i.number().int().nonnegative().optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.replies"),expected_account_id:E,tenant_id:E,conversation_id:E,message_id:E,limit:i.number().int().min(1).max(100).optional(),after_seq:i.number().int().nonnegative().optional(),before_seq:i.number().int().positive().optional(),order:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("team_bridge.messages.list"),conversation_id:E,tenant_id:E.optional(),limit:i.number().int().min(1).max(100).optional(),before_seq:i.number().int().nonnegative().optional(),endpoint_id:E.optional()}).strict(),i.object({op:i.literal("team_bridge.typing.get"),conversation_id:E,tenant_id:E}).strict(),i.object({op:i.enum(["team_bridge.typing.set","team_bridge.typing.clear"]),conversation_id:E,tenant_id:E,expected_account_id:E,thread_root_id:E.optional()}).strict(),i.object({op:i.literal("agent_messages.settings.share_typing"),expected_account_id:E,share_typing:i.boolean()}).strict(),i.object({op:i.literal("team_bridge.reactions.toggle"),conversation_id:E,message_id:E,expected_account_id:E,tenant_id:E,emoji:i.string().min(1),active:i.boolean()}).strict(),i.object({op:i.literal("team_bridge.messages.send"),expected_account_id:E.optional(),conversation_id:E,tenant_id:E.optional(),client_ref:E,body:i.string(),agent_label:i.string().min(1).max(64).optional(),thread_root_id:E.optional(),attachment_ids:Gi.optional(),files:i.array(E).min(1).max(10).refine(e=>new Set(e).size===e.length,"Duplicate file").optional(),mentions:Nv.optional()}).strict(),i.object({op:i.literal("team_bridge.messages.replies"),conversation_id:E,message_id:E,expected_account_id:E,tenant_id:E,limit:i.number().int().min(1).max(100).optional(),after_seq:i.number().int().nonnegative().optional(),before_seq:i.number().int().positive().optional(),order:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("team_bridge.scheduled.list"),tenant_id:E}).strict(),i.object({op:i.literal("team_bridge.scheduled.create"),tenant_id:E,conversation_id:E,client_ref:E,body:i.string(),send_at:i.string().datetime({offset:!0}),attachment_ids:Gi.optional(),thread_root_id:E.optional()}).strict(),i.object({op:i.literal("team_bridge.scheduled.update"),tenant_id:E,scheduled_id:E,body:i.string().optional(),send_at:i.string().datetime({offset:!0}).optional(),attachment_ids:Gi.optional(),expected_version:i.number().int().nonnegative().optional()}).strict(),i.object({op:i.literal("team_bridge.attachments.delete"),tenant_id:E,conversation_id:E,attachment_id:E,expected_account_id:E}).strict(),i.object({op:i.literal("team_bridge.scheduled.cancel"),tenant_id:E,scheduled_id:E}).strict(),i.object({op:i.literal("team_bridge.read"),expected_account_id:E.optional(),conversation_id:E,tenant_id:E.optional(),seq:i.number().int().nonnegative().optional(),muted:i.boolean().optional()}).strict(),i.object({op:i.literal("team_bridge.thread_read"),expected_account_id:E,conversation_id:E,message_id:E,tenant_id:E,seq:i.number().int().nonnegative()}).strict(),i.object({op:i.literal("team_bridge.unread"),scope:i.literal("account").optional(),tenant_id:E.optional()}).strict(),i.object({op:i.literal("team_bridge.directory"),tenant_id:E}).strict(),i.object({op:i.literal("team_bridge.status"),boundary:Sd.optional()}).strict(),i.object({op:i.literal("team_bridge.link_preview.resolve"),url:i.string().min(1).max(_v),index:i.number().int().nonnegative(),expectedAccountId:E}).strict(),i.object({op:i.literal("settings.list")}).strict(),i.object({op:i.literal("settings.edit"),key:cs,value:i.unknown().refine(e=>e!==void 0,"A setting value is required."),base:$v.optional()}).strict(),i.object({op:i.literal("settings.reset"),key:cs}).strict(),i.object({op:i.literal("tts.paths")}).strict(),i.object({op:i.literal("notification_sounds.list")}).strict(),i.object({op:i.literal("notification_sounds.rename"),id:i.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/),name:i.string().min(1).max(200)}).strict(),i.object({op:i.literal("notification_sounds.remove"),id:i.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)}).strict(),i.object({op:i.literal("config.get")}).strict(),i.object({op:i.literal("config.update"),value:Bv}).strict(),i.object({op:i.literal("instructions.get")}).strict(),i.object({op:i.literal("instructions.update"),content:i.string().max(64e3)}).strict(),i.object({op:i.literal("credentials.list")}).strict(),i.object({op:i.literal("credentials.update"),key:cs,value:ls}).strict(),i.object({op:i.literal("peers.list")}).strict(),i.object({op:i.literal("networks.list")}).strict(),i.object({op:i.literal("networks.invite"),networkId:mr,role:i.enum(["read","drive","admin"]),deviceId:mr.optional()}).strict(),i.object({op:i.literal("networks.member.remove"),networkId:mr,deviceId:mr,confirm:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("sessions.transfer"),sessionId:B,to:i.union([i.literal("local"),mr]),keep:i.boolean().optional(),waitS:i.number().min(0).max(300).optional(),requestId:fe.optional()}).strict(),i.object({op:i.literal("approvals.list")}).strict(),i.object({op:i.literal("approvals.approve"),approvalId:Zr}).strict(),i.object({op:i.literal("approvals.deny"),approvalId:Zr}).strict(),...["approvals.approveOperation","approvals.applyOperation"].map(e=>i.object({op:i.literal(e),approvalId:Zr,operation:i.literal("profile_save"),requestDigest:i.string().regex(Zs),disclosureDigest:i.string().regex(Zs)}).strict()),i.object({op:i.literal("approvals.approveCredential"),approvalId:Zr,...Td}).strict(),i.object({op:i.literal("approvals.applyCredential"),approvalId:Zr,...Td}).strict(),i.object({op:i.literal("asks.list")}).strict(),i.object({op:i.literal("projects.list")}).strict(),i.object({op:i.literal("projects.get"),key:En}).strict(),i.object({op:i.literal("projects.create"),name:Ki,description:i.string().max(Jd).optional(),status:Zd.optional(),tags:Yd.optional()}).strict(),i.object({op:i.literal("projects.update"),key:En,fields:i.object({name:Ki.optional(),title:i.string().max(80).optional(),owner:i.string().max(80).optional(),team:i.string().max(80).optional(),description:i.string().max(Jd).optional(),status:Zd.optional(),progress:i.string().max(iy).optional(),tags:Yd.optional(),start_date:ps.optional(),target_date:ps.optional(),completed_at:ps.optional(),estimate:i.number().positive().max(1e3).optional(),estimate_unit:i.enum(["points","days"]).optional()}).strict(),force_done:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.delete"),key:En,confirmed_name:Ki}).strict(),i.object({op:i.literal("projects.link"),key:En,sessionId:B}).strict(),i.object({op:i.literal("projects.unlink"),key:En,sessionId:B}).strict(),i.object({op:i.literal("projects.milestone"),key:En,name:i.string().min(1).max(Qd),targetDate:ps.optional(),completed:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.milestone.remove"),key:En,name:i.string().min(1).max(Qd)}).strict(),i.object({op:i.literal("projects.request_update"),key:En}).strict(),i.object({op:i.literal("projects.search"),q:i.string().min(1).max(ay),limit:i.number().int().min(1).max(ly).optional()}).strict(),i.object({op:i.literal("aida.status")}).strict(),i.object({op:i.literal("aida.control"),action:i.enum(["open","pause","resume","greet","status"])}).strict(),i.object({op:i.literal("code_requests.list"),sessionId:B}).strict(),i.object({op:i.literal("code_requests.refresh"),sessionId:B,keys:i.array(i.string().min(1).max(512)).max(256).optional(),force:i.boolean().optional()}).strict(),i.object({op:i.literal("static.sign"),route:i.enum(["images","videos","audio","html"]),path:i.string().min(1),ttlS:i.number().int().min(1).max(3600).optional()}).strict(),i.object({op:i.literal("library.list"),scope:i.enum(["final","all"]).optional(),q:i.string().max(512).optional(),category:i.string().min(1).max(64).optional(),kind:i.string().min(1).max(64).optional(),origin_group:i.enum(["generated","created","mentioned"]).optional(),origin:i.string().min(1).max(64).optional(),tag:i.string().min(1).max(128).optional(),tag_mode:i.enum(["all","any"]).optional(),highlighted:i.boolean().optional(),organized:i.boolean().optional(),favorite:i.boolean().optional(),session:i.string().min(1).max(12).optional(),session_id:i.string().min(1).max(512).optional(),sort:i.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(512).optional()}).strict(),i.object({op:i.literal("library.get"),id:Yr}).strict(),i.object({op:i.literal("library.update"),id:Yr,fields:i.object({name:i.string().max(200).optional(),description:i.string().max(2e3).optional(),favorite:i.boolean().optional(),locked:i.boolean().optional(),archived:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("library.tags")}).strict(),i.object({op:i.literal("library.tags.create"),name:i.string().trim().min(1).max(24),category:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("library.tags.update"),id:Jr,name:i.string().trim().min(1).max(24).optional(),category:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("library.tags.delete"),id:Jr}).strict(),i.object({op:i.literal("library.tags.merge"),id:Jr,into:Jr}).strict(),i.object({op:i.literal("library.tags.assign"),id:Yr,tags:i.array(Jr).max(64),primary:i.string().max(128).optional()}).strict(),i.object({op:i.literal("library.chat.link"),id:Yr,sessionId:B}).strict(),i.object({op:i.literal("library.chat.clear"),id:Yr}).strict(),i.object({op:i.literal("library.librarian"),action:i.enum(["status","open","pause","resume","run"]).optional()}).strict(),i.object({op:i.literal("sidebar_layout.get")}).strict(),i.object({op:i.literal("sidebar_layout.set"),layout:uy}).strict(),i.object({op:i.literal("notifications.list"),preview:i.literal(!0).optional(),includeAskReads:i.boolean().optional(),countSessionIds:i.array(B).max(50).optional(),kind:i.enum(["all","asks","updates"]).optional(),bulkPriority:i.enum(["any","high","normal_up"]).optional(),state:i.enum(["unread","all","dismissed"]).optional(),source:i.enum(["notify","ask"]).optional(),priority:i.enum(["high","normal","low"]).optional(),sessionId:B.optional(),throughSeq:i.number().int().min(0).optional(),cursor:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("notifications.get"),id:dn}).strict(),i.object({op:i.literal("notifications.count")}).strict(),i.object({op:i.literal("notifications.read"),verb:i.enum(["read","unread","undo"]),target:i.union([eu,qd,fy])}).strict(),i.object({op:i.literal("notifications.dismiss"),verb:i.enum(["dismiss","undismiss"]),target:i.union([eu,qd])}).strict(),i.object({op:i.literal("notifications.seen"),items:i.array(i.object({id:dn,revision:i.number().int().min(1),anchorId:i.string().min(1).max(256),visibleSinceMs:i.number().int().min(0)}).strict()).min(1).max(50),evidence:i.object({sessionId:B,inputKind:i.enum(["pointer","key","wheel"]),inputAtMs:i.number().int().min(0),visibleSinceMs:i.number().int().min(0)}).strict()}).strict()]);hy.superRefine((e,t)=>{if(e.op==="usage.reset"&&!e.credentialRef&&!e.identity&&t.addIssue({code:i.ZodIssueCode.custom,message:"A usage reset must name an account: send `credentialRef` or `identity`.",path:["credentialRef"]}),e.op==="team_bridge.conversations.consent"&&e.decision==="withdraw"!=(e.consent_version===void 0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"accept and decline require consent_version; withdraw carries none",path:["consent_version"]}),(e.op==="notifications.read"||e.op==="notifications.dismiss")&&"items"in e.target&&!!e.target.receipt!=(e.target.throughSeq!==void 0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"Receipt writes require a sequence boundary",path:["target"]}),e.op==="notifications.read"&&e.verb==="undo"!="operationToken"in e.target&&t.addIssue({code:i.ZodIssueCode.custom,message:"Undo requires an operation token, and only undo accepts one",path:["target"]}),e.op==="team_bridge.messages.send"&&e.files){const n=e.attachment_ids??[];(n.length+e.files.length>10||e.files.some(r=>n.includes(r)))&&t.addIssue({code:i.ZodIssueCode.custom,message:"Invalid combined attachment set",path:["files"]})}if((e.op==="team_bridge.messages.send"||e.op==="team_bridge.scheduled.create"||e.op==="team_bridge.scheduled.update"&&e.body!==void 0)&&e.body?.trim()===""&&(e.attachment_ids?.length??0)===0&&!(e.op==="team_bridge.messages.send"&&e.files?.length)){t.addIssue({code:i.ZodIssueCode.custom,message:"A message needs text or an image",path:["body"]});return}if(e.op.startsWith("team_bridge.")&&"expected_account_id"in e&&e.expected_account_id&&(!("tenant_id"in e)||!e.tenant_id)){t.addIssue({code:i.ZodIssueCode.custom,path:["tenant_id"],message:"Guarded conversation writes require an explicit tenant"});return}if(e.op==="team_bridge.messages.send"&&e.thread_root_id!==void 0&&!e.expected_account_id){t.addIssue({code:i.ZodIssueCode.custom,path:["expected_account_id"],message:"Thread replies require the captured account"});return}if(e.op==="hub.skillPull"||e.op==="hub.skillSubscribe"||e.op==="hub.skillPublish"){if(e.visibility==="public"&&e.tenantId!==null||e.visibility==="org"&&!e.tenantId){t.addIssue({code:i.ZodIssueCode.custom,message:"A skill destination requires explicit paired scope",path:["tenantId"]});return}if(e.op==="hub.skillPublish"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:i.ZodIssueCode.custom,message:"An initial skill publication requires its reviewed draft receipt",path:["previewReceipt"]});return}}if(e.op==="hub.check"||e.op==="hub.apply"||e.op==="hub.retry"){const n=e.name!==void 0,r=e.localId!==void 0,o=e.op!=="hub.check";if(n&&r||o&&!n&&!r||r&&e.kind===void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"A hub action addresses one item by name or local id, never both",path:["localId"]});return}}if(e.op==="hub.apply"&&e.resolveSource===!0){const n=e.visibility==="public"&&e.tenantId===null||e.visibility==="org"&&typeof e.tenantId=="string"&&e.tenantId.length>0;if(!e.hubSource||!n||e.acknowledgeUnknownBaseline!==!0||e.localId!==void 0||e.prefer!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"Confirming a source requires its exact stated destination and the unknown-baseline acknowledgement, addressed by name, with no preference",path:["hubSource"]});return}}if(e.op==="hub.push"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:i.ZodIssueCode.custom,message:"A confirmed publication requires its reviewed preview receipt",path:["previewReceipt"]});return}if(e.op==="hub.policy"&&e.subscribe===void 0&&e.autoPush===void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"A hub policy change must name subscribe or autoPush",path:["subscribe"]});return}if((e.op==="team_bridge.conversations.list"||e.op==="team_bridge.unread")&&e.scope==="account"&&e.tenant_id!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"An account-scoped read cannot name a tenant",path:["scope"]});return}if(e.op==="team_bridge.conversations.list"&&e.scope==="account"&&e.before!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"An account-scoped page uses cursor, not before",path:["before"]});return}if(e.op==="sessions.answer"){if(e.askId!==void 0){if(e.askId||t.addIssue({code:i.ZodIssueCode.custom,message:"ask_id must be a non-empty string",path:["askId"]}),e.dismiss===!0){(e.answers!==void 0||e.decline===!0||e.revise===!0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:i.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:i.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:i.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:i.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:i.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:i.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:i.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:i.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:i.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"reason applies to a queued ask",path:["reason"]});return}if(e.op==="sessions.create"&&e.purpose===void 0){e.cwd===void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"A conversation needs a working directory: only a configuration run (`purpose`) may omit `cwd`.",path:["cwd"]});return}if(e.op==="sessions.create"&&e.purpose!==void 0){for(const n of["cwd","target","model","draftId"])e[n]!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:`A configuration run resolves its own \`${n}\`: send \`purpose\` alone.`,path:[n]});return}if(!(e.op!=="agent.publish"&&e.op!=="agent.republish"&&e.op!=="team.publish")){if((e.subscribe!==void 0||e.autoPush!==void 0||e.confirmPublicEgress!==void 0)&&!e.requestId){t.addIssue({code:i.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:i.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const He={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed",serverUpdating:"transient.server-updating"},Tp="service is preparing a safe reload; retry shortly",Cp="serve_reloading";function my(e,t){if(e!==503||t===null||typeof t!="object")return!1;const n=t.detail;return n===Tp?!0:n!==null&&typeof n=="object"&&n.code===Cp}function gy(e){return e!==null&&typeof e=="object"&&e.updating===!0}function _y(e){return e!==null&&typeof e=="object"&&e.update_stalled===!0}const by={runtimeUnreachable:"runtime_unreachable"},mi="runtime_busy",Op="runtime_retiring";i.object({data:i.object({aside_id:i.string().optional(),status:i.union([i.enum(["adopted","queued"]),i.string()]).optional()}).passthrough()}).passthrough();const Pp=i.object({name:i.string(),description:i.string().nullish(),source:i.string().nullish(),link_id:i.string().nullish(),editable:i.boolean().nullish(),installed:i.boolean().nullish(),fingerprint:i.string().nullish(),form:i.string().nullish()}).passthrough(),vy=i.object({path:i.string(),size:i.number().nullish(),preview:i.string().nullish(),preview_truncated:i.boolean().nullish()}).passthrough(),yy=Pp.extend({body:i.string().nullish(),body_in_detail:i.boolean().nullish(),body_length:i.number().nullish(),body_bytes:i.number().nullish(),body_truncated:i.boolean().nullish(),files:i.array(vy).nullish(),files_total:i.number().nullish(),files_truncated:i.boolean().nullish(),publish_budget:i.object({limit:i.number(),total:i.number()}).passthrough().nullish()}).passthrough(),vP=i.object({skills:i.array(Pp),scope:i.string().nullish(),detail:i.string().nullish(),skill_detail:yy.nullish(),warning_count:i.number().nullish(),version:i.string().nullish()}).passthrough(),yP=i.object({reset:i.object({outcome:i.union([i.enum(["reset","already_redeemed","no_credit","nothing_to_reset","failed","refused"]),i.string()]),windows_reset:i.number().int().nonnegative(),detail:i.string().default(""),refused:i.boolean()}).passthrough(),usage:i.object({reports:i.array(i.record(i.unknown())),source:i.string(),fetched_at:i.number()}).passthrough().nullish()}).passthrough(),wP="aside_adopt_refused",wy=["session_closed","open_tool_batch","turn_running"];function kP(e){if(typeof e!="object"||e===null)return;const t=e.reason;return wy.find(n=>n===t)}const ky={[He.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[He.refused]:"ui.common.errors.desktop_refusal.refused",[He.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[He.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed",[He.serverUpdating]:"ui.common.errors.desktop_refusal.server_updating"},Ua={noCredential:"Restart with a desktop-managed backend to use these controls.",transportFailed:"The backend could not complete this request. Check its connection and try again."};function gi(e){return e!==void 0&&Object.values(He).includes(e)}function Sy(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return He.refused;if(t===503)return He.planeClosed}}const SP=i.object({step:i.string(),blocked_on:i.string(),configured:i.boolean(),ready:i.boolean(),verified:i.boolean(),url:i.string().nullable(),credential_id:i.number().int().positive().nullable(),identity_label:i.string().nullable(),credential_choices:i.array(i.object({id:i.number().int().positive(),identity_label:i.string().nullable().optional()}).passthrough()).default([]),quote:i.object({monthly_price_usd:i.string().nullable(),positive_balance:i.boolean(),eligible:i.boolean(),account_valid:i.boolean()}).passthrough().nullable(),receipts:i.array(i.object({step:i.string(),ok:i.boolean(),text:i.string()})).default([]),remedy:i.object({kind:i.string(),text:i.string(),command:i.string().nullable().optional(),url:i.string().nullable().optional()}).nullable(),source:i.string(),in_progress:i.boolean().default(!1),progress:i.array(i.string()).default([]),active_credential_id:i.number().int().positive().nullable().default(null),billing_outcome:i.string().optional(),reservation_outcome:i.string().optional(),failure_stage:i.string().optional(),transport:i.string().optional()}).passthrough();function EP(e){return e.transport!=="relay"?!1:e.blocked_on==="cloudflared"||e.remedy?.kind==="install_cloudflared"}const AP=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),Ey=88e4,Ay=11e5,Iy=2e4,Ry=9e4,xy=new Set(["analytics.get","analytics.models","sessions.report"]),Ty=new Set(["usage.get"]),Cy=new Set(["networks.list","peers.list"]),Oy=new Set(["usage.reset"]),Py=new Set([...xy,...Ty,...Cy,...Oy]),My=90,jy=30,$y=300,Ny=10,Mp=15,Dy=1e4;function Ly(e){const n=e.to==="local"||e.keep?$y:jy,r=Math.max(0,e.waitS??0);return(My+n+Ny+Mp)*1e3+r*1e3}const Fy=18e4,Uy=Fy+15e3,By=120,Hy=135e3,Wy=93e4,jp=(By+30+Mp)*1e3,Gy=6e4,zy=5*jp,Ky=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function Vy(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 jp;case"hub.check":return Gy;case"hub.applyAll":return zy;default:return null}}function Zy(e){if(typeof e!="string"&&e.op==="sessions.transfer")return Ly(e)+Dy;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return Uy;if(t==="tunnel.setup.run")return Wy;if(t==="tunnel.setup.plan")return Hy;const n=Vy(t);return n!==null?n:Py.has(t)?Ry:Iy}const Yy=5e3;function $p(e){return Zy(e)+Yy}const Wc="deadline_exceeded",Np="foreground_required",Dp="View these completions in the foreground before marking them read.",Jy=new Set(["capabilities","agent_messages.status","agent_messages.settings","agent_messages.allowlist.get","team_bridge.conversations.list","team_bridge.conversations.get","team_bridge.messages.list","team_bridge.messages.replies","team_bridge.owner_audit.conversations","team_bridge.owner_audit.messages","team_bridge.owner_audit.replies","team_bridge.unread","team_bridge.directory","team_bridge.status","accounts.list","analytics.get","analytics.models","approvals.list","commands.entities","commands.list","config.get","credentials.list","hub.updates","hub.links","info.get","instructions.get","legacy.agent.get","legacy.agent.history","legacy.agent.schedules.list","legacy.agents.list","legacy.job.get","legacy.jobs.list","legacy.models","legacy.models.providers","legacy.schedule.get","legacy.schedules.list","mcp.catalog","mcp.list","models.catalogue","networks.list","peers.list","profiles.get","profiles.list","projects.search","providers.list","quota.notice","runtimes.list","sessions.aside.get","sessions.checkpoints","sessions.failovers","sessions.find","sessions.get","sessions.history","sessions.files","sessions.userAttachments","sessions.list","sessions.preview","sessions.report","sessions.search","sessions.variables.list","skills.list","subagents.transcript","teams.effective","teams.get","teams.list","tunnel.setup.plan","tunnel.setup.read","usage.get"]),Qy=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Xy(e,t){const n=Math.round(t/1e3),r=Wc;return e==="sessions.transfer"?{code:r,message:`The app waits up to ${n} seconds for a move, and it was still running when the app stopped waiting. The move was asked for, so its outcome is unknown from here: read the session again before moving it anywhere else.`}:e==="approvals.approve"||e==="approvals.approveCredential"?{code:r,message:`The app waits up to ${n} seconds for an approval, and the signing prompt was still open when it stopped waiting. The request was sent, so the decision may or may not have landed: read the approvals again — if the record still waits, answering it again is safe, because the store keeps the first decision and refuses a second.`}:Ky.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:Jy.has(e)?{code:r,message:Qy.has(e)?`The app waits up to ${n} seconds for this panel's data, and the read was still running when the app stopped waiting. Nothing was read; reopen the panel to ask again.`:`The app waits up to ${n} seconds for this read, and it was still running when the app stopped waiting. Nothing was read; ask again.`}:{code:r,message:`The app waits up to ${n} seconds for this request, and it was still running when the app stopped waiting. It may or may not have reached the server; check the result before repeating it.`}}const IP=Ey,RP=Ay;i.object({state:i.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:i.string(),kind:i.enum(["balance","subscription","radient","none"]),model_free:i.boolean(),title:i.string(),body:i.string(),actions:i.array(i.object({id:i.enum(["open_url","resend_verification","refresh"]),label:i.string(),url:i.string().nullable().optional()})),resets_at_ms:i.number().int().nullable().optional(),checked_at_ms:i.number().int(),age_ms:i.number().int().nullable().optional(),source:i.enum(["cached","live"])});function qy(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function tu(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 Zi(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 Yi(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 nu(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 Qr(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 ms(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function ew(e){switch(e.op){case"capabilities":return{path:"/v1/capabilities",method:"GET"};case"runtimes.list":return{path:"/v1/desktop/runtimes?probe=false",method:"GET"};case"peers.list":return{path:"/v1/desktop/peers",method:"GET"};case"networks.list":return{path:"/v1/desktop/networks",method:"GET"};case"asks.list":return{path:"/v1/desktop/asks",method:"GET"};case"networks.invite":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/invite`,method:"POST",body:{role:e.role,device:e.deviceId??null}};case"networks.member.remove":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/members/${encodeURIComponent(e.deviceId)}`,method:"DELETE",body:{confirm:e.confirm}};case"sessions.transfer":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/transfer`,method:"POST",body:{to:e.to,keep:e.keep??!1,wait_s:e.waitS??0,...e.requestId?{request_id:e.requestId}:{}}};case"approvals.list":return{path:"/v1/desktop/approvals",method:"GET"};case"approvals.approve":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/approve`,method:"POST"};case"approvals.deny":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/deny`,method:"POST"};case"approvals.approveOperation":case"approvals.applyOperation":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveOperation"?"approve-operation":"apply-operation"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"approvals.approveCredential":case"approvals.applyCredential":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveCredential"?"approve-credential":"apply-credential"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"profiles.list":return{path:"/v1/desktop/profiles",method:"GET"};case"profiles.get":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"GET"};case"profiles.install":return{path:"/v1/desktop/profiles/install",method:"POST",body:{request_id:e.requestId,name:e.name}};case"imports.sources":return{path:"/v1/desktop/imports/sources",method:"GET"};case"imports.sessions":{const t=new URLSearchParams({source:e.source});return e.includeSubagents&&t.set("include_subagents","true"),{path:`/v1/desktop/imports/sessions?${t.toString()}`,method:"GET"}}case"imports.preview":return{path:"/v1/desktop/imports/preview",method:"POST",body:nu(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:nu(e)};case"imports.status":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"GET"};case"imports.cancel":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"DELETE"};case"profiles.create":return{path:"/v1/desktop/profiles",method:"POST",body:{request_id:e.requestId,name:e.name,...e.fields}};case"profiles.update":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"hub.updates":return{path:"/v1/desktop/hub/updates",method:"GET"};case"hub.skillPull":return{path:"/v1/desktop/hub/skills/pull",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.adoptionStrategy!==void 0?{adoption_strategy:e.adoptionStrategy}:{},...e.allowLlm!==void 0?{allow_llm:e.allowLlm}:{},...e.confirm!==void 0?{confirm:e.confirm}:{},...e.adoptionReceipt!==void 0?{adoption_receipt:e.adoptionReceipt}:{}}};case"hub.skillSubscribe":return{path:"/v1/desktop/hub/skills/subscribe",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias}};case"hub.skillUnpull":return{path:"/v1/desktop/hub/skills/unpull",method:"POST",body:{request_id:e.requestId,link_id:e.linkId}};case"hub.skillPublish":return{path:"/v1/desktop/hub/skills/publish",method:"POST",body:{request_id:e.requestId,dry_run:e.dryRun,source_skill:e.sourceSkill,local_alias:e.localAlias,visibility:e.visibility,tenant_id:e.tenantId,subscribe:e.subscribe,auto_push:e.autoPush,confirm_public_egress:e.confirmPublicEgress,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"hub.links":return{path:`/v1/desktop/hub/links${e.kind?`?kind=${e.kind}`:""}`,method:"GET"};case"hub.policy":return{path:`/v1/desktop/hub/links/${encodeURIComponent(e.linkId)}`,method:"PATCH",body:{request_id:e.requestId,expected_policy_revision:e.expectedPolicyRevision,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}};case"hub.check":return{path:"/v1/desktop/hub/updates/check",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{}}};case"hub.apply":return{path:"/v1/desktop/hub/updates/apply",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{},...e.prefer?{prefer:e.prefer}:{},...e.acknowledgeUnknownBaseline!==void 0?{acknowledge_unknown_baseline:e.acknowledgeUnknownBaseline}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.resolveSource===!0?{resolve_source:!0,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId??null}:{}}};case"hub.applyAll":return{path:"/v1/desktop/hub/updates/apply-all",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{}}};case"hub.retry":return{path:"/v1/desktop/hub/updates/retry",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{}}};case"hub.push":return{path:"/v1/desktop/hub/updates/push",method:"POST",body:{request_id:e.requestId,link_id:e.linkId,direction:e.direction,dry_run:e.dryRun,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"teams.list":return{path:"/v1/desktop/teams",method:"GET"};case"teams.get":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"GET"};case"teams.effective":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}/effective`,method:"GET"};case"teams.create":return{path:"/v1/desktop/teams",method:"POST",body:{request_id:e.requestId,...e.fields}};case"teams.update":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"sessions.list":{const t=new URLSearchParams;return t.set("limit",String(e.limit??100)),e.include_archived&&t.set("include_archived","true"),e.scope_kind&&t.set("scope_kind",e.scope_kind),e.scope_name&&t.set("scope_name",e.scope_name),e.cursor&&t.set("cursor",e.cursor),e.with_counts&&t.set("with_counts","true"),e.include_peers&&t.set("include_peers","true"),e.sort&&t.set("sort",e.sort),{path:`/v1/desktop/sessions?${t}`,method:"GET"}}case"delegated_cleanup_notice.ack":return{path:"/v1/desktop/delegated-cleanup-notice/ack",method:"POST"};case"sessions.search":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??xv)});return e.include_archived&&t.set("include_archived","true"),{path:`/v1/desktop/sessions/search?${t}`,method:"GET"}}case"sessions.archive":return{path:`/v1/desktop/sessions/${e.sessionId}/archive`,method:"POST",body:{archived:e.archived}};case"sessions.delete":return{path:`/v1/desktop/sessions/${e.sessionId}`,method:"DELETE",body:{confirmed:!0}};case"sessions.create":return{path:"/v1/desktop/sessions",method:"POST",body:{request_id:e.requestId,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.peer?{peer:e.peer}:{},...e.target?{target:e.target}:{},...e.model?{model:e.model}:{},...e.draftId?{draft_id:e.draftId}:{},...e.purpose?{purpose:e.purpose}:{}}};case"sessions.preview":return{path:"/v1/desktop/sessions/preview",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.draft":return{path:"/v1/desktop/sessions/draft",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.get":{const t=new URLSearchParams;return e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),Vs(t,`/v1/desktop/sessions/${e.sessionId}`,e.orderIds??[])),{path:`/v1/desktop/sessions/${e.sessionId}${t.size?`?${t}`:""}`,method:"GET"}}case"sessions.files":{const t=new URLSearchParams({limit:String(e.limit??200)});for(const n of["scope","kind","q","sort","order","cursor"]){const r=e[n];r!==void 0&&t.set(n,r)}return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files?${t}`,method:"GET"}}case"sessions.files.materialise":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files/${encodeURIComponent(e.fileId)}/materialise`,method:"POST"};case"sessions.userAttachments":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/user-attachments`,method:"GET"};case"sessions.userAttachments.materialise":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/user-attachments/${encodeURIComponent(e.digest)}/materialise`,method:"POST"};case"sessions.history":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.openFrame&&(t.set("open_frame","1"),t.set("supplements","1")),e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),e.sourceRead==="metadata"?t.set("source_read","metadata"):e.sourceRead==="payload"&&e.expectedJournalGeneration&&t.set("source_read","payload"),e.expectedJournalGeneration&&t.set("expected_journal_generation",e.expectedJournalGeneration),Vs(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??Cv)});return{path:`/v1/desktop/sessions/${e.sessionId}/find?${t}`,method:"GET"}}case"subagents.transcript":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.entryId&&t.set("entry_id",e.entryId),{path:`/v1/desktop/sessions/${e.sessionId}/children/${e.childId}/transcript?${t}`,method:"GET"}}case"sessions.message":return{path:`/v1/desktop/sessions/${e.sessionId}/messages`,method:"POST",body:{request_id:e.requestId,text:e.text,images:e.images??[],...e.files?.length?{files:e.files}:{},mode:e.mode??"prompt",...e.inputMode?{input_mode:e.inputMode}:{},...e.inputPath?{input_path:e.inputPath}:{}}};case"sessions.command":return{path:`/v1/desktop/sessions/${e.sessionId}/commands`,method:"POST",body:{request_id:e.requestId,command:e.command,args:e.args??"",images:e.images??[]}};case"sessions.profileActionStatus":return{path:`/v1/desktop/sessions/${e.sessionId}/profile-action-status`,method:"POST",body:{action_id:e.actionId,receipt_id:e.receiptId,profile_kind:e.profileKind,profile_name:e.profileName,tool_call_id:e.toolCallId}};case"sessions.answer":return e.askId!==void 0?{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{ask_id:e.askId,answers:e.answers,decline:e.decline,...e.revise===!0?{revise:!0}:{},...e.dismiss===!0?{dismiss:!0,...e.reason!==void 0?{reason:e.reason}:{}}:{}}}:{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{epoch:e.epoch,request_id:e.requestId,value:e.value,approved:e.approved,question_index:e.questionIndex}};case"sessions.seen":return{path:`/v1/desktop/sessions/${e.sessionId}/seen`,method:"POST",body:{completion_token:e.completionToken}};case"attention.seen":return{path:"/v1/desktop/attention/seen",method:"POST",body:{items:e.items.map(t=>({session_id:t.sessionId,completion_token:t.completionToken}))}};case"sessions.notified":return{path:`/v1/desktop/sessions/${e.sessionId}/notified`,method:"POST",body:{completion_token:e.completionToken}};case"tags.list":return{path:"/v1/desktop/tags",method:"GET"};case"tags.replace":return{path:"/v1/desktop/tags",method:"PUT",body:{tags:e.tags}};case"sessions.tags":return{path:`/v1/desktop/sessions/${e.sessionId}/tags`,method:"PUT",body:{tags:e.tags,primary:e.primary,...e.expected_revision===void 0?{}:{expected_revision:e.expected_revision}}};case"sessions.pin":return{path:`/v1/desktop/sessions/${e.sessionId}/pin`,method:"POST",body:{pinned:e.pinned}};case"sessions.watch":return{path:`/v1/desktop/sessions/${e.sessionId}/watch`,method:"POST",body:{subscription_id:e.subscriptionId,visible:e.visible,can_notify:e.canNotify}};case"sessions.presence":return{path:"/v1/desktop/presence",method:"POST",body:{subscription_id:e.subscriptionId,can_notify_kinds:e.canNotifyKinds,session_id:e.sessionId,window:e.window,can_notify:e.canNotify}};case"sessions.move":return{path:`/v1/desktop/sessions/${e.sessionId}/working-directory`,method:"POST",body:{request_id:e.requestId,cwd:e.cwd}};case"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":{Yi(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??{},...Zi(e)}}}case"agent.republish":{Yi(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??{},...Zi(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{Yi(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:Zi(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,...qy(e),message:e.message,...tu(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...tu(e)}};case"wakes.remove":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"DELETE"};case"monitors.cancel":return{path:`/v1/desktop/monitors/${encodeURIComponent(e.sessionId)}/${encodeURIComponent(e.monitorId)}`,method:"DELETE"};case"jobs.cancel":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/jobs/${encodeURIComponent(e.jobId)}/cancel`,method:"POST"};case"legacy.jobs.list":{const t=new URLSearchParams;return e.agentId&&t.set("agent_id",e.agentId),e.status&&t.set("status",e.status),{path:t.size>0?`/v1/jobs?${t}`:"/v1/jobs",method:"GET"}}case"legacy.job.get":return{path:`/v1/jobs/${e.jobId}`,method:"GET"};case"legacy.schedules.list":return{path:`/v1/schedules?${new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)})}`,method:"GET"};case"legacy.agent.schedules.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/schedules?${t}`,method:"GET"}}case"legacy.agent.schedule.create":return{path:`/v1/agents/${e.agentId}/schedules`,method:"POST",body:e.schedule};case"legacy.schedule.get":return{path:`/v1/schedules/${e.scheduleId}`,method:"GET"};case"legacy.schedule.edit":return{path:`/v1/schedules/${e.scheduleId}`,method:"PATCH",body:e.schedule};case"legacy.schedule.remove":return{path:`/v1/schedules/${e.scheduleId}`,method:"DELETE"};case"legacy.agent.create":return{path:"/v1/agents",method:"POST",body:e.agent};case"legacy.agent.update":return{path:`/v1/agents/${e.agentId}`,method:"PATCH",body:e.update};case"legacy.agent.delete":return{path:`/v1/agents/${e.agentId}`,method:"DELETE"};case"legacy.agent.conversation.clear":return{path:`/v1/agents/${e.agentId}/conversation`,method:"DELETE"};case"legacy.agent.systemPrompt.get":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"GET"};case"legacy.agent.systemPrompt.update":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"PUT",body:{system_prompt:e.systemPrompt}};case"legacy.agent.download":return{path:`/v1/agents/${e.agentId}/download`,method:"GET"};case"legacy.job.cancel":return{path:`/v1/jobs/${e.jobId}`,method:"DELETE"};case"commands.list":return{path:"/v1/desktop/commands",method:"GET"};case"commands.entities":return{path:`/v1/desktop/sessions/${e.sessionId}/command-entities?command=${encodeURIComponent(e.command)}${e.name?`&name=${encodeURIComponent(e.name)}`:""}`,method:"GET"};case"models.catalogue":{const t=e.scope?`&scope=${e.scope}`:"";return{path:`/v1/desktop/models?live=${e.live??!1}${t}`,method:"GET"}}case"usage.get":{const t=new URLSearchParams({live:String(e.live??!1),refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),{path:`/v1/desktop/usage?${t}`,method:"GET"}}case"usage.reset":{const t={provider:e.provider,redeem_request_id:e.redeemRequestId};return e.credentialRef&&(t.credential_ref=e.credentialRef),e.identity&&(t.identity=e.identity),{path:"/v1/desktop/usage/reset",method:"POST",body:t}}case"quota.notice":{const t=new URLSearchParams({refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),e.model&&t.set("model",e.model),{path:`/v1/desktop/quota-notice?${t}`,method:"GET"}}case"analytics.get":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics?${t}`,method:"GET"}}case"analytics.models":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics/models?${t}`,method:"GET"}}case"info.get":return{path:"/v1/desktop/info",method:"GET"};case"sessions.report":{const t=new URLSearchParams({recent_limit:String(e.recentLimit??12)});return{path:`/v1/desktop/sessions/${e.sessionId}/report?${t}`,method:"GET"}}case"skills.list":{const t=new URLSearchParams;e.sessionId&&t.set("session_id",e.sessionId),e.cwd&&t.set("cwd",e.cwd),e.name&&t.set("name",e.name);const n=t.toString();return{path:`/v1/desktop/skills${n?`?${n}`:""}`,method:"GET"}}case"skills.create":return{path:"/v1/desktop/skills",method:"POST",body:{request_id:e.requestId,name:e.name,copy_from:e.copyFrom}};case"skills.update":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"PUT",body:{request_id:e.requestId,expected_fingerprint:e.expectedFingerprint,files:e.files}};case"skills.remove":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"DELETE",body:{request_id:e.requestId,discard_local_changes:e.discardLocalChanges}};case"sessions.failovers":return{path:`/v1/desktop/sessions/${e.sessionId}/failovers`,method:"GET"};case"sessions.credential":return{path:`/v1/desktop/sessions/${e.sessionId}/credentials`,method:"POST",body:{action:e.action,key:e.key,value:e.value,confirmed:e.confirmed}};case"sessions.fork":return{path:`/v1/desktop/sessions/${e.sessionId}/fork`,method:"POST",body:{request_id:e.requestId,message:e.message,boundary:e.boundary,entry_id:e.entryId,auto_tag:e.autoTag}};case"sessions.stop":return{path:"/v1/desktop/stop",method:"POST",body:{request_id:e.requestId,targets:e.targets,confirmed:e.confirmed}};case"sessions.aside":return{path:`/v1/desktop/sessions/${e.sessionId}/asides`,method:"POST",body:{request_id:e.requestId,text:e.text,aside_id:e.asideId,subscription_id:e.subscriptionId}};case"sessions.adopt":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}/adopt`,method:"POST",body:{request_id:e.requestId,confirmed:e.confirmed}};case"sessions.aside.get":case"sessions.aside.close":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}`,method:e.op==="sessions.aside.get"?"GET":"DELETE"};case"mcp.list":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"GET"};case"mcp.credentials.store":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp/credentials`,method:"POST",body:{name:e.name,values:e.values,confirmed_replace:e.confirmedReplace}};case"mcp.control":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"POST",body:e.control};case"mcp.catalog":{const t=new URLSearchParams;e.cwd&&t.set("cwd",e.cwd),e.sessionId&&t.set("session_id",e.sessionId);const n=t.toString();return{path:n?`/v1/desktop/mcp?${n}`:"/v1/desktop/mcp",method:"GET"}}case"mcp.catalog.control":return{path:"/v1/desktop/mcp",method:"POST",body:{...e.control,...e.cwd?{cwd:e.cwd}:{}}};case"mcp.catalog.credentials":return{path:"/v1/desktop/mcp/credentials",method:"POST",body:{name:e.name,values:e.values,...e.header?{header:e.header}:{},confirmed_replace:e.confirmedReplace,...e.cwd?{cwd:e.cwd}:{}}};case"radient.request":return{path:"/v1/desktop/radient",method:"POST",body:e.control};case"providers.list":return{path:"/v1/auth/providers",method:"GET"};case"accounts.list":return{path:"/v1/auth/status",method:"GET"};case"accounts.remove":return{path:`/v1/auth/accounts/${e.accountId}`,method:"DELETE"};case"tunnel.setup.read":return{path:e.credentialId===void 0?"/v1/desktop/tunnel/setup":`/v1/desktop/tunnel/setup?credential_id=${e.credentialId}`,method:"GET"};case"tunnel.setup.plan":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"plan",...e.credentialId!==void 0?{credential_id:e.credentialId}:{}}};case"tunnel.setup.run":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"run",credential_id:e.credentialId,...e.acceptMonthlyPrice!==void 0?{accept_monthly_price:e.acceptMonthlyPrice}:{}}};case"auth.start":return{path:"/v1/auth/login",method:"POST",body:{provider:e.provider}};case"auth.status":return{path:`/v1/auth/operations/${e.id}`,method:"GET"};case"auth.input":return{path:`/v1/auth/operations/${e.id}/input`,method:"POST",body:{prompt_id:e.promptId,value:e.value}};case"auth.cancel":return{path:`/v1/auth/operations/${e.id}`,method:"DELETE"};case"auth.key":return{path:`/v1/auth/providers/${e.provider}/key`,method:"PUT",body:{value:e.value}};case"auth.logout":return{path:`/v1/auth/providers/${e.provider}/credentials`,method:"DELETE"};case"agent_messages.status":return{path:`/v1/desktop/team-bridge/status?boundary=${e.boundary}`,method:"GET"};case"agent_messages.enable":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,state:e.state,consent_version:e.consent_version,consented_via:e.consented_via}};case"agent_messages.settings":return{path:`/v1/desktop/team-bridge/settings${ms(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${ms(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)}${ms(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"?"":Qr(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${Qr(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)}${Qr(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)}${Qr(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${ms(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"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}${Qr(e)}`,method:"DELETE"}}case"team_bridge.messages.send":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},client_ref:e.client_ref,body:e.body,...e.agent_label?{agent_label:e.agent_label}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{},...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.files?.length?{files:e.files}:{},...e.mentions?.length?{mentions:e.mentions}:{}}};case"team_bridge.scheduled.list":return{path:`/v1/desktop/team-bridge/scheduled?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"GET"};case"team_bridge.scheduled.create":return{path:"/v1/desktop/team-bridge/scheduled",method:"POST",body:{tenant_id:e.tenant_id,conversation_id:e.conversation_id,client_ref:e.client_ref,body:e.body,send_at:e.send_at,...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{}}};case"team_bridge.scheduled.update":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"PATCH",body:{...e.body===void 0?{}:{body:e.body},...e.send_at===void 0?{}:{send_at:e.send_at},...e.attachment_ids===void 0?{}:{attachment_ids:e.attachment_ids},...e.expected_version===void 0?{}:{expected_version:e.expected_version}}};case"team_bridge.attachments.delete":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/attachments/${encodeURIComponent(e.attachment_id)}?${new URLSearchParams({tenant_id:e.tenant_id,expected_account_id:e.expected_account_id})}`,method:"DELETE"};case"team_bridge.scheduled.cancel":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"DELETE"};case"team_bridge.messages.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit)),e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/replies${n}`,method:"GET"}}case"team_bridge.read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.seq===void 0?{}:{seq:e.seq},...e.muted===void 0?{}:{muted:e.muted}}};case"team_bridge.thread_read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/read`,method:"POST",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,seq:e.seq}};case"team_bridge.unread":{const t=new URLSearchParams;return e.scope==="account"?t.set("scope","account"):e.tenant_id&&t.set("tenant_id",e.tenant_id),{path:`/v1/desktop/team-bridge/unread${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.directory":return{path:`/v1/desktop/team-bridge/directory?tenant_id=${encodeURIComponent(e.tenant_id)}`,method:"GET"};case"team_bridge.status":{const t=new URLSearchParams;return e.boundary&&t.set("boundary",e.boundary),{path:`/v1/desktop/team-bridge/status${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.link_preview.resolve":return{path:"/v1/desktop/team-bridge/link-preview/resolve",method:"POST",body:{url:e.url,index:e.index,expected_account_id:e.expectedAccountId}};case"settings.list":return{path:"/v1/settings",method:"GET"};case"settings.edit":return{path:`/v1/settings/${e.key}`,method:"PATCH",body:{value:e.value,base:e.base}};case"settings.reset":return{path:`/v1/settings/${e.key}/reset`,method:"POST"};case"tts.paths":return{path:"/v1/tts/paths",method:"GET"};case"notification_sounds.list":return{path:"/v1/notification-sounds",method:"GET"};case"notification_sounds.rename":return{path:`/v1/notification-sounds/${e.id}`,method:"PATCH",body:{name:e.name}};case"notification_sounds.remove":return{path:`/v1/notification-sounds/${e.id}`,method:"DELETE"};case"config.get":return{path:"/v1/config",method:"GET"};case"config.update":return{path:"/v1/config",method:"PATCH",body:e.value};case"instructions.get":return{path:"/v1/config/system-prompt",method:"GET"};case"instructions.update":return{path:"/v1/config/system-prompt",method:"PATCH",body:{content:e.content}};case"credentials.list":return{path:"/v1/credentials",method:"GET"};case"credentials.update":return{path:"/v1/credentials",method:"PATCH",body:{key:e.key,value:e.value}};case"library.list":{const t=new URLSearchParams;e.scope&&t.set("scope",e.scope),e.q&&t.set("q",e.q),e.category&&t.set("category",e.category),e.kind&&t.set("kind",e.kind),e.origin_group&&t.set("origin_group",e.origin_group),e.origin&&t.set("origin",e.origin),e.tag&&t.set("tag",e.tag),e.tag_mode&&t.set("tag_mode",e.tag_mode),e.highlighted!==void 0&&t.set("highlighted",e.highlighted?"1":"0"),e.organized!==void 0&&t.set("organized",e.organized?"1":"0"),e.favorite!==void 0&&t.set("favorite",e.favorite?"1":"0"),e.session&&t.set("session",e.session),e.session_id&&t.set("session_id",e.session_id),e.sort&&t.set("sort",e.sort),e.order&&t.set("order",e.order),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);const n=t.toString();return{path:`/v1/desktop/library/assets${n?`?${n}`:""}`,method:"GET"}}case"library.get":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"GET"};case"library.update":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"PATCH",body:e.fields};case"library.tags":return{path:"/v1/desktop/library/tags",method:"GET"};case"library.tags.create":return{path:"/v1/desktop/library/tags",method:"POST",body:{name:e.name,...e.category!==void 0?{category:e.category}:{}}};case"library.tags.update":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"PATCH",body:{...e.name!==void 0?{name:e.name}:{},...e.category!==void 0?{category:e.category}:{}}};case"library.tags.delete":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"DELETE"};case"library.tags.merge":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}/merge`,method:"POST",body:{into:e.into}};case"library.tags.assign":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/tags`,method:"PUT",body:{tags:e.tags,...e.primary!==void 0?{primary:e.primary}:{}}};case"library.chat.link":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"PUT",body:{session_id:e.sessionId}};case"library.chat.clear":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"DELETE"};case"library.librarian":{const t=e.action??"status";return t==="status"?{path:"/v1/desktop/librarian",method:"GET"}:{path:"/v1/desktop/librarian",method:"POST",body:{op:t}}}case"projects.list":return{path:"/v1/desktop/projects",method:"GET"};case"projects.get":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"GET"};case"projects.create":return{path:"/v1/desktop/projects",method:"POST",body:{name:e.name,...e.description!==void 0?{description:e.description}:{},...e.status!==void 0?{status:e.status}:{},...e.tags!==void 0?{tags:e.tags}:{}}};case"projects.update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"PATCH",body:{...e.fields,...e.force_done===!0?{force_done:!0}:{}}};case"projects.delete":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"DELETE",body:{confirm:e.confirmed_name}};case"projects.link":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links`,method:"POST",body:{session_id:e.sessionId}};case"projects.unlink":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links/${encodeURIComponent(e.sessionId)}`,method:"DELETE"};case"projects.milestone":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones`,method:"POST",body:{name:e.name,...e.targetDate!==void 0?{target_date:e.targetDate}:{},...e.completed!==void 0?{completed:e.completed}:{}}};case"projects.milestone.remove":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones/${encodeURIComponent(e.name)}`,method:"DELETE"};case"projects.request_update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/request-update`,method:"POST"};case"projects.search":return{path:`/v1/desktop/projects/search?${new URLSearchParams({q:e.q,limit:String(e.limit??cy)})}`,method:"GET"};case"aida.status":return{path:"/v1/desktop/aida",method:"GET"};case"aida.control":return{path:"/v1/desktop/aida",method:"POST",body:{op:e.action}};case"code_requests.list":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests`,method:"GET"};case"code_requests.refresh":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests/refresh`,method:"POST",body:{...e.keys!==void 0?{keys:e.keys}:{},...e.force!==void 0?{force:e.force}:{}}};case"static.sign":return{path:"/v1/static/sign",method:"POST",body:{route:e.route,path:e.path,ttl_s:e.ttlS}};case"sidebar_layout.get":return{path:"/v1/desktop/sidebar-layout",method:"GET"};case"sidebar_layout.set":return{path:"/v1/desktop/sidebar-layout",method:"PUT",body:{layout:e.layout}};case"notifications.list":{const t=new URLSearchParams;e.preview&&t.set("preview","true"),e.includeAskReads&&t.set("include_ask_reads","true");for(const n of e.countSessionIds??[])t.append("count_session_ids",n);return e.kind&&t.set("kind",e.kind),e.bulkPriority&&t.set("bulk_priority",e.bulkPriority),e.state&&t.set("state",e.state),e.source&&t.set("source",e.source),e.priority&&t.set("priority",e.priority),e.sessionId&&t.set("session_id",e.sessionId),e.cursor&&t.set("cursor",e.cursor),e.throughSeq!==void 0&&t.set("through_seq",String(e.throughSeq)),e.limit!==void 0&&t.set("limit",String(e.limit)),{path:`/v1/desktop/notifications${t.size?`?${t}`:""}`,method:"GET"}}case"notifications.get":return{path:`/v1/desktop/notifications/${encodeURIComponent(e.id)}`,method:"GET"};case"notifications.count":return{path:"/v1/desktop/notifications/count",method:"GET"};case"notifications.read":case"notifications.dismiss":return{path:"/v1/desktop/notifications",method:"PATCH",body:{op:e.verb,...tw(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:py[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function tw(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 xP=64,TP=64*1024*1024,CP="superseded_completion_token",OP="store_busy",nw="session_is_remote",rw="owner_build_behind";function PP(e,t,n){if(!e||typeof e!="object")return!1;const r=e;return r.unseen===!1&&r.conversation_id===`session/${t}`&&r.completion_token===n}function Ar(e,t,n){return!t||t.conversation_id!==`session/${n}`||!Array.isArray(t.revision)||t.revision.length!==2||!t.revision.every(r=>Number.isSafeInteger(r)&&r>=0)||e?.conversation_id===t.conversation_id&&(t.revision[0]<e.revision[0]||t.revision[1]<e.revision[1])?e:t.supported===void 0&&e?.supported!==void 0?{...t,supported:e.supported}:t}function ow(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const MP=e=>typeof e?.goal_status=="string",jP=e=>(e?.goal??"").trim().length>0;function sw(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function iw(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 go={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 aw(e){return e?e===go.notPaired?"notPaired":e===go.serverDown?"serverDown":e===go.frameBudget?"frameTooLarge":"lost":"lost"}const cw=/^[a-f0-9]{12}$/,lw=/^[a-zA-Z0-9_-]{1,128}$/,dw=()=>performance.timeOrigin+performance.now();function uw(e){e&&(e.rendererEntryEpochMs=dw())}function Gc(e,t){e&&(e.delivery=t,e.deliveryAt=performance.now())}function fw(e,t,n,r){const o=a=>a===void 0?"-":a.toFixed(3),s=(a,c)=>a===void 0||c===void 0?void 0:a-c;return["[snapshot-receipt]",`openToken=${t??"-"}`,`session=${cw.test(e.sessionId)?e.sessionId:"?"}`,`streamId=${lw.test(e.streamId)?e.streamId:"?"}`,"kind=snapshot",`chars=${e.chars}`,`mainRecordEpochMs=${o(e.mainRecordEpochMs)}`,`mainFoldMs=${o(e.mainFoldMs)}`,`mainObserverMs=${o(e.mainObserverMs)}`,`mainEmitMs=${o(e.mainEmitMs)}`,`mainSendEpochMs=${o(e.mainSendEpochMs)}`,`ipcApproxMs=${o(s(e.preloadReceiptEpochMs,e.mainSendEpochMs))}`,`preloadReceiptEpochMs=${o(e.preloadReceiptEpochMs)}`,`preloadReadyMs=${o(e.preloadReadyMs)}`,`bridgeApproxMs=${o(s(e.rendererEntryEpochMs,e.preloadReceiptEpochMs===void 0||e.preloadReadyMs===void 0?void 0:e.preloadReceiptEpochMs+e.preloadReadyMs))}`,`rendererEntryEpochMs=${o(e.rendererEntryEpochMs)}`,`delivery=${e.delivery??"-"}`,`bufferMs=${o(s(e.deliveryAt,e.bufferedAt))}`,`deliveryToParseMs=${o(s(n,e.deliveryAt))}`,`parseMs=${o(r-n)}`].join(" ")}const ru=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const h=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(m=>m(t,h))}},o=()=>t,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d))},l=t=e(r,o,c);return c},pw=e=>e?ru(e):ru,hw=e=>e;function mw(e,t=hw){const n=od.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return od.useDebugValue(n),n}const ou=e=>{const t=pw(e),n=r=>mw(t,r);return Object.assign(n,t),n},Qo=e=>e?ou(e):ou;function Lp(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var s;const a=l=>l===null?null:JSON.parse(l,void 0),c=(s=n.getItem(o))!=null?s:null;return c instanceof Promise?c.then(a):a(c)},setItem:(o,s)=>n.setItem(o,JSON.stringify(s,void 0)),removeItem:o=>n.removeItem(o)}}const Ba=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Ba(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Ba(r)(n)}}}},gw=(e,t)=>(n,r,o)=>{let s={storage:Lp(()=>localStorage),partialize:b=>b,version:0,merge:(b,v)=>({...v,...b}),...t},a=!1;const c=new Set,l=new Set;let d=s.storage;if(!d)return e((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),n(...b)},r,o);const u=()=>{const b=s.partialize({...r()});return d.setItem(s.name,{state:b,version:s.version})},f=o.setState;o.setState=(b,v)=>{f(b,v),u()};const h=e((...b)=>{n(...b),u()},r,o);o.getInitialState=()=>h;let m;const y=()=>{var b,v;if(!d)return;a=!1,c.forEach(A=>{var k;return A((k=r())!=null?k:h)});const p=((v=s.onRehydrateStorage)==null?void 0:v.call(s,(b=r())!=null?b:h))||void 0;return Ba(d.getItem.bind(d))(s.name).then(A=>{if(A)if(typeof A.version=="number"&&A.version!==s.version){if(s.migrate){const k=s.migrate(A.state,A.version);return k instanceof Promise?k.then(C=>[!0,C]):[!0,k]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,A.state];return[!1,void 0]}).then(A=>{var k;const[C,L]=A;if(m=s.merge(L,(k=r())!=null?k:h),n(m,!0),C)return u()}).then(()=>{p?.(m,void 0),m=r(),a=!0,l.forEach(A=>A(m))}).catch(A=>{p?.(void 0,A)})};return o.persist={setOptions:b=>{s={...s,...b},b.storage&&(d=b.storage)},clearStorage:()=>{d?.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>y(),hasHydrated:()=>a,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(l.add(b),()=>{l.delete(b)})},s.skipHydration||y(),m||h},_i=gw,_w=(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 bw(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.message!="string"||t.message.trim()==="")return null;const n=(r,o)=>typeof r=="number"&&Number.isFinite(r)?r:o;return{message:t.message,removed:n(t.removed,0),max_age_hours:n(t.max_age_hours,48),in_progress:t.in_progress===!0,first_removal_at:typeof t.first_removal_at=="string"?t.first_removal_at:"",freed_bytes_estimate:typeof t.freed_bytes_estimate=="number"&&Number.isFinite(t.freed_bytes_estimate)?t.freed_bytes_estimate:null,record:typeof t.record=="string"?t.record:""}}const Fp=Qo()(_i(e=>({notice:null,receive:t=>e(n=>_w(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:Lp(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function Xn(e){return _(ky[e])}let Ha=null;function vw(e){if(e===null){Ha=null;return}Ha={openFrame:e.openFrame===!0,journalOrder:e.journalOrder===!0,peerJournalSource:e.peerJournalSource===!0}}function Up(){return Ha}const su=()=>_("ui.common.errors.desktop_backend_offline"),yw=()=>_("ui.common.errors.desktop_backend_compatibility");async function Bp(e){if(window.api?.desktop)try{return await ww(window.api.desktop.request(e),e)}catch(n){throw n instanceof xe?n:Rw(n)?new mn(Dp,Np):new xe(null,su(),n)}let t;try{t=await fetch("/__desktop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(n){throw new xe(null,su(),n)}if(!t.ok)throw new xe(t.status,yw());return t.json()}function ww(e,t){const n=$p(t);let r;return Promise.race([e,new Promise((o,s)=>{r=setTimeout(()=>{const a=Xy(t.op,n);s(new xe(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const Hp="This server did not answer the request for its desktop controls.",kw=()=>_("ui.common.errors.desktop_refusal_placeholder");class xe extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,o,s,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=o,this.retryAfterMs=s,this.detail=a}}class mn extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function zc(e){return e instanceof xe||e instanceof mn?e.code===He.serverUpdating?!0:e instanceof xe&&gy(e.detail):!1}function $P(e){return e instanceof xe&&_y(e.detail)}function Kc(e,t){return zc(e)?Xn(He.serverUpdating):e instanceof xe||e instanceof mn?gi(e.code)?Xn(e.code):e.message===Hp?kw():e.message:t}function Sw(e,t,n,r){return r===Cp&&t===503?He.serverUpdating:typeof r=="string"?r:n===Tp&&t===503?He.serverUpdating:n===Ua.noCredential?He.noCredential:n===Ua.transportFailed?He.transportFailed:Sy(ew(e).path,t)}async function Qe(e){const t=await Bp(e),n=t.body;if(t.status<200||t.status>=300){const r=typeof n?.detail=="string"?n.detail:typeof n?.detail?.text=="string"?n.detail.text:typeof n?.detail?.message=="string"?n.detail.message:null;throw new xe(t.status,r??Hp,void 0,Sw(e,t.status,r,typeof n?.detail=="object"?n.detail?.code:void 0),typeof n?.detail=="object"&&typeof n.detail?.retry_after_ms=="number"&&Number.isFinite(n.detail.retry_after_ms)?n.detail.retry_after_ms:void 0,typeof n?.detail=="object"?n.detail:void 0)}return e.op==="sessions.list"&&Ew(n?.result),n?.result}function Ew(e){if(typeof e!="object"||e===null)return;const t=bw(e.delegated_cleanup_notice);t&&Fp.getState().receive(t)}async function Aw(){try{await Qe({op:"delegated_cleanup_notice.ack"})}catch{}}async function NP(){Fp.getState().dismiss(),await Aw()}function Iw(e){return e instanceof xe&&e.code===Wc}function DP(e){if(!(e instanceof xe))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===rw:e.code===nw}function LP(e){return e instanceof mn&&e.code===Np}function Rw(e){return e instanceof Error&&e.message.includes(Dp)}async function FP(e){const t=await Bp(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function UP(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await Qe({op:"auth.status",id:e});if(!n.auth_url)throw new Error("This sign-in is no longer waiting for a browser.");const r=new URL(n.auth_url);if(r.username||r.password||r.protocol!=="https:"&&!(r.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(r.hostname)))throw new Error("The provider returned an invalid sign-in address.");window.open(r.href,"_blank","noopener,noreferrer")}function xw(e,t,n){const r=Ow(e);return r.record?(n?.("adopted"),iu(e.sessionId,"adopted","none",Wa(e),null),jw(r.record,t)):(Gt&&un(),n?.("requested"),iu(e.sessionId,"requested",r.refusal,Wa(e),r.held),Wp(e,t))}const Tw=6e4,Cw=512;function Wa(e){return{openFrame:e.openFrame===!0,journalOrder:e.journalOrder===!0,peerJournalSource:e.peerJournalSource===!0}}let Gt=null,qn=null;function un(){qn!==null&&(clearTimeout(qn),qn=null);const e=Gt;Gt=null,e&&(e.live=null,e.buffered=[],e.disposeTransport())}function BP(){return Gt?.sessionId??null}function HP(e){!e||Gt?.sessionId!==e||un()}function WP(e,t){if(!e||Gt?.sessionId===e)return;un();const n=Up(),r={openFrame:n?.openFrame===!0,journalOrder:n?.journalOrder===!0,peerJournalSource:n?.peerJournalSource===!0&&t?.remoteOwned===!0};let o=!1;const s={sessionId:e,negotiation:r,buffered:[],live:null,ended:!1,disposeTransport:()=>{}};if(s.disposeTransport=Wp({sessionId:e,...r.openFrame?{openFrame:!0}:{},...r.journalOrder?{journalOrder:!0}:{},...r.peerJournalSource?{peerJournalSource:!0}:{}},c=>{if(s.live){Gc(c.receipt,"live"),s.live(c);return}if(c.kind==="error"||c.kind==="end"){s.ended=!0,o=!0,un();return}if(s.buffered.length>=Cw){o=!0,un();return}c.receipt&&(c.receipt.bufferedAt=performance.now()),s.buffered.push(c)}),o){s.disposeTransport();return}Gt=s;const a=setTimeout(()=>{Gt===s&&un()},Tw);typeof a.unref=="function"&&a.unref(),qn=a}function Ow(e){const t=Gt;if(!t)return{record:null,refusal:"none",held:null};if(t.ended)return un(),{record:null,refusal:"ended",held:t.negotiation};if(t.sessionId!==e.sessionId)return{record:null,refusal:"other-session",held:null};const n=Wa(e);return e.epoch!==void 0||e.afterSeq!==void 0||(e.orderIds?.length??0)>0?(un(),{record:null,refusal:"resuming",held:t.negotiation}):n.openFrame!==t.negotiation.openFrame||n.journalOrder!==t.negotiation.journalOrder||n.peerJournalSource!==t.negotiation.peerJournalSource?(un(),{record:null,refusal:"negotiation",held:t.negotiation}):{record:t,refusal:null,held:t.negotiation}}const Pw=/^[A-Za-z0-9_-]{1,80}$/,Mw="[stream-prewarm]";function iu(e,t,n,r,o){if(t==="requested"&&n==="none")return;const s=Pw.test(e)?e:"?",a=l=>[l.openFrame?"1":"0",l.journalOrder?"1":"0",l.peerJournalSource?"1":"0"].join(","),c=[Mw,`session=${s}`,`decision=${t}`];t==="requested"&&(c.push(`why=${n}`,`asked=${a(r)}`),o&&c.push(`prewarm=${a(o)}`),n==="negotiation"&&c.push(`caps=${Up()?"recorded":"absent"}`)),console.warn(c.join(" "))}function jw(e,t){const n=e.buffered;e.buffered=[],e.live=t,qn!==null&&(clearTimeout(qn),qn=null),Gt===e&&(Gt=null);let r=!1;return queueMicrotask(()=>{if(!r)for(const o of n)Gc(o.receipt,"replay"),t(o)}),()=>{r||(r=!0,e.live=null,e.disposeTransport())}}function Wp(e,t){const n=window.api?.desktop?.stream;if(n){const s=n.subscribe(e,a=>{const c=a.receipt?{...a,receipt:{...a.receipt}}:a;uw(c.receipt),Gc(c.receipt,"direct"),t(c)});return()=>s.dispose()}const r=new URLSearchParams({session:e.sessionId});e.epoch&&r.set("epoch",e.epoch),e.afterSeq!==void 0&&r.set("after_seq",String(e.afterSeq)),r.set("frontend_replace","1"),e.openFrame===!0&&r.set("open_frame","1"),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),Vs(r,"/__desktop/stream",e.orderIds??[]));const o=new EventSource(`/__desktop/stream?${r}`);return o.onmessage=s=>{t({kind:"data",data:s.data})},o.onerror=()=>{o.readyState===EventSource.CLOSED&&(t({kind:"error",detail:go.ended}),o.close())},()=>{o.close(),t({kind:"end"})}}async function GP(e,t){const n=window.api?.desktop?.media;if(n)return n(e,t);const r=await fetch("/__desktop/media",{method:"POST",headers:{"x-desktop-media":JSON.stringify(e),"Content-Type":"application/octet-stream"},body:t?new Blob([t]):void 0}),o=r.headers.get("content-type")??"";if(!r.ok){let s="The media request failed.",a,c;if(o.includes("application/json"))try{const l=await r.json();my(r.status,l)&&(a=He.serverUpdating);const d=l?.detail;if(typeof d=="string")s=d;else if(typeof d=="object"&&d!==null){const u=d;typeof u.text=="string"&&u.text.trim()?s=u.text:typeof u.message=="string"&&u.message.trim()&&(s=u.message),typeof u.code=="string"&&a===void 0&&(a=u.code);const f=d.params;typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}}catch{}return{status:r.status,kind:"error",detail:s,code:a!==void 0&&gi(a)?a:s===Ua.noCredential?He.noCredential:void 0,...e.op==="notification_sounds.upload"&&a!==void 0?{refusal:{code:a.slice(0,64),...c?{params:c}:{}}}:{}}}return o.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:o||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function zP(e){return e.kind==="error"?gi(e.code)?new mn(Xn(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function $w(e){if(zc(e))return"updating";if(Iw(e))return"deadline";const t=e instanceof xe?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const Gp={updating:"",unreachable:"",deadline:"",unauthorized:"",get outdated(){return _("ui.common.connection.backend.remedy_outdated")},unknown:""},Os={get updating(){return Xn(He.serverUpdating)},get unreachable(){return _("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return _("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return _("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return _("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function Nw(e,t){const n=$w(t);return[e,Os[n],Gp[n]].filter(Boolean).join(" ")}const Ga={get successor(){return _("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return _("ui.common.connection.backend.pairing_unpaired")}},Dw={get successor(){return _("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return _("ui.common.connection.backend.pane_unpaired")}};function KP(e,t){return e!=="unpaired"?null:Dw[t??"unpaired"]}function VP(e,t){return e!=="unpaired"?null:Ga[t??"unpaired"]}function ZP(e){const{kind:t,unpaired:n,answered:r,cause:o=null,servedByThisApp:s=!1}=e;return o==="pre-handshake"?s:o!==null||n?!1:r?s:t==="outdated"}function YP(e){const{kind:t,unpaired:n,missing:r,answered:o,cause:s=null}=e;if(s!==null)return Ga[s];if(!o){if(t==="updating")return Os.updating;if(t==="unreachable")return _("ui.common.connection.backend.compatibility_unreachable",{diagnosis:Os.unreachable});if(t==="unauthorized")return _("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return _("ui.common.connection.backend.compatibility_deadline",{diagnosis:Os.deadline});if(t==="outdated")return _("ui.common.connection.backend.compatibility_outdated",{remedy:Gp.outdated})}return n?Ga.unpaired:o?_("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):_("ui.common.connection.backend.compatibility_unknown")}const Lw=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function JP(e,t=null){return t!==null||!e?!0:Lw.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function Fw(e,t){return t instanceof xe&&t.status===null?!1:e<1}function QP(e,t){return t instanceof xe&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const Uw={get successor(){return _("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.card_credential_refused")},get unpaired(){return _("ui.common.connection.backend.card_unpaired")}};function XP(e,t,n){return e===null?{sentence:Nw(t,n),remedy:!0}:{sentence:Uw[e],remedy:hp(e)}}const zp={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]},Bw=3e4,Hw=15e3;function Ww(e){return e?.desktop_available===!0}function qP(){const{client:e,provided:t}=J_();return pp({enabled:t,queryKey:zp.capabilities,queryFn:async()=>{try{const n=await Qe({op:"capabilities"});return vw(zw(n)),n}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>Ww(n.state.data)?Bw:Hw,refetchIntervalInBackground:!0},e)}function Gw(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function Ji(e,t,n=1){return Gw(e,t,n)==="enabled"}function zw(e){return{openFrame:Ji(e,"open_frame"),journalOrder:Ji(e,"journal_order"),peerJournalSource:Ji(e,"peer_journal_source")}}function eM(e){return pp({queryKey:zp.providers,queryFn:()=>Qe({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:Fw})}let bi=!1,Ys=!1;const Js=[];function tM(){typeof window>"u"||!window.__loDevDriver?.armed||(bi=!0,Ys=!1,Js.length=0)}function Kw(){return bi}function Vw(e){if(bi)try{if(Js.length>=256){Ys=!0;return}Js.push({carrier:e.carrier,sessionId:e.sessionId,epoch:typeof e.epoch=="string"?e.epoch:null,seq:typeof e.seq=="number"?e.seq:null,disposition:e.disposition})}catch{Ys=!0}}function nM(){return{armed:bi,fault:Ys,receipts:Js.map(e=>({...e}))}}const Xr=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function Zw(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=Xr(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=Xr(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>Xr(d)===c);l===-1?r.push(a):r[l]=a}if(!t.order)return r;const o=new Map;for(const a of r){const c=Xr(a);c!==null&&o.set(c,a)}const s=[];for(const a of t.order){const c=String(a),l=o.get(c);l&&(s.push(l),o.delete(c))}for(const a of r){const c=Xr(a);c!==null&&o.has(c)?(s.push(a),o.delete(c)):c===null&&s.push(a)}return s}const za=e=>({revision:xt(e),demand:e.orderDemand}),er=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Lr(e,t,n,r,o,s={}){let a=e;const c=t.journal_generation;if(t.reconcile===!0){const h=typeof c=="string"&&c.length>0?c:void 0;return a.orderNeedsReconcile&&a.orderWantedGeneration===h?a.journalMode?a:{...a,journalMode:!0}:{...a,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:h,orderDemand:h!==void 0?{generation:h}:{}}}if(typeof c!="string"||c.length===0)return t.journal_order_state&&t.journal_order_state!=="unsupported"&&!a.journalMode?{...a,journalMode:!0}:a;if(r&&t.journal_order_state==="ready"&&o&&a.orderNeedsReconcile&&a.orderDemand===o.demand&&(a={...a,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),c!==a.journalGeneration&&!r)return a.orderNeedsReconcile&&a.orderWantedGeneration===c?a:{...a,orderNeedsReconcile:!0,orderWantedGeneration:c,orderDemand:{generation:c}};let l=a.journalMode?a:{...a,journalMode:!0};if(c!==a.journalGeneration&&(l={...a,journalMode:!0,journalGeneration:c,orderRevision:(a.orderRevision??0)+1,journalPositions:new Map,orderNeedsReconcile:a.orderNeedsReconcile,orderWantedGeneration:a.orderWantedGeneration,orderDemand:a.orderDemand},s.peer===!0)){const h=(a.orderRevision??0)+1,m=new Map;for(const y of a.records){const b=y.sourceEntryId??(y.kind==="tool"||y.kind==="supplement"?null:y.id);typeof b=="string"&&b.length>0&&b.length<=128&&m.set(b,h)}l={...l,...m.size>0?{journalBodyOwed:m}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(h,m,y)=>{if(!er(y))return;const b=d.get(h);b&&b.seq>=y||(d===u&&(d=new Map(d)),d.set(h,{entryId:m,seq:y}))};for(const[h,m]of Object.entries(t.journal_ordinals??{}))f(h,h,m);for(const h of n)typeof h.id=="string"&&(f(h.id,h.id,h.journal_seq),h.role==="tool"&&typeof h.tool_call_id=="string"&&f(`tool:${h.tool_call_id}`,h.id,h.journal_seq),typeof h.anchor=="string"&&f(`supplement:${h.anchor}`,h.id,h.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function Vc(e,t){if(!e.journalMode||typeof t.id!="string"||!Array.isArray(t.tool_calls))return e;let n=e.journalCallOwners??new Map,r=e.journalCallSlots??new Map;const o=n,s=r;return t.tool_calls.forEach((a,c)=>{!a||typeof a.id!="string"||(n.get(a.id)!==t.id&&(n===o&&(n=new Map(n)),n.set(a.id,t.id)),r.get(a.id)!==c&&(r===s&&(r=new Map(r)),r.set(a.id,c)))}),n===o&&r===s?e:{...e,journalCallOwners:n,journalCallSlots:r}}function Kp(e,t){const n=new Set(e.map(s=>s.id));let r=!1,o;for(let s=0;s<e.length;s++){const a=e[s];if(a.kind==="user"&&a.provisional===!0){o=a;continue}if(a.sourcePrecedes!==void 0){if(a.sourceAdmissionAnchor!==void 0){const{sourceAdmissionAnchor:c,...l}=a;e[s]=l,r=!0}o=e[s];continue}!t(a)&&o&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[s]={...a,sourceAdmissionAnchor:o.id},r=!0),o=e[s]}return r}function Vp(e,t,n,r,o){const s=[],a=new Set;let c=e,l;for(;c!==void 0;){if(o.has(c.id)){l=o.get(c.id);break}if(n(c)){l=r(c);break}if(c.kind==="user"&&c.provisional===!0||a.has(c.id))break;a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of s)o.set(d,l);return l}const Yw=Number.MAX_SAFE_INTEGER;function Jw(e,t){const n=new Map,r=new Map,o=new Map;for(const s of e){if(s.sourcePrecedes===void 0)continue;const a=t(s);if(a!==void 0)r.set(s.sourcePrecedes,a);else{const c=r.get(s.sourcePrecedes);c!==void 0&&n.set(s.id,{seq:c,slot:Yw})}}for(let s=e.length-1;s>=0;s--){const a=e[s];if(a.sourcePrecedes===void 0)continue;const c=t(a);if(c!==void 0)o.set(a.sourcePrecedes,c);else if(!n.has(a.id)){const l=o.get(a.sourcePrecedes);l!==void 0&&n.set(a.id,{seq:l,slot:-1})}}return n}function Zp(e,t){return{floor:Qw(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:Jw(e,t)}}function Yp(e,t,n,r){if(r===void 0||e.sourcePrecedes===void 0)return;const o=r.page.get(e.id);if(o!==void 0)return o;const s=new Set;let a=1,c=t.get(e.sourcePrecedes);for(;c!==void 0&&!s.has(c.id);){s.add(c.id);const l=n(c);if(l!==void 0)return{seq:l,slot:-a};const d=r.page.get(c.id);if(d!==void 0)return{seq:d.seq,slot:d.slot-a};a+=1,c=c.sourcePrecedes?t.get(c.sourcePrecedes):void 0}return r.floor===void 0?void 0:{seq:r.floor,slot:-a}}function Jp(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:r}=n,o=new Set;let s=1,a=t.get(e.sourcePrecedes);for(;a!==void 0&&!o.has(a.id);){if(a.sourcePrecedes===void 0){const c=r.get(a.id);return c===void 0?void 0:{slot:c,depth:s}}o.add(a.id),s+=1,a=t.get(a.sourcePrecedes)}}function Qw(e,t){let n;for(const r of e){if(r.sourcePrecedes!==void 0)continue;const o=t(r);o!==void 0&&(n===void 0||o<n)&&(n=o)}return n}function Qp(e,t){const n=new Map;return r=>{if(!r)return;const o=t(r);if(o===void 0)return;const s=[],a=new Set;let c=r,l=!0;for(;c;){if(n.has(c.id)){l=n.get(c.id)===!0;break}if(a.has(c.id)||t(c)===void 0){l=!1;break}a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of s)n.set(d,l);return l?o:void 0}}function Qs(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const o=new Map;t.forEach((a,c)=>{if(a.kind!=="tool")return;const l=n.get(a.toolCallId);if(l===void 0||!r.has(a.toolCallId))return;const d=o.get(l);d?d.push(c):o.set(l,[c])});let s=t;for(const a of o.values()){if(a.length<2)continue;const c=a.map(l=>t[l]).sort((l,d)=>(r.get(l.toolCallId)??0)-(r.get(d.toolCallId)??0));c.every((l,d)=>l===t[a[d]])||(s===t&&(s=t.slice()),a.forEach((l,d)=>{s[l]=c[d]}))}return s}function Xp(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return Xw(e,t);const n=e.journalGeneration,r=e.journalPositions;let o=!1,s=!1;const a=t.map(b=>{b.sourcePrecedes!==void 0&&(s=!0);let p=[r?.get(b.sourceEntryId??b.id),r?.get(b.id)].filter(C=>C!==void 0).sort((C,L)=>L.seq-C.seq)[0];if(b.journalGeneration===n&&er(b.journalSeq)&&(!p||b.journalSeq>p.seq)&&(p={entryId:b.sourceEntryId??b.id,seq:b.journalSeq}),!p||!n||!(b.kind==="user"&&(b.provisional===!0||b.local===!0))&&b.sourceEntryId===p.entryId&&b.journalSeq===p.seq&&b.journalGeneration===n)return b;o=!0;let k={...b,sourceEntryId:p.entryId,journalSeq:p.seq,journalGeneration:n};if(k.kind==="user"){const{provisional:C,local:L,...O}=k;k=O}return k});Kp(a,b=>b.journalGeneration===n&&er(b.journalSeq))&&(o=!0);const l=new Map,d=new Map(a.map(b=>[b.id,b])),u=Qp(d,b=>b!==void 0&&b.journalGeneration===n&&er(b.journalSeq)?b.journalSeq:void 0),f=b=>u(b)!==void 0,h=s?Zp(a,u):void 0,m=(b,v)=>{const p=u(b);if(b.kind==="user"&&b.provisional===!0&&p===void 0)return[1,0,0,0,v];const A=b.kind==="supplement"?b.anchor:b.kind==="tool"?e.journalCallOwners?.get(b.toolCallId)??e.argsByCall.get(b.toolCallId)?.anchorId:void 0,k=typeof A=="string"?u(d.get(A)):void 0,C=k===void 0&&p===void 0?Yp(b,d,u,h):void 0,L=p===void 0&&C===void 0?Vp(b,d,f,u,l):void 0,O=k??p??C?.seq??L;if(O===void 0){const I=Jp(b,d,h);return[1,I?.slot??v,I?-I.depth:0,0,v]}return[0,O,k!==void 0?1:p!==void 0?0:C!==void 0?C.slot:2,p??Number.MAX_SAFE_INTEGER,v]},y=a.map((b,v)=>({record:b,index:v,rank:m(b,v)}));return y.sort((b,v)=>{for(let p=0;p<b.rank.length;p++){const A=b.rank[p]-v.rank[p];if(A)return A}return 0}),!o&&y.every((b,v)=>b.index===v)?Qs(e,t):Qs(e,y.map(b=>b.record))}function Xw(e,t){const n=e.journalGeneration,r=e.journalPositions,o=new Map;let s=!1;for(const p of t){p.sourcePrecedes!==void 0&&(s=!0);let k=[r?.get(p.sourceEntryId??p.id),r?.get(p.id)].filter(C=>C!==void 0).sort((C,L)=>L.seq-C.seq)[0];p.journalGeneration===n&&er(p.journalSeq)&&(!k||p.journalSeq>k.seq)&&(k={entryId:p.sourceEntryId??p.id,seq:p.journalSeq}),k&&o.set(p.id,k)}const a=p=>p===void 0?void 0:o.get(p.id)??r?.get(p.sourceEntryId??p.id)??r?.get(p.id);let c=!1;const l=t.slice();Kp(l,p=>p.journalGeneration===n&&er(p.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(p=>[p.id,p])),h=Qp(f,p=>a(p)?.seq),m=p=>h(p)!==void 0,y=s?Zp(l,h):void 0,b=(p,A)=>{const k=h(p);if(p.kind==="user"&&p.provisional===!0&&k===void 0)return[1,0,0,0,A];const C=p.kind==="supplement"?p.anchor:p.kind==="tool"?e.journalCallOwners?.get(p.toolCallId)??e.argsByCall.get(p.toolCallId)?.anchorId:void 0,L=typeof C=="string"?h(f.get(C)):void 0,O=L===void 0&&k===void 0?Yp(p,f,h,y):void 0,I=k===void 0&&O===void 0?Vp(p,f,m,h,u):void 0,g=L??k??O?.seq??I;if(g===void 0){const w=Jp(p,f,y);return[1,w?.slot??A,w?-w.depth:0,0,A]}return[0,g,L!==void 0?1:k!==void 0?0:O!==void 0?O.slot:2,k??Number.MAX_SAFE_INTEGER,A]},v=l.map((p,A)=>({record:p,index:A,rank:b(p,A)}));return v.sort((p,A)=>{for(let k=0;k<p.rank.length;k++){const C=p.rank[k]-A.rank[k];if(C)return C}return 0}),!c&&v.every((p,A)=>p.index===A)?Qs(e,t):Qs(e,v.map(p=>p.record))}function Zt(e){const t=e.records.filter(o=>o.kind==="user"&&o.provisional===!0),n=e.records.filter(o=>o.journalGeneration!==e.journalGeneration||!er(o.journalSeq)),r=[...t,...n].map(o=>o.sourceEntryId??(o.kind==="tool"||o.kind==="supplement"?null:o.id));if(r.push(...Zc(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let o=r.length-1;o>=0;o--){const s=r[o];typeof s=="string"&&e.journalSourceVoid.has(s)&&r.splice(o,1)}return[...new Set(r.filter(o=>typeof o=="string"&&o.length>0&&o.length<=128))]}function Zc(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const o=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof o=="string"&&o.length>0&&o.length<=128&&t.add(o)}const n=[];for(const r of e.journalBodyOwed.keys())r.length<1||r.length>128||t.has(r)&&(e.journalSourceVoid?.has(r)||n.push(r));return n}function qp(e,t){const n=e.journalPositions;return Zt(e).filter(r=>!n?.has(r)&&!t?.has(r))}const xt=e=>e.orderRevision??0;async function qw(e){const t=new Map,n=c=>{let l=t.get(c);return l||(l=new Set,t.set(c,l)),l},r=(c,l)=>l==="payload"?Zc(c):l==="lookup"?qp(c):Zt(c);let o=e.getTranscript().journalGeneration,s=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=za(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",h=gv(r(c,f).filter(v=>!n(f).has(v)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),m=await e.read(h,f);if(!e.isCurrent()||xt(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(m,d,l),!e.isCurrent())return{kind:"stale"};const y=e.getTranscript(),b=e.page(m);if(b.journal_order_state==="ready"&&b.journal_generation===y.journalGeneration){b.journal_generation!==o&&(t.clear(),o=b.journal_generation);for(const A of h)n(f).add(A);if(y.orderNeedsReconcile){if(y.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear();continue}if(f==="payload"){const A=(b.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 v=e.sweep?.(y,n);if(v?.kind==="none")return{kind:"complete",transcript:y};const p=v?.kind??"authority";if(r(y,p).some(A=>!n(p).has(A)))continue;return{kind:"complete",transcript:y}}if(!y.orderNeedsReconcile||y.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear()}}function Dt(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const o=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof o=="string"&&o?o:e.id}function Qi(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function au(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function rM(e){if(!e||e.runs_state!=="ready")return null;const t=e.runs;if(!t||t.length===0)return null;const n=new Map;for(const s of t){if(!s.settled||typeof s.run_key!="string"||s.run_key.length===0)continue;const a=Qi(s.action_count);if(a===null)continue;const c={actions:a,workedSeconds:au(s.worked_seconds),failed:Qi(s.failed_count)??0,complete:s.complete!==!1,openingUserId:typeof s.opening_user_id=="string"&&s.opening_user_id.length>0?s.opening_user_id:null,closingAnswerId:typeof s.closing_answer_id=="string"&&s.closing_answer_id.length>0?s.closing_answer_id:null,crossSessionActions:Qi(s.cross_session_action_count),crossSessionWorkedSeconds:au(s.cross_session_worked_seconds)};n.set(s.run_key,c),c.openingUserId!==null&&n.set(c.openingUserId,c),c.closingAnswerId!==null&&n.set(c.closingAnswerId,c)}if(n.size===0)return null;const r=new Set;for(const s of e.entries)r.add(Dt(s));const o=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:o?Dt(o):null}}}function e0(e){if(!e||e.runs_state!=="ready"||e.head_cut===!0)return null;const t=e.runs,n=e.entries[0];if(!n||!t||t.length===0||!t.find(s=>s.opening_user_id===n.id))return null;const o=Math.round((n.ts??0)*1e3);return o>0?{id:n.id,tsMs:o}:null}function t0(e,t,n){const r=e0(e),o=e?.entries;if(r===null||!o||o.length===0)return!1;const s=Math.round((o[o.length-1].ts??0)*1e3);if(!(s>r.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>r.tsMs)||!(c<s)))return!1;return!0}const Yc=new Set,Dn="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Jc=new RegExp(`[${Dn}]`),n0=new RegExp(`[${Dn}]+`),oM=new RegExp(`[${Dn}]+`,"g"),r0=new RegExp(`^[${Dn}]+|[${Dn}]+$`,"g"),o0=new RegExp(`^[${Dn}]+`),sM=new RegExp(`[^${Dn}]`);function qt(e){return e.replace(r0,"")}function Do(e){return e.replace(o0,"")}function eh(e,t){return t===0||Jc.test(e[t-1])}function th(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&eh(e,n)&&t.push(n);return t}function Qc(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
1
+ import{r as R,j as i_,b as sd,D as a_,l as Pc,m as np,n as Mc,o as c_}from"./index-kEyWW56d.js";import{c as nn,t as _,a as l_}from"./messages-CUhxkxii.js";import{P as d_,i as jc,a as $c,p as rp}from"./roles-D1pcbxAx.js";const id=new Map,ad=new Map,cd=new Map,ld=new Map;function Nc(e){return e===void 0?"":JSON.stringify(e)}function Dc(e,t){const n=`${e}\0${Nc(t)}`;let r=id.get(n);return r===void 0&&(r=new Intl.DateTimeFormat(e,t),id.set(n,r)),r}function u_(e,t){const n=`${e}\0${Nc(t)}`;let r=ad.get(n);return r===void 0&&(r=new Intl.NumberFormat(e,t),ad.set(n,r)),r}function JO(e,t,n){return Dc(n??nn(),t).format(e)}function QO(e,t,n){return Dc(n??nn(),t).format(e)}function XO(e,t,n){return Dc(n??nn(),t).format(e)}function f_(e,t,n){return u_(n??nn(),t).format(e)}function qO(e,t,n,r){const o=r??nn(),s=`${o}\0${Nc(n)}`;let a=cd.get(s);return a===void 0&&(a=new Intl.RelativeTimeFormat(o,n),cd.set(s,a)),a.format(e,t)}const p_={B:"byte",KB:"kilobyte",MB:"megabyte",GB:"gigabyte",TB:"terabyte",PB:"petabyte"},dd=new Map,ud=new Map;function h_(e){return e.split("-")[0]?.toLowerCase()==="en"}function m_(e,t){if(e==="KiB"||e==="MiB"||e==="GiB"||h_(t))return e;const n=`${t}\0${e}`;let r=dd.get(n);if(r===void 0){r=e;try{r=new Intl.NumberFormat(t,{style:"unit",unit:p_[e],unitDisplay:"narrow"}).formatToParts(1).find(s=>s.type==="unit")?.value??e}catch{}dd.set(n,r)}return r}function g_(e){let t=ud.get(e);if(t===void 0){t=" ";try{t=new Intl.NumberFormat(e,{style:"unit",unit:"kilobyte",unitDisplay:"short"}).formatToParts(1).find(r=>r.type==="literal")?.value??" "}catch{}ud.set(e,t)}return t}function mo(e,t,n,r){const o=nn();return`${f_(e,{useGrouping:!1,...n},o)}${g_(o)}${m_(t,o)}`}function Ts(e,t){const n=nn();let r=ld.get(n);return r===void 0&&(r=new Intl.ListFormat(n,{type:"conjunction",style:"narrow"}),ld.set(n,r)),r.format(e)}const __={zh:";",ja:";",ur:"؛ ",ar:"؛ "};function eP(e,t){const n=nn().split("-")[0]?.toLowerCase();return e.join(__[n??""]??"; ")}var Yo=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(){}},sr=typeof window>"u"||"Deno"in globalThis;function Ot(){}function b_(e,t){return typeof e=="function"?e(t):e}function Ra(e){return typeof e=="number"&&e>=0&&e!==1/0}function op(e,t){return Math.max(e+(t||0)-Date.now(),0)}function xr(e,t){return typeof e=="function"?e(t):e}function Ut(e,t){return typeof e=="function"?e(t):e}function fd(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:s,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==Lc(a,t.options))return!1}else if(!So(t.queryKey,a))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||o&&o!==t.state.fetchStatus||s&&!s(t))}function pd(e,t){const{exact:n,status:r,predicate:o,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(ko(t.options.mutationKey)!==ko(s))return!1}else if(!So(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Lc(e,t){return(t?.queryKeyHashFn||ko)(e)}function ko(e){return JSON.stringify(e,(t,n)=>Ta(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function So(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>So(e[n],t[n])):!1}function sp(e,t){if(e===t)return e;const n=hd(e)&&hd(t);if(n||Ta(e)&&Ta(t)){const r=n?e:Object.keys(e),o=r.length,s=n?t:Object.keys(t),a=s.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:s[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=sp(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return o===a&&l===o?e:c}return t}function xa(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 hd(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ta(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 v_(e){return new Promise(t=>{setTimeout(t,e)})}function Ca(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?sp(e,t):t}function y_(e){return e}function w_(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function k_(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Fc=Symbol();function ip(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Fc?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var S_=class extends Yo{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!sr&&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"}},Uc=new S_,E_=class extends Yo{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!sr&&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}},Fs=new E_;function Oa(){let e,t;const n=new Promise((o,s)=>{e=o,t=s});n.status="pending",n.catch(()=>{});function r(o){Object.assign(n,o),delete n.resolve,delete n.reject}return n.resolve=o=>{r({status:"fulfilled",value:o}),e(o)},n.reject=o=>{r({status:"rejected",reason:o}),t(o)},n}function A_(e){return Math.min(1e3*2**e,3e4)}function ap(e){return(e??"online")==="online"?Fs.isOnline():!0}var cp=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Li(e){return e instanceof cp}function lp(e){let t=!1,n=0,r=!1,o;const s=Oa(),a=b=>{r||(h(new cp(b)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>Uc.isFocused()&&(e.networkMode==="always"||Fs.isOnline())&&e.canRun(),u=()=>ap(e.networkMode)&&e.canRun(),f=b=>{r||(r=!0,e.onSuccess?.(b),o?.(),s.resolve(b))},h=b=>{r||(r=!0,e.onError?.(b),o?.(),s.reject(b))},m=()=>new Promise(b=>{o=v=>{(r||d())&&b(v)},e.onPause?.()}).then(()=>{o=void 0,r||e.onContinue?.()}),y=()=>{if(r)return;let b;const v=n===0?e.initialPromise:void 0;try{b=v??e.fn()}catch(p){b=Promise.reject(p)}Promise.resolve(b).then(f).catch(p=>{if(r)return;const A=e.retry??(sr?0:3),k=e.retryDelay??A_,T=typeof k=="function"?k(n,p):k,F=A===!0||typeof A=="number"&&n<A||typeof A=="function"&&A(n,p);if(t||!F){h(p);return}n++,e.onFail?.(n,p),v_(T).then(()=>d()?void 0:m()).then(()=>{t?h(p):y()})})};return{promise:s,cancel:a,continue:()=>(o?.(),s),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?y():m().then(y),s)}}var I_=e=>setTimeout(e,0);function R_(){let e=[],t=0,n=c=>{c()},r=c=>{c()},o=I_;const s=c=>{t?e.push(c):o(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&o(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{s(()=>{c(...l)})},schedule:s,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{o=c}}}var rt=R_(),dp=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ra(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(sr?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},x_=class extends dp{#t;#e;#n;#r;#o;#a;#i;constructor(e){super(),this.#i=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=T_(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#o?.promise}setOptions(e){this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const n=Ca(this.state.data,e,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#s({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#o?.promise;return this.#o?.cancel(e),t?t.then(Ot).catch(Ot):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>Ut(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Fc||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||!op(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#o?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#o?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#o&&(this.#i?this.#o.cancel({revert:!0}):this.#o.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#o)return this.#o.continueRetry(),this.#o.promise}if(e&&this.setOptions(e),!this.options.queryFn){const c=this.observers.find(l=>l.options.queryFn);c&&this.setOptions(c.options)}const n=new AbortController,r=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},o=()=>{const c=ip(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(l),this.#i=!1,this.options.persister?this.options.persister(c,l,this):c(l)},s={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:o};r(s),this.options.behavior?.onFetch(s,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#s({type:"fetch",meta:s.fetchOptions?.meta});const a=c=>{Li(c)&&c.silent||this.#s({type:"error",error:c}),Li(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#o=lp({initialPromise:t?.initialPromise,fn:s.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){a(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){a(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:a,onFail:(c,l)=>{this.#s({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0}),this.#o.start()}#s(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...up(n.data,this.options),fetchMeta:e.meta??null};case"success":return{...n,data:e.data,dataUpdateCount:n.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const r=e.error;return Li(r)&&r.revert&&this.#e?{...this.#e,fetchStatus:"idle"}:{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),rt.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function up(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ap(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function T_(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var C_=class extends Yo{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,o=t.queryHash??Lc(r,t);let s=this.get(o);return s||(s=new x_({client:e,queryKey:r,queryHash:o,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(s)),s}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){rt.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#t.get(e)}getAll(){return[...this.#t.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>fd(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>fd(e,n)):t}notify(e){rt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){rt.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){rt.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},O_=class extends dp{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||P_(),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=lp({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(r,o)=>{this.#r({type:"failed",failureCount:r,error:o})},onPause:()=>{this.#r({type:"pause"})},onContinue:()=>{this.#r({type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#e.canRun(this)});const t=this.state.status==="pending",n=!this.#n.canStart();try{if(!t){this.#r({type:"pending",variables:e,isPaused:n}),await this.#e.config.onMutate?.(e,this);const o=await this.options.onMutate?.(e);o!==this.state.context&&this.#r({type:"pending",context:o,variables:e,isPaused:n})}const r=await this.#n.start();return await this.#e.config.onSuccess?.(r,e,this.state.context,this),await this.options.onSuccess?.(r,e,this.state.context),await this.#e.config.onSettled?.(r,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(r,null,e,this.state.context),this.#r({type:"success",data:r}),r}catch(r){try{throw await this.#e.config.onError?.(r,e,this.state.context,this),await this.options.onError?.(r,e,this.state.context),await this.#e.config.onSettled?.(void 0,r,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,r,e,this.state.context),r}finally{this.#r({type:"error",error:r})}}finally{this.#e.runNext(this)}}#r(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),rt.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#e.notify({mutation:this,type:"updated",action:e})})}};function P_(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var M_=class extends Yo{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#e=new Map,this.#n=0}#t;#e;#n;build(e,t,n){const r=new O_({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=as(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=as(e);if(typeof t=="string"){const n=this.#e.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#e.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=as(e);if(typeof t=="string"){const r=this.#e.get(t)?.find(o=>o.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=as(e);return typeof t=="string"?this.#e.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){rt.batch(()=>{this.#t.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#t.clear(),this.#e.clear()})}getAll(){return Array.from(this.#t)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>pd(t,n))}findAll(e={}){return this.getAll().filter(t=>pd(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(Ot))))}};function as(e){return e.options.scope?.id}function gd(e){return{onFetch:(t,n)=>{const r=t.options,o=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},h=ip(t.options,t.fetchOptions),m=async(y,b,v)=>{if(u)return Promise.reject();if(b==null&&y.pages.length)return Promise.resolve(y);const p={client:t.client,queryKey:t.queryKey,pageParam:b,direction:v?"backward":"forward",meta:t.options.meta};f(p);const A=await h(p),{maxPages:k}=t.options,T=v?k_:w_;return{pages:T(y.pages,A,k),pageParams:T(y.pageParams,b,k)}};if(o&&s.length){const y=o==="backward",b=y?fp:Pa,v={pages:s,pageParams:a},p=b(r,v);c=await m(v,p,y)}else{const y=e??s.length;do{const b=l===0?a[0]??r.initialPageParam:Pa(r,c);if(l>0&&b==null)break;c=await m(c,b),l++}while(l<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function Pa(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function fp(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function tP(e,t){return t?Pa(e,t)!=null:!1}function nP(e,t){return!t||!e.getPreviousPageParam?!1:fp(e,t)!=null}var j_=class{#t;#e;#n;#r;#o;#a;#i;#s;constructor(e={}){this.#t=e.queryCache||new C_,this.#e=e.mutationCache||new M_,this.#n=e.defaultOptions||{},this.#r=new Map,this.#o=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#i=Uc.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#s=Fs.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#i?.(),this.#i=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#t.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(xr(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=this.#t.get(r.queryHash)?.state.data,a=b_(t,s);if(a!==void 0)return this.#t.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return rt.batch(()=>this.#t.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;rt.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return rt.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=rt.batch(()=>this.#t.findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Ot).catch(Ot)}invalidateQueries(e,t={}){return rt.batch(()=>(this.#t.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=rt.batch(()=>this.#t.findAll(e).filter(o=>!o.isDisabled()).map(o=>{let s=o.fetch(void 0,n);return n.throwOnError||(s=s.catch(Ot)),o.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(Ot)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(xr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Ot).catch(Ot)}fetchInfiniteQuery(e){return e.behavior=gd(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Ot).catch(Ot)}ensureInfiniteQueryData(e){return e.behavior=gd(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Fs.isOnline()?this.#e.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#t}getMutationCache(){return this.#e}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(ko(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{So(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#o.set(ko(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(r=>{So(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Lc(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===Fc&&(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()}},$_=class extends Yo{constructor(e,t){super(),this.options=t,this.#t=e,this.#s=null,this.#i=Oa(),this.options.experimental_prefetchInRender||this.#i.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#r=void 0;#o;#a;#i;#s;#m;#f;#p;#l;#d;#c;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),_d(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ma(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ma(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#y(),this.#w(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,n=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ut(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#k(),this.#e.setOptions(this.options),t._defaulted&&!xa(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&bd(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||Ut(this.options.enabled,this.#e)!==Ut(t.enabled,this.#e)||xr(this.options.staleTime,this.#e)!==xr(t.staleTime,this.#e))&&this.#g();const o=this.#_();r&&(this.#e!==n||Ut(this.options.enabled,this.#e)!==Ut(t.enabled,this.#e)||o!==this.#c)&&this.#b(o)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return D_(this,n)&&(this.#r=n,this.#a=this.options,this.#o=this.#e.state),n}getCurrentResult(){return this.#r}trackResult(e,t){const n={};return Object.keys(e).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(r),t?.(r),e[r])})}),n}trackProp(e){this.#h.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),n=this.#t.getQueryCache().build(this.#t,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#u({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#u(e){this.#k();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Ot)),t}#g(){this.#y();const e=xr(this.options.staleTime,this.#e);if(sr||this.#r.isStale||!Ra(e))return;const n=op(this.#r.dataUpdatedAt,e)+1;this.#l=setTimeout(()=>{this.#r.isStale||this.updateResult()},n)}#_(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#b(e){this.#w(),this.#c=e,!(sr||Ut(this.options.enabled,this.#e)===!1||!Ra(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||Uc.isFocused())&&this.#u()},this.#c))}#v(){this.#g(),this.#b(this.#_())}#y(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){this.#d&&(clearInterval(this.#d),this.#d=void 0)}createResult(e,t){const n=this.#e,r=this.options,o=this.#r,s=this.#o,a=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,h;if(t._optimisticResults){const g=this.hasListeners(),w=!g&&_d(e,t),S=g&&bd(e,n,t,r);(w||S)&&(u={...u,...up(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:b}=u;h=u.data;let v=!1;if(t.placeholderData!==void 0&&h===void 0&&b==="pending"){let g;o?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(g=o.data,v=!0):g=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,g!==void 0&&(b="success",h=Ca(o?.data,g,t),f=!0)}if(t.select&&h!==void 0&&!v)if(o&&h===s?.data&&t.select===this.#m)h=this.#f;else try{this.#m=t.select,h=t.select(h),h=Ca(o?.data,h,t),this.#f=h,this.#s=null}catch(g){this.#s=g}this.#s&&(m=this.#s,h=this.#f,y=Date.now(),b="error");const p=u.fetchStatus==="fetching",A=b==="pending",k=b==="error",T=A&&p,F=h!==void 0,I={status:b,fetchStatus:u.fetchStatus,isPending:A,isSuccess:b==="success",isError:k,isInitialLoading:T,isLoading:T,data:h,dataUpdatedAt:u.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:p,isRefetching:p&&!A,isLoadingError:k&&!F,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:k&&F,isStale:Bc(e,t),refetch:this.refetch,promise:this.#i};if(this.options.experimental_prefetchInRender){const g=x=>{I.status==="error"?x.reject(I.error):I.data!==void 0&&x.resolve(I.data)},w=()=>{const x=this.#i=I.promise=Oa();g(x)},S=this.#i;switch(S.status){case"pending":e.queryHash===n.queryHash&&g(S);break;case"fulfilled":(I.status==="error"||I.data!==S.value)&&w();break;case"rejected":(I.status!=="error"||I.error!==S.reason)&&w();break}}return I}updateResult(){const e=this.#r,t=this.createResult(this.#e,this.options);if(this.#o=this.#e.state,this.#a=this.options,this.#o.data!==void 0&&(this.#p=this.#e),xa(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,o=typeof r=="function"?r():r;if(o==="all"||!o&&!this.#h.size)return!0;const s=new Set(o??this.#h);return this.options.throwOnError&&s.add("error"),Object.keys(this.#r).some(a=>{const c=a;return this.#r[c]!==e[c]&&s.has(c)})};this.#S({listeners:n()})}#k(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#S(e){rt.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function N_(e,t){return Ut(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function _d(e,t){return N_(e,t)||e.state.data!==void 0&&Ma(e,t,t.refetchOnMount)}function Ma(e,t,n){if(Ut(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Bc(e,t)}return!1}function bd(e,t,n,r){return(e!==t||Ut(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Bc(e,n)}function Bc(e,t){return Ut(t.enabled,e)!==!1&&e.isStaleByTime(xr(t.staleTime,e))}function D_(e,t){return!xa(e.getCurrentResult(),t)}var Hc=R.createContext(void 0),L_=e=>{const t=R.useContext(Hc);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},rP=({client:e,children:t})=>(R.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),i_.jsx(Hc.Provider,{value:e,children:t})),pp=R.createContext(!1),F_=()=>R.useContext(pp);pp.Provider;function U_(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var B_=R.createContext(U_()),H_=()=>R.useContext(B_);function W_(e,t){return typeof e=="function"?e(...t):!!e}function vd(){}var G_=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},z_=e=>{R.useEffect(()=>{e.clearReset()},[e])},K_=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(o&&e.data===void 0||W_(n,[e.error,r])),V_=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)))},Z_=(e,t)=>e.isLoading&&e.isFetching&&!t,Y_=(e,t)=>e?.suspense&&t.isPending,yd=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function J_(e,t,n){const r=L_(n),o=F_(),s=H_(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=o?"isRestoring":"optimistic",V_(a),G_(a,s),z_(s);const c=!r.getQueryCache().get(a.queryHash),[l]=R.useState(()=>new t(r,a)),d=l.getOptimisticResult(a),u=!o&&e.subscribed!==!1;if(R.useSyncExternalStore(R.useCallback(f=>{const h=u?l.subscribe(rt.batchCalls(f)):vd;return l.updateResult(),h},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),R.useEffect(()=>{l.setOptions(a)},[a,l]),Y_(a,d))throw yd(a,l,s);if(K_({result:d,errorResetBoundary:s,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw d.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!sr&&Z_(d,o)&&(c?yd(a,l,s):r.getQueryCache().get(a.queryHash)?.promise)?.catch(vd).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function hp(e,t){return J_(e,$_,t)}const Q_=()=>{const e=R.useContext(Hc)??null,t=R.useMemo(()=>new j_({defaultOptions:{queries:{enabled:!1,retry:!1,gcTime:0}}}),[]);return R.useEffect(()=>{if(!e)return()=>t.clear()},[e,t]),R.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function oP(e){return e!=="detached"&&e!=="wedged"}function mp(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function sP(e){if(!e)return{title:"Not connected to a Local Operator server.",detail:null,retry:!0};const t=e.addressSubstitution??null;if(t&&e.state!=="detached"&&e.state!=="wedged")return t.kind==="substituted"?{title:`Serving on ${t.serving}, not the address this app is configured for.`,detail:t.holder?`${t.holder}. The app uses ${t.serving} while that holds.${t.reclaim?` ${t.reclaim}`:""} It is back on ${t.configured} on its next launch or recovery.`:`The daemon this app is using was already running, so it did not start one. It looks for ${t.configured} again on its next launch or recovery.`,retry:!0}:{title:`Back on ${t.configured}, the address this app is configured for.`,detail:`It served on ${t.serving} while the configured address was held; it is on the address it was told to use again.`,retry:!1,dismiss:!0};const n=e.detail?.trim()?e.detail.trim():null,r=mp(e.pairing?.cause??null);switch(e.state){case"wedged":return{title:"A Local Operator server is running on this machine and this app is not attached to it.",detail:n,retry:r};case"detached":return e.reconnecting?{title:r?"Not connected to a Local Operator server. If one is still running, the app reconnects to it on its own.":"Not connected to a Local Operator server.",detail:n,retry:r}:{title:r?"The Local Operator server stopped. The app keeps looking for one and attaches to it when it appears.":"Not connected to a Local Operator server. The app keeps looking for one.",detail:n,retry:r};default:return null}}var be;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(const c of s)a[c]=o[c];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(be||(be={}));var ja;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(ja||(ja={}));const H=be.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ln=e=>{switch(typeof e){case"undefined":return H.undefined;case"string":return H.string;case"number":return isNaN(e)?H.nan:H.number;case"boolean":return H.boolean;case"function":return H.function;case"bigint":return H.bigint;case"symbol":return H.symbol;case"object":return Array.isArray(e)?H.array:e===null?H.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?H.promise:typeof Map<"u"&&e instanceof Map?H.map:typeof Set<"u"&&e instanceof Set?H.set:typeof Date<"u"&&e instanceof Date?H.date:H.object;default:return H.unknown}},$=be.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),X_=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class At extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){const d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return o(this),r}static assert(t){if(!(t instanceof At))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,be.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}At.create=e=>new At(e);const $r=(e,t)=>{let n;switch(e.code){case $.invalid_type:e.received===H.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case $.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,be.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:n=`Unrecognized key(s) in object: ${be.joinValues(e.keys,", ")}`;break;case $.invalid_union:n="Invalid input";break;case $.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${be.joinValues(e.options)}`;break;case $.invalid_enum_value:n=`Invalid enum value. Expected ${be.joinValues(e.options)}, received '${e.received}'`;break;case $.invalid_arguments:n="Invalid function arguments";break;case $.invalid_return_type:n="Invalid function return type";break;case $.invalid_date:n="Invalid date";break;case $.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:be.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case $.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 $.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 $.custom:n="Invalid input";break;case $.invalid_intersection_types:n="Intersection results could not be merged";break;case $.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case $.not_finite:n="Number must be finite";break;default:n=t.defaultError,be.assertNever(e)}return{message:n}};let gp=$r;function q_(e){gp=e}function Us(){return gp}const Bs=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="";const l=r.filter(d=>!!d).slice().reverse();for(const d of l)c=d(a,{data:t,defaultError:c}).message;return{...o,path:s,message:c}},eb=[];function U(e,t){const n=Us(),r=Bs({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===$r?void 0:$r].filter(o=>!!o)});e.common.issues.push(r)}class dt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return q;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const s=await o.key,a=await o.value;r.push({key:s,value:a})}return dt.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return q;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}}const q=Object.freeze({status:"aborted"}),Er=e=>({status:"dirty",value:e}),ut=e=>({status:"valid",value:e}),$a=e=>e.status==="aborted",Na=e=>e.status==="dirty",ir=e=>e.status==="valid",Eo=e=>typeof Promise<"u"&&e instanceof Promise;function Hs(e,t,n,r){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function _p(e,t,n,r,o){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var V;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(V||(V={}));var ao,co;class en{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const wd=(e,t)=>{if(ir(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 At(e.common.issues);return this._error=n,this._error}}};function ce(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,c)=>{var l,d;const{message:u}=e;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??r)!==null&&l!==void 0?l:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??n)!==null&&d!==void 0?d:c.defaultError}},description:o}}class le{get description(){return this._def.description}_getType(t){return ln(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ln(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new dt,ctx:{common:t.parent.common,data:t.data,parsedType:ln(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Eo(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n?.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ln(t)},s=this._parseSync({data:t,path:o.path,parent:o});return wd(o,s)}"~validate"(t){var n,r;const o={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ln(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:o});return ir(s)?{value:s.value}:{issues:o.common.issues}}catch(s){!((r=(n=s?.message)===null||n===void 0?void 0:n.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),o.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:o}).then(s=>ir(s)?{value:s.value}:{issues:o.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ln(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Eo(o)?o:Promise.resolve(o));return wd(r,s)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{const a=t(o),c=()=>s.addIssue({code:$.custom,...r(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new zt({schema:this,typeName:X.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Xt.create(this,this._def)}nullable(){return Nn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Wt.create(this)}promise(){return Dr.create(this,this._def)}or(t){return xo.create([this,t],this._def)}and(t){return To.create(this,t,this._def)}transform(t){return new zt({...ce(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new jo({...ce(this._def),innerType:this,defaultValue:n,typeName:X.ZodDefault})}brand(){return new Wc({typeName:X.ZodBranded,type:this,...ce(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new $o({...ce(this._def),innerType:this,catchValue:n,typeName:X.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Jo.create(this,t)}readonly(){return No.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const tb=/^c[^\s-]{8,}$/i,nb=/^[0-9a-z]+$/,rb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ob=/^[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,sb=/^[a-z0-9_-]{21}$/i,ib=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ab=/^[-+]?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)?)??$/,cb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Fi;const db=/^(?:(?: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])$/,ub=/^(?:(?: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])$/,fb=/^(([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]))$/,pb=/^(([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])$/,hb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,bp="((\\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])))",gb=new RegExp(`^${bp}$`);function vp(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 _b(e){return new RegExp(`^${vp(e)}$`)}function yp(e){let t=`${bp}T${vp(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 bb(e,t){return!!((t==="v4"||!t)&&db.test(e)||(t==="v6"||!t)&&fb.test(e))}function vb(e,t){if(!ib.test(e))return!1;try{const[n]=e.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||!o.typ||!o.alg||t&&o.alg!==t)}catch{return!1}}function yb(e,t){return!!((t==="v4"||!t)&&ub.test(e)||(t==="v6"||!t)&&pb.test(e))}class Ht extends le{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==H.string){const s=this._getOrReturnCtx(t);return U(s,{code:$.invalid_type,expected:H.string,received:s.parsedType}),q}const r=new dt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,c=t.data.length<s.value;(a||c)&&(o=this._getOrReturnCtx(t,o),a?U(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&U(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")cb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"email",code:$.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Fi||(Fi=new RegExp(lb,"u")),Fi.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"emoji",code:$.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")ob.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"uuid",code:$.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")sb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"nanoid",code:$.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")tb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid",code:$.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")nb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid2",code:$.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")rb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ulid",code:$.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),U(o,{validation:"url",code:$.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"regex",code:$.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),U(o,{code:$.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:$.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:$.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?yp(s).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:$.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?gb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:$.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?_b(s).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:$.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?ab.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"duration",code:$.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?bb(t.data,s.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ip",code:$.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?vb(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"jwt",code:$.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?yb(t.data,s.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cidr",code:$.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?hb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64",code:$.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?mb.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64url",code:$.invalid_string,message:s.message}),r.dirty()):be.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:$.invalid_string,...V.errToObj(r)})}_addCheck(t){return new Ht({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...V.errToObj(t)})}url(t){return this._addCheck({kind:"url",...V.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...V.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...V.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...V.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...V.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...V.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...V.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...V.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...V.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...V.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...V.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...V.errToObj(t)})}datetime(t){var n,r;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(n=t?.offset)!==null&&n!==void 0?n:!1,local:(r=t?.local)!==null&&r!==void 0?r:!1,...V.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...V.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...V.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...V.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...V.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...V.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...V.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...V.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...V.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...V.errToObj(n)})}nonempty(t){return this.min(1,V.errToObj(t))}trim(){return new Ht({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ht({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ht({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}Ht.create=e=>{var t;return new Ht({checks:[],typeName:X.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};function wb(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=parseInt(e.toFixed(o).replace(".","")),a=parseInt(t.toFixed(o).replace(".",""));return s%a/Math.pow(10,o)}class Mn extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==H.number){const s=this._getOrReturnCtx(t);return U(s,{code:$.invalid_type,expected:H.number,received:s.parsedType}),q}let r;const o=new dt;for(const s of this._def.checks)s.kind==="int"?be.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:$.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:$.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:$.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?wb(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),U(r,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:$.not_finite,message:s.message}),o.dirty()):be.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,V.toString(n))}gt(t,n){return this.setLimit("min",t,!1,V.toString(n))}lte(t,n){return this.setLimit("max",t,!0,V.toString(n))}lt(t,n){return this.setLimit("max",t,!1,V.toString(n))}setLimit(t,n,r,o){return new Mn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:V.toString(o)}]})}_addCheck(t){return new Mn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:V.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:V.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:V.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:V.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:V.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:V.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:V.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:V.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:V.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&be.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}}Mn.create=e=>new Mn({checks:[],typeName:X.ZodNumber,coerce:e?.coerce||!1,...ce(e)});class jn extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==H.bigint)return this._getInvalidInput(t);let r;const o=new dt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:$.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:$.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),U(r,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):be.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return U(n,{code:$.invalid_type,expected:H.bigint,received:n.parsedType}),q}gte(t,n){return this.setLimit("min",t,!0,V.toString(n))}gt(t,n){return this.setLimit("min",t,!1,V.toString(n))}lte(t,n){return this.setLimit("max",t,!0,V.toString(n))}lt(t,n){return this.setLimit("max",t,!1,V.toString(n))}setLimit(t,n,r,o){return new jn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:V.toString(o)}]})}_addCheck(t){return new jn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:V.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:V.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:V.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:V.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:V.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}jn.create=e=>{var t;return new jn({checks:[],typeName:X.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};class Ao extends le{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==H.boolean){const r=this._getOrReturnCtx(t);return U(r,{code:$.invalid_type,expected:H.boolean,received:r.parsedType}),q}return ut(t.data)}}Ao.create=e=>new Ao({typeName:X.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});class ar extends le{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==H.date){const s=this._getOrReturnCtx(t);return U(s,{code:$.invalid_type,expected:H.date,received:s.parsedType}),q}if(isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return U(s,{code:$.invalid_date}),q}const r=new dt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:$.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:$.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):be.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new ar({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:V.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:V.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}}ar.create=e=>new ar({checks:[],coerce:e?.coerce||!1,typeName:X.ZodDate,...ce(e)});class Ws extends le{_parse(t){if(this._getType(t)!==H.symbol){const r=this._getOrReturnCtx(t);return U(r,{code:$.invalid_type,expected:H.symbol,received:r.parsedType}),q}return ut(t.data)}}Ws.create=e=>new Ws({typeName:X.ZodSymbol,...ce(e)});class Io extends le{_parse(t){if(this._getType(t)!==H.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:$.invalid_type,expected:H.undefined,received:r.parsedType}),q}return ut(t.data)}}Io.create=e=>new Io({typeName:X.ZodUndefined,...ce(e)});class Ro extends le{_parse(t){if(this._getType(t)!==H.null){const r=this._getOrReturnCtx(t);return U(r,{code:$.invalid_type,expected:H.null,received:r.parsedType}),q}return ut(t.data)}}Ro.create=e=>new Ro({typeName:X.ZodNull,...ce(e)});class Nr extends le{constructor(){super(...arguments),this._any=!0}_parse(t){return ut(t.data)}}Nr.create=e=>new Nr({typeName:X.ZodAny,...ce(e)});class Qn extends le{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ut(t.data)}}Qn.create=e=>new Qn({typeName:X.ZodUnknown,...ce(e)});class hn extends le{_parse(t){const n=this._getOrReturnCtx(t);return U(n,{code:$.invalid_type,expected:H.never,received:n.parsedType}),q}}hn.create=e=>new hn({typeName:X.ZodNever,...ce(e)});class Gs extends le{_parse(t){if(this._getType(t)!==H.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:$.invalid_type,expected:H.void,received:r.parsedType}),q}return ut(t.data)}}Gs.create=e=>new Gs({typeName:X.ZodVoid,...ce(e)});class Wt extends le{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==H.array)return U(n,{code:$.invalid_type,expected:H.array,received:n.parsedType}),q;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,c=n.data.length<o.exactLength.value;(a||c)&&(U(n,{code:a?$.too_big:$.too_small,minimum:c?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(U(n,{code:$.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(U(n,{code:$.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>o.type._parseAsync(new en(n,a,n.path,c)))).then(a=>dt.mergeArray(r,a));const s=[...n.data].map((a,c)=>o.type._parseSync(new en(n,a,n.path,c)));return dt.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new Wt({...this._def,minLength:{value:t,message:V.toString(n)}})}max(t,n){return new Wt({...this._def,maxLength:{value:t,message:V.toString(n)}})}length(t,n){return new Wt({...this._def,exactLength:{value:t,message:V.toString(n)}})}nonempty(t){return this.min(1,t)}}Wt.create=(e,t)=>new Wt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...ce(t)});function br(e){if(e instanceof Fe){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Xt.create(br(r))}return new Fe({...e._def,shape:()=>t})}else return e instanceof Wt?new Wt({...e._def,type:br(e.element)}):e instanceof Xt?Xt.create(br(e.unwrap())):e instanceof Nn?Nn.create(br(e.unwrap())):e instanceof tn?tn.create(e.items.map(t=>br(t))):e}class Fe extends le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=be.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==H.object){const d=this._getOrReturnCtx(t);return U(d,{code:$.invalid_type,expected:H.object,received:d.parsedType}),q}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof hn&&this._def.unknownKeys==="strip"))for(const d in o.data)a.includes(d)||c.push(d);const l=[];for(const d of a){const u=s[d],f=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new en(o,f,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof hn){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(d==="strict")c.length>0&&(U(o,{code:$.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const u of c){const f=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new en(o,f,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of l){const f=await u.key,h=await u.value;d.push({key:f,value:h,alwaysSet:u.alwaysSet})}return d}).then(d=>dt.mergeObjectSync(r,d)):dt.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return V.errToObj,new Fe({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,s,a,c;const l=(a=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=V.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new Fe({...this._def,unknownKeys:"strip"})}passthrough(){return new Fe({...this._def,unknownKeys:"passthrough"})}extend(t){return new Fe({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Fe({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:X.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Fe({...this._def,catchall:t})}pick(t){const n={};return be.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Fe({...this._def,shape:()=>n})}omit(t){const n={};return be.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Fe({...this._def,shape:()=>n})}deepPartial(){return br(this)}partial(t){const n={};return be.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Fe({...this._def,shape:()=>n})}required(t){const n={};return be.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Xt;)s=s._def.innerType;n[r]=s}}),new Fe({...this._def,shape:()=>n})}keyof(){return wp(be.objectKeys(this.shape))}}Fe.create=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strip",catchall:hn.create(),typeName:X.ZodObject,...ce(t)});Fe.strictCreate=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strict",catchall:hn.create(),typeName:X.ZodObject,...ce(t)});Fe.lazycreate=(e,t)=>new Fe({shape:e,unknownKeys:"strip",catchall:hn.create(),typeName:X.ZodObject,...ce(t)});class xo extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const a=s.map(c=>new At(c.ctx.common.issues));return U(n,{code:$.invalid_union,unionErrors:a}),q}if(n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of r){const d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const c=a.map(l=>new At(l));return U(n,{code:$.invalid_union,unionErrors:c}),q}}get options(){return this._def.options}}xo.create=(e,t)=>new xo({options:e,typeName:X.ZodUnion,...ce(t)});const sn=e=>e instanceof Oo?sn(e.schema):e instanceof zt?sn(e.innerType()):e instanceof Po?[e.value]:e instanceof $n?e.options:e instanceof Mo?be.objectValues(e.enum):e instanceof jo?sn(e._def.innerType):e instanceof Io?[void 0]:e instanceof Ro?[null]:e instanceof Xt?[void 0,...sn(e.unwrap())]:e instanceof Nn?[null,...sn(e.unwrap())]:e instanceof Wc||e instanceof No?sn(e.unwrap()):e instanceof $o?sn(e._def.innerType):[];class pi extends le{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==H.object)return U(n,{code:$.invalid_type,expected:H.object,received:n.parsedType}),q;const r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(U(n,{code:$.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const s of n){const a=sn(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of a){if(o.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);o.set(c,s)}}return new pi({typeName:X.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...ce(r)})}}function Da(e,t){const n=ln(e),r=ln(t);if(e===t)return{valid:!0,data:e};if(n===H.object&&r===H.object){const o=be.objectKeys(t),s=be.objectKeys(e).filter(c=>o.indexOf(c)!==-1),a={...e,...t};for(const c of s){const l=Da(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===H.array&&r===H.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],c=t[s],l=Da(a,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===H.date&&r===H.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class To extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(s,a)=>{if($a(s)||$a(a))return q;const c=Da(s.value,a.value);return c.valid?((Na(s)||Na(a))&&n.dirty(),{status:n.value,value:c.data}):(U(r,{code:$.invalid_intersection_types}),q)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}To.create=(e,t,n)=>new To({left:e,right:t,typeName:X.ZodIntersection,...ce(n)});class tn extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==H.array)return U(r,{code:$.invalid_type,expected:H.array,received:r.parsedType}),q;if(r.data.length<this._def.items.length)return U(r,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),q;!this._def.rest&&r.data.length>this._def.items.length&&(U(r,{code:$.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new en(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>dt.mergeArray(n,a)):dt.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new tn({...this._def,rest:t})}}tn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new tn({items:e,typeName:X.ZodTuple,rest:null,...ce(t)})};class Co extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==H.object)return U(r,{code:$.invalid_type,expected:H.object,received:r.parsedType}),q;const o=[],s=this._def.keyType,a=this._def.valueType;for(const c in r.data)o.push({key:s._parse(new en(r,c,r.path,c)),value:a._parse(new en(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?dt.mergeObjectAsync(n,o):dt.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof le?new Co({keyType:t,valueType:n,typeName:X.ZodRecord,...ce(r)}):new Co({keyType:Ht.create(),valueType:t,typeName:X.ZodRecord,...ce(n)})}}class zs extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==H.map)return U(r,{code:$.invalid_type,expected:H.map,received:r.parsedType}),q;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:o._parse(new en(r,c,r.path,[d,"key"])),value:s._parse(new en(r,l,r.path,[d,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of a){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return q;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const l of a){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return q;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}zs.create=(e,t,n)=>new zs({valueType:t,keyType:e,typeName:X.ZodMap,...ce(n)});class cr extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==H.set)return U(r,{code:$.invalid_type,expected:H.set,received:r.parsedType}),q;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(U(r,{code:$.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(U(r,{code:$.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return q;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>s._parse(new en(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new cr({...this._def,minSize:{value:t,message:V.toString(n)}})}max(t,n){return new cr({...this._def,maxSize:{value:t,message:V.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}cr.create=(e,t)=>new cr({valueType:e,minSize:null,maxSize:null,typeName:X.ZodSet,...ce(t)});class Tr extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==H.function)return U(n,{code:$.invalid_type,expected:H.function,received:n.parsedType}),q;function r(c,l){return Bs({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Us(),$r].filter(d=>!!d),issueData:{code:$.invalid_arguments,argumentsError:l}})}function o(c,l){return Bs({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Us(),$r].filter(d=>!!d),issueData:{code:$.invalid_return_type,returnTypeError:l}})}const s={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Dr){const c=this;return ut(async function(...l){const d=new At([]),u=await c._def.args.parseAsync(l,s).catch(m=>{throw d.addIssue(r(l,m)),d}),f=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(f,s).catch(m=>{throw d.addIssue(o(f,m)),d})})}else{const c=this;return ut(function(...l){const d=c._def.args.safeParse(l,s);if(!d.success)throw new At([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,s);if(!f.success)throw new At([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Tr({...this._def,args:tn.create(t).rest(Qn.create())})}returns(t){return new Tr({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Tr({args:t||tn.create([]).rest(Qn.create()),returns:n||Qn.create(),typeName:X.ZodFunction,...ce(r)})}}class Oo extends le{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Oo.create=(e,t)=>new Oo({getter:e,typeName:X.ZodLazy,...ce(t)});class Po extends le{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return U(n,{received:n.data,code:$.invalid_literal,expected:this._def.value}),q}return{status:"valid",value:t.data}}get value(){return this._def.value}}Po.create=(e,t)=>new Po({value:e,typeName:X.ZodLiteral,...ce(t)});function wp(e,t){return new $n({values:e,typeName:X.ZodEnum,...ce(t)})}class $n extends le{constructor(){super(...arguments),ao.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{expected:be.joinValues(r),received:n.parsedType,code:$.invalid_type}),q}if(Hs(this,ao)||_p(this,ao,new Set(this._def.values)),!Hs(this,ao).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{received:n.data,code:$.invalid_enum_value,options:r}),q}return ut(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 $n.create(t,{...this._def,...n})}exclude(t,n=this._def){return $n.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}ao=new WeakMap;$n.create=wp;class Mo extends le{constructor(){super(...arguments),co.set(this,void 0)}_parse(t){const n=be.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==H.string&&r.parsedType!==H.number){const o=be.objectValues(n);return U(r,{expected:be.joinValues(o),received:r.parsedType,code:$.invalid_type}),q}if(Hs(this,co)||_p(this,co,new Set(be.getValidEnumValues(this._def.values))),!Hs(this,co).has(t.data)){const o=be.objectValues(n);return U(r,{received:r.data,code:$.invalid_enum_value,options:o}),q}return ut(t.data)}get enum(){return this._def.values}}co=new WeakMap;Mo.create=(e,t)=>new Mo({values:e,typeName:X.ZodNativeEnum,...ce(t)});class Dr extends le{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==H.promise&&n.common.async===!1)return U(n,{code:$.invalid_type,expected:H.promise,received:n.parsedType}),q;const r=n.parsedType===H.promise?n.data:Promise.resolve(n.data);return ut(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Dr.create=(e,t)=>new Dr({type:e,typeName:X.ZodPromise,...ce(t)});class zt extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{U(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return q;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?q:l.status==="dirty"||n.value==="dirty"?Er(l.value):l});{if(n.value==="aborted")return q;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?q:c.status==="dirty"||n.value==="dirty"?Er(c.value):c}}if(o.type==="refinement"){const a=c=>{const l=o.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?q:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?q:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ir(a))return a;const c=o.transform(a.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>ir(a)?Promise.resolve(o.transform(a.value,s)).then(c=>({status:n.value,value:c})):a);be.assertNever(o)}}zt.create=(e,t,n)=>new zt({schema:e,typeName:X.ZodEffects,effect:t,...ce(n)});zt.createWithPreprocess=(e,t,n)=>new zt({schema:t,effect:{type:"preprocess",transform:e},typeName:X.ZodEffects,...ce(n)});class Xt extends le{_parse(t){return this._getType(t)===H.undefined?ut(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Xt.create=(e,t)=>new Xt({innerType:e,typeName:X.ZodOptional,...ce(t)});class Nn extends le{_parse(t){return this._getType(t)===H.null?ut(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Nn.create=(e,t)=>new Nn({innerType:e,typeName:X.ZodNullable,...ce(t)});class jo extends le{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===H.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}jo.create=(e,t)=>new jo({innerType:e,typeName:X.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});class $o extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Eo(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new At(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new At(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}$o.create=(e,t)=>new $o({innerType:e,typeName:X.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});class Ks extends le{_parse(t){if(this._getType(t)!==H.nan){const r=this._getOrReturnCtx(t);return U(r,{code:$.invalid_type,expected:H.nan,received:r.parsedType}),q}return{status:"valid",value:t.data}}}Ks.create=e=>new Ks({typeName:X.ZodNaN,...ce(e)});const kb=Symbol("zod_brand");class Wc extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Jo extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?q:s.status==="dirty"?(n.dirty(),Er(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?q:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new Jo({in:t,out:n,typeName:X.ZodPipeline})}}class No extends le{_parse(t){const n=this._def.innerType._parse(t),r=o=>(ir(o)&&(o.value=Object.freeze(o.value)),o);return Eo(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}No.create=(e,t)=>new No({innerType:e,typeName:X.ZodReadonly,...ce(t)});function kd(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function kp(e,t={},n){return e?Nr.create().superRefine((r,o)=>{var s,a;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=kd(t,r),h=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;o.addIssue({code:"custom",...f,fatal:h})}});if(!c){const l=kd(t,r),d=(a=(s=l.fatal)!==null&&s!==void 0?s:n)!==null&&a!==void 0?a:!0;o.addIssue({code:"custom",...l,fatal:d})}}):Nr.create()}const Sb={object:Fe.lazycreate};var X;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(X||(X={}));const Eb=(e,t={message:`Input not instance of ${e.name}`})=>kp(n=>n instanceof e,t),Sp=Ht.create,Ep=Mn.create,Ab=Ks.create,Ib=jn.create,Ap=Ao.create,Rb=ar.create,xb=Ws.create,Tb=Io.create,Cb=Ro.create,Ob=Nr.create,Pb=Qn.create,Mb=hn.create,jb=Gs.create,$b=Wt.create,Nb=Fe.create,Db=Fe.strictCreate,Lb=xo.create,Fb=pi.create,Ub=To.create,Bb=tn.create,Hb=Co.create,Wb=zs.create,Gb=cr.create,zb=Tr.create,Kb=Oo.create,Vb=Po.create,Zb=$n.create,Yb=Mo.create,Jb=Dr.create,Sd=zt.create,Qb=Xt.create,Xb=Nn.create,qb=zt.createWithPreprocess,ev=Jo.create,tv=()=>Sp().optional(),nv=()=>Ep().optional(),rv=()=>Ap().optional(),ov={string:e=>Ht.create({...e,coerce:!0}),number:e=>Mn.create({...e,coerce:!0}),boolean:e=>Ao.create({...e,coerce:!0}),bigint:e=>jn.create({...e,coerce:!0}),date:e=>ar.create({...e,coerce:!0})},sv=q;var i=Object.freeze({__proto__:null,defaultErrorMap:$r,setErrorMap:q_,getErrorMap:Us,makeIssue:Bs,EMPTY_PATH:eb,addIssueToContext:U,ParseStatus:dt,INVALID:q,DIRTY:Er,OK:ut,isAborted:$a,isDirty:Na,isValid:ir,isAsync:Eo,get util(){return be},get objectUtil(){return ja},ZodParsedType:H,getParsedType:ln,ZodType:le,datetimeRegex:yp,ZodString:Ht,ZodNumber:Mn,ZodBigInt:jn,ZodBoolean:Ao,ZodDate:ar,ZodSymbol:Ws,ZodUndefined:Io,ZodNull:Ro,ZodAny:Nr,ZodUnknown:Qn,ZodNever:hn,ZodVoid:Gs,ZodArray:Wt,ZodObject:Fe,ZodUnion:xo,ZodDiscriminatedUnion:pi,ZodIntersection:To,ZodTuple:tn,ZodRecord:Co,ZodMap:zs,ZodSet:cr,ZodFunction:Tr,ZodLazy:Oo,ZodLiteral:Po,ZodEnum:$n,ZodNativeEnum:Mo,ZodPromise:Dr,ZodEffects:zt,ZodTransformer:zt,ZodOptional:Xt,ZodNullable:Nn,ZodDefault:jo,ZodCatch:$o,ZodNaN:Ks,BRAND:kb,ZodBranded:Wc,ZodPipeline:Jo,ZodReadonly:No,custom:kp,Schema:le,ZodSchema:le,late:Sb,get ZodFirstPartyTypeKind(){return X},coerce:ov,any:Ob,array:$b,bigint:Ib,boolean:Ap,date:Rb,discriminatedUnion:Fb,effect:Sd,enum:Zb,function:zb,instanceof:Eb,intersection:Ub,lazy:Kb,literal:Vb,map:Wb,nan:Ab,nativeEnum:Yb,never:Mb,null:Cb,nullable:Xb,number:Ep,object:Nb,oboolean:rv,onumber:nv,optional:Qb,ostring:tv,pipeline:ev,preprocess:qb,promise:Jb,record:Hb,set:Gb,strictObject:Db,string:Sp,symbol:xb,transformer:Sd,tuple:Bb,undefined:Tb,union:Lb,unknown:Pb,void:jb,NEVER:sv,ZodIssueCode:$,quotelessJson:X_,ZodError:At});const Ed=i.enum(["app_start","sign_in","window_focus","surface_open"]),Ip=i.object({id:i.string().min(1),state:i.enum(["active","paused","disabled"])}).passthrough(),iv=i.object({tenant_id:i.string().min(1),tenant_name:i.string().optional(),eligible:i.boolean(),endpoint:Ip.nullable()}).passthrough(),av=i.object({code:i.string(),message:i.string(),details:i.record(i.unknown()).optional(),retry_after_seconds:i.number().optional()}).passthrough(),cv=i.object({code:i.string().min(1),count:i.number().int().nonnegative(),session:i.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),lv=i.object({in_force:i.boolean(),notice_pending:i.boolean().catch(!1)}).passthrough().optional().catch(void 0),iP=i.object({capability:i.number(),consent_account_guard:i.boolean().optional(),state:i.enum(["ready","signed_out","unavailable","update_required"]),account_id:i.string().nullable(),tenant_id:i.string().nullable(),surface_state:i.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:i.object({settings:i.boolean(),inbox:i.boolean(),account_door:i.boolean(),onboarding:i.boolean()}),update_required:i.boolean(),local:i.object({enabled:i.boolean(),onboarding:i.string(),session:i.string()}),status:i.object({tenants:i.array(iv)}).passthrough().nullable(),consent:i.object({version:i.string().min(1).max(128),text:i.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:i.enum(["served","cached","embedded"])}).nullable(),error:av.nullable(),state_note:i.string().nullable().optional(),read_only:i.boolean().optional(),trial_ended:i.object({tenant_id:i.string().min(1),trial_ended_at:i.string().min(1)}).passthrough().nullable().optional().catch(null),delivery_hold:cv,default_on:lv}).passthrough(),dv=i.object({version:i.string().min(1),consented_at:i.string().min(1),consented_via:i.string().min(1),current:i.boolean()}).passthrough(),aP=i.object({endpoint:Ip.extend({tenant_id:i.string().min(1),label:i.string().optional(),consent:dv.nullable().optional(),created_at:i.string().optional(),updated_at:i.string().optional()}).nullable(),settings:i.object({tenant_id:i.string().min(1),eligible:i.boolean(),consent_version:i.string().optional(),consent_required:i.boolean()}).passthrough(),default_on:i.boolean().optional().catch(void 0),share_typing:i.boolean().optional().catch(void 0)}).passthrough(),uv=i.object({kind:i.enum(["endpoint","account"]).optional(),endpoint_id:i.string().min(1).optional(),account_id:i.string().min(1).optional()}).passthrough().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id").refine(e=>e.kind===void 0||(e.kind==="endpoint"?e.endpoint_id!==void 0:e.account_id!==void 0),"An allowlist target's kind must agree with the id it carries"),Ad=i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:uv,id:i.string().optional()}).passthrough(),Id=i.object({mode:i.enum(["class_default","listed_only"]),allow:i.number(),deny:i.number()}).passthrough(),cP=i.object({allowlist:i.object({tenant_id:i.string().min(1),entries:i.array(Ad)}).passthrough(),view:i.object({tenant_id:i.string().nullable(),entries:i.array(Ad),directions:i.object({send:Id,receive:Id}),class_default:i.literal("cos_cos"),cues:i.object({allow_entry_switches_direction_to_listed_only:i.boolean(),listed_only_affects:i.string(),removing_allow_does_not_stop_open_thread:i.boolean(),deny_stops_pair_both_directions:i.boolean()}).passthrough()}).passthrough()}).passthrough(),lP=i.object({onboarding:i.literal("seen")}).passthrough();function fv(e){return e?.default_on?.in_force===!0}function dP(e,t){const n=pv(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function uP(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function fP(e,t){if(!e||!t||fv(e)||e.account_id!==t||e.capability<1||e.state!=="ready"||e.update_required||e.surface_state!=="B"||!e.visibility.onboarding||!e.tenant_id)return null;const n=e.status?.tenants.filter(r=>r.tenant_id===e.tenant_id);return n?.length!==1||n[0].eligible!==!0||n[0].endpoint!==null?null:{accountId:t,tenantId:e.tenant_id}}function pv(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const hv=8,La=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],mv=6*1024,gv=512;function Vs(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const o=[];for(const s of n){if(o.length===gv)break;const c=new URLSearchParams({order_ids:s}).toString().length+1;if(r+c>mv)break;e.append("order_ids",s),o.push(s),r+=c}return o}function _v(e,t,n){return Vs(new URLSearchParams(n),t,e)}const pP=3,bv=4096,hP=128,mP=/^[0-9a-f]{32}$/,vv=/^\.+$/,yv=new RegExp("\\p{Cf}","u"),wv=/[/\\:]/,E=i.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),kv=i.string().min(1).max(128),cs=i.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),ls=i.string().min(1).max(32768),Sv=/^[a-f0-9]{12}$/,B=i.string().regex(Sv),Ui=i.string().regex(/^[a-f0-9]{12}$/),Bi=i.string().min(1).max(128),Ev=i.string().min(1).max(4096),Vr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),Hi=i.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),ds=i.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),Rd=i.string().regex(/^[a-f0-9]{32}$/),Av=/^(\/|[A-Za-z]:[\\/])/,Wi=i.string().min(1).max(4096).regex(Av),xd=/^[a-f0-9]{32}$/,ue=i.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),Td=i.string().min(1).max(512).nullish(),mr=i.string().regex(/^[A-Za-z0-9_-]{1,128}$/),Zr=i.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),Iv=["credential_finite_share","credential_inheritance"],Zs=/^sha256:[0-9a-f]{64}$/,Cd={operation:i.enum(Iv),requestDigest:i.string().regex(Zs),disclosureDigest:i.string().regex(Zs)},Yr=i.string().regex(/^la_[0-9a-f]{16}$/),Jr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),Od=i.object({data_b64:i.string().min(1).max(1e6),mime_type:i.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:i.string().max(4096).optional()}).strict(),Rv=i.object({digest:i.string().regex(/^[0-9a-f]{32}$/),name:i.string().max(1024).optional(),mime_type:i.string().max(255).optional(),bytes:i.number().int().min(0).optional(),path:i.string().max(4096).optional()}).strict(),Pd=2e5,Md=8,xv=256,Tv=100,jd=16,Cv=256,Ov=100,Pv=200,Mv=1e6,jv=i.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),nt=i.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),us=i.object({kind:i.enum(["agent","team"]),name:nt}).strict(),Rp=i.enum(["claude","codex","omp"]),$v=i.record(i.string(),i.array(i.string().min(1).max(512)).max(5e3)),$d={sources:i.array(Rp).max(3).optional(),sessionIds:$v.optional(),all:i.boolean().optional(),includeSubagents:i.boolean().optional(),includeClearedSegments:i.boolean().optional(),includeMemory:i.boolean().optional(),includeInstructions:i.boolean().optional(),maxSessions:i.number().int().min(1).max(5e3).optional()},Gi=i.object({provider:i.string().min(1).max(128),model_id:i.string().min(1).max(512),reasoning_effort:i.string().min(1).max(64).nullable(),fast_mode:i.boolean().nullable().optional()}).strict(),Nd=i.object({kind:i.enum(["role","specialist"]).optional(),description:i.string().max(8e3).optional(),instructions:i.string().max(8e3).optional(),tools:i.array(i.string().min(1).max(128)).max(256).optional(),effort:i.string().max(64).optional(),delegate:i.boolean().optional(),action_class:i.enum(["reactive","proactive"]).optional()}).strict(),Dd=i.object({name:i.string().min(1).max(64).optional(),description:i.string().max(8e3).optional(),manager:nt.optional(),members:i.array(i.object({role:nt,count:i.number().int().min(1).max(16),kind:i.enum(["agent","team"]),tier:i.enum(["lo","med","hi"]).nullable().optional(),effort:jv.nullable().optional()}).strict()).max(128).optional(),instructions:i.string().max(8e3).optional(),project:i.string().max(8e3).optional()}).strict(),Nv=i.record(i.array(i.string().max(1024)).max(100)),zi=i.array(E).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),Dv=i.array(i.object({kind:i.enum(["human","agent"]),account_id:E,endpoint_id:E.optional()}).strict()).max(50).refine(e=>new Set(e.map(t=>`${t.kind}:${t.account_id}:${t.endpoint_id??""}`)).size===e.length,"Duplicate mention"),Ld=i.enum(["minutes","hours","days"]);function Lv(e){return!vv.test(e)}const gP=e=>Cs.safeParse(e).success,Cs=i.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(Lv),Fd=i.enum(["str","int","float","bool","list","dict"]),Ud=i.string().max(16384),Fv=2e3,Bd=i.string().min(1).max(Fv),Hd=i.string().min(1).max(64),Uv=i.string().min(1).max(64),Bv=i.string().min(1).max(64),Wd=i.object({is_active:i.boolean().nullish(),one_time:i.boolean().nullish(),start_time_utc:i.string().max(64).nullish(),end_time_utc:i.string().max(64).nullish()}).strict(),Hv=i.object({conversation_length:i.number().int().optional(),detail_length:i.number().int().optional(),max_learnings_history:i.number().int().optional(),hosting:i.string().max(256).optional(),model_name:i.string().max(1024).optional(),auto_save_conversation:i.boolean().optional()}).strict(),Fa=128,Gd=2e3,zd=8e3,Kd=64,Vd=64,hi=e=>[...e].length,Ua=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,Wv=e=>e===9||e===10||e===11||e===12||e===13||e===133,Gv=e=>e<=31||e>=127&&e<=159,zv=e=>yv.test(String.fromCodePoint(e)),Kv=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,fs=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},xp=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&Ua(t[n].codePointAt(0)??0);)n++;for(;r>n&&Ua(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},Vv=e=>{let t="",n=!1;for(const r of e){if(Ua(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function Zv(e){const t=xp(e);if(!t)return"must not be empty";if(hi(t)>Fa)return`must be at most ${Fa} characters`;if(wv.test(t))return'must not contain "/", "\\" or ":"';if(fs(t,Kv))return"must not contain Unicode bidirectional override characters";if(fs(t,Wv))return"must not contain whitespace";if(fs(t,Gv))return"must not contain control characters";if(fs(t,zv))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 _P(e){return Vv(xp(e).normalize("NFKC").toLowerCase())}function Yv(e){return e.trim()?hi(e)>Gd?`must be at most ${Gd} characters`:null:"must not be empty"}function Jv(e){return e.trim()?hi(e)>zd?`must be at most ${zd} characters`:null:"must not be empty"}function Qv(e){if(e.length>Vd)return`must hold at most ${Vd} items`;for(const t of e)if(!t.trim()||hi(t)>Kd)return`must hold items of 1 to ${Kd} characters`;return null}const Xv=e=>Zv(e)===null,qv=i.string().refine(Xv,{message:"That is not a name the hub can publish."}),ey=i.string().refine(e=>Jv(e)===null,{message:"That instruction body cannot be published."}),ty=i.string().refine(e=>Yv(e)===null,{message:"That description cannot be published."}),ny=i.array(i.string()).refine(e=>Qv(e)===null,{message:"That tool list cannot be published."}),Ki={requestId:ue.optional(),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()},Zd=i.object({name:qv,description:ty,instructions:ey,kind:i.enum(["role","specialist"]),when_to_use:i.string(),tools:ny,effort:i.string(),delegate:i.boolean(),version:i.string(),categories:i.array(i.string()),tags:i.array(i.string())}).partial().strict(),ry=i.enum(["team","agent"]),oy=i.string().min(1).max(64),sy=i.string().min(1).max(256),Tp=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Vi=i.string().regex(Tp,{message:"Letters, digits, dot, underscore and dash; no spaces."}),iy=["planning","active","qa","validation","done","paused","archived"],Yd=i.enum(iy),ps=i.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),Jd=i.array(i.string().min(1).max(24)).max(8),En=i.string().min(1).max(64),ay=1e3,Qd=240,Xd=80,cy=256,ly=100,dy=200,uy=/^[a-z0-9][a-z0-9_-]{0,23}$/;function bP(e){return e?Tp.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 vP(e){return uy.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const hs=i.enum(["agent","team","skill"]),Zi=i.string().min(1).max(128).regex(/\S/),qd=i.enum(La),fy=i.object({visible:i.array(qd).max(La.length),more:i.array(qd).max(La.length)}).strict(),dn=i.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),eu=i.object({selectionToken:i.string().min(1).max(512),reconcileIds:i.array(dn).max(500).optional(),excludedIds:i.array(dn).max(500).optional()}).strict(),py=i.object({operationToken:i.string().min(1).max(512),reconcileIds:i.array(dn).max(500).optional()}).strict(),tu=i.union([i.object({throughSeq:i.number().int().min(0).optional(),receipt:i.literal(!0).optional(),reconcileIds:i.array(dn).max(500).optional(),items:i.array(i.object({id:dn,revision:i.number().int().min(1)}).strict()).min(1).max(500)}).strict(),i.object({sessionId:B,throughSeq:i.number().int().min(0),observed:i.array(i.object({id:dn,revision:i.number().int().min(1)}).strict()).max(500)}).strict(),i.object({all:i.literal(!0),throughSeq:i.number().int().min(0),observed:i.array(i.object({id:dn,revision:i.number().int().min(1)}).strict()).max(500)}).strict()]),hy={pointer:"pointerdown",key:"keydown",wheel:"wheel"},my=i.discriminatedUnion("op",[i.object({op:i.literal("capabilities")}).strict(),i.object({op:i.literal("runtimes.list")}).strict(),i.object({op:i.literal("profiles.list")}).strict(),i.object({op:i.literal("profiles.get"),name:nt}).strict(),i.object({op:i.literal("imports.sources")}).strict(),i.object({op:i.literal("imports.sessions"),source:Rp,includeSubagents:i.boolean().optional()}).strict(),i.object({op:i.literal("imports.preview"),...$d}).strict(),i.object({op:i.literal("imports.start"),...$d}).strict(),i.object({op:i.literal("imports.status"),jobId:i.string().min(1).max(128)}).strict(),i.object({op:i.literal("imports.cancel"),jobId:i.string().min(1).max(128)}).strict(),i.object({op:i.literal("profiles.update"),name:nt,requestId:ue,fields:Nd,expectedDefinitionRevision:Td.optional()}).strict(),i.object({op:i.literal("profiles.install"),name:nt,requestId:ue}).strict(),i.object({op:i.literal("profiles.create"),name:nt,requestId:ue,fields:Nd.extend({description:i.string().max(8e3),instructions:i.string().min(1).max(8e3)})}).strict(),i.object({op:i.literal("hub.updates")}).strict(),i.object({op:i.literal("hub.skillPull"),requestId:ue,hubId:E,hubSource:i.string().min(1).max(2048),visibility:i.enum(["public","org"]),tenantId:E.nullable(),localAlias:nt,subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional(),dryRun:i.boolean().optional(),adoptionStrategy:i.enum(["merge","keep-local","take-hub"]).optional(),allowLlm:i.boolean().optional(),confirm:i.boolean().optional(),adoptionReceipt:i.string().min(16).max(128).optional()}).strict(),i.object({op:i.literal("hub.skillSubscribe"),requestId:ue,hubId:E,hubSource:i.string().min(1).max(2048),visibility:i.enum(["public","org"]),tenantId:E.nullable(),localAlias:nt}).strict(),i.object({op:i.literal("hub.skillUnpull"),requestId:ue,linkId:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("hub.skillPublish"),requestId:ue,dryRun:i.boolean(),sourceSkill:nt,localAlias:nt,visibility:i.enum(["public","org"]),tenantId:E.nullable(),subscribe:i.boolean(),autoPush:i.boolean(),confirmPublicEgress:i.boolean(),previewReceipt:i.string().min(1).max(4096).optional(),confirmPublish:i.literal(!0).optional()}).strict(),i.object({op:i.literal("hub.links"),kind:i.enum(["agent","team","skill"]).optional()}).strict(),i.object({op:i.literal("hub.policy"),requestId:ue,linkId:i.string().min(1).max(256),expectedPolicyRevision:i.string().min(1).max(256),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()}).strict(),i.object({op:i.literal("hub.check"),requestId:ue,kind:hs.optional(),name:nt.optional(),localId:Zi.optional()}).strict(),i.object({op:i.literal("hub.apply"),requestId:ue,kind:hs.optional(),name:nt.optional(),localId:Zi.optional(),prefer:i.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:i.boolean().optional(),dryRun:i.boolean().optional(),resolveSource:i.literal(!0).optional(),hubSource:i.string().min(1).max(2048).optional(),visibility:i.enum(["public","org"]).optional(),tenantId:i.string().min(1).max(128).nullable().optional()}).strict(),i.object({op:i.literal("hub.applyAll"),requestId:ue,kind:hs.optional()}).strict(),i.object({op:i.literal("hub.retry"),requestId:ue,kind:hs.optional(),name:nt.optional(),localId:Zi.optional()}).strict(),i.object({op:i.literal("hub.push"),requestId:ue,linkId:i.string().min(1).max(256),direction:i.literal("push"),dryRun:i.boolean(),previewReceipt:i.string().min(1).max(4096).optional(),confirmPublish:i.literal(!0).optional()}).strict(),i.object({op:i.literal("teams.list")}).strict(),i.object({op:i.literal("teams.get"),name:nt}).strict(),i.object({op:i.literal("teams.effective"),name:nt}).strict(),i.object({op:i.literal("teams.update"),name:nt,requestId:ue,fields:Dd,expectedDefinitionRevision:Td.optional()}).strict(),i.object({op:i.literal("teams.create"),requestId:ue,fields:Dd.extend({name:i.string().min(1).max(64)})}).strict(),i.object({op:i.literal("sessions.list"),limit:i.number().int().min(1).max(500).optional(),include_archived:i.boolean().optional(),include_peers:i.boolean().optional(),scope_kind:ry.optional(),scope_name:oy.optional(),cursor:sy.optional(),with_counts:i.boolean().optional(),sort:i.literal("activity").optional()}).strict(),i.object({op:i.literal("delegated_cleanup_notice.ack")}).strict(),i.object({op:i.literal("sessions.search"),q:i.string().min(1).max(xv),limit:i.number().int().min(1).max(500).optional(),include_archived:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.archive"),sessionId:B,archived:i.boolean()}).strict(),i.object({op:i.literal("sessions.delete"),sessionId:B,confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.create"),requestId:ue,cwd:i.string().min(1).max(4096).optional(),target:us.optional(),purpose:i.literal("agents-config").optional(),model:Gi.optional(),draftId:B.optional(),peer:mr.optional()}).strict(),i.object({op:i.literal("sessions.preview"),requestId:ue,cwd:i.string().min(1).max(4096),target:us.optional(),model:Gi.optional()}).strict(),i.object({op:i.literal("sessions.draft"),requestId:ue,cwd:i.string().min(1).max(4096),target:us.optional(),model:Gi.optional()}).strict(),i.object({op:i.literal("sessions.get"),sessionId:B,journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.files"),sessionId:B,scope:i.enum(["family","self"]).optional(),kind:i.string().max(256).optional(),q:i.string().max(256).optional(),sort:i.enum(["recent","name","kind","modified","created","size"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(8192).optional()}).strict(),i.object({op:i.literal("sessions.files.materialise"),sessionId:B,fileId:i.string().regex(/^[a-f0-9]{16}$/)}).strict(),i.object({op:i.literal("sessions.userAttachments"),sessionId:B}).strict(),i.object({op:i.literal("sessions.userAttachments.materialise"),sessionId:B,digest:i.string().regex(/^[a-f0-9]{32}$/)}).strict(),i.object({op:i.literal("sessions.history"),sessionId:B,beforeId:E.optional(),limit:i.number().int().min(1).max(500).optional(),openFrame:i.boolean().optional(),journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional(),sourceRead:i.enum(["metadata","payload"]).optional(),expectedJournalGeneration:i.string().min(1).max(128).optional()}).strict(),i.object({op:i.literal("sessions.checkpoints"),sessionId:B}).strict(),i.object({op:i.literal("sessions.checkpoints.warm"),sessionId:B,ids:i.array(E).max(jd).optional(),limit:i.number().int().min(1).max(jd).optional()}).strict(),i.object({op:i.literal("sessions.find"),sessionId:B,q:i.string().min(1).max(Cv),limit:i.number().int().min(1).max(Pv).optional()}).strict(),i.object({op:i.literal("subagents.transcript"),sessionId:B,childId:B,beforeId:E.optional(),entryId:i.string().min(1).max(128).regex(/^[a-zA-Z0-9_:-]+$/).optional(),limit:i.number().int().min(1).max(500).optional()}).strict(),i.object({op:i.literal("sessions.message"),sessionId:B,requestId:ue,text:i.string().max(Pd),images:i.array(Od).max(Md).optional(),files:i.array(Rv).max(hv).optional(),mode:i.enum(["prompt","steer"]).optional(),inputMode:i.enum(["typed","dictated","mixed"]).optional(),inputPath:i.string().max(1024).optional()}).strict(),i.object({op:i.literal("sessions.command"),sessionId:B,requestId:ue,command:i.string().regex(/^\/?[A-Za-z]+$/).max(64),args:i.string().max(Pd).optional(),images:i.array(Od).max(Md).optional()}).strict(),i.object({op:i.literal("sessions.move"),sessionId:B,requestId:ue,cwd:i.string().min(1).max(4096)}).strict(),i.object({op:i.literal("settingsIntents.list"),sessionId:B.optional()}).strict(),i.object({op:i.literal("settingsIntents.submit"),sessionId:B,requestId:ue,kind:i.enum(["model","effort","fast","cwd"]),value:i.union([i.string().min(1).max(4096),i.boolean()]),effort:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("settingsIntents.dismiss"),sessionId:B,kind:i.enum(["model","effort","fast","cwd"]),generation:i.number().int().nonnegative()}).strict(),i.object({op:i.literal("sessions.profileActionStatus"),sessionId:B,actionId:i.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),receiptId:i.string().min(1).max(160),profileKind:i.enum(["agent","team"]),profileName:i.string().min(1).max(128),toolCallId:i.string().min(1).max(160)}).strict(),i.object({op:i.literal("sessions.answer"),sessionId:B,epoch:E.optional(),requestId:E.optional(),value:i.string().max(32768).optional(),approved:i.boolean().optional(),questionIndex:i.number().int().min(0).optional(),askId:E.optional(),answers:i.record(i.string(),i.array(i.string().max(32768))).optional(),decline:i.boolean().optional(),revise:i.boolean().optional(),dismiss:i.boolean().optional(),reason:i.enum(["answered_in_chat","moot"]).optional()}).strict(),i.object({op:i.literal("sessions.seen"),sessionId:B,completionToken:i.string().uuid()}).strict(),i.object({op:i.literal("attention.seen"),items:i.array(i.object({sessionId:B,completionToken:i.string().uuid()}).strict()).min(1).max(500)}).strict(),i.object({op:i.literal("sessions.notified"),sessionId:B,completionToken:i.string().uuid()}).strict(),i.object({op:i.literal("tags.list")}).strict(),i.object({op:i.literal("tags.replace"),tags:i.array(i.object({id:i.string().optional(),name:i.string()}).strict())}).strict(),i.object({op:i.literal("sessions.tags"),expected_revision:i.string().optional(),sessionId:B,tags:i.array(i.string()),primary:i.string().nullable()}).strict(),i.object({op:i.literal("sessions.pin"),sessionId:B,pinned:i.boolean()}).strict(),i.object({op:i.literal("sessions.watch"),sessionId:B,subscriptionId:i.string().regex(xd),visible:i.boolean(),canNotify:i.boolean()}).strict(),i.object({op:i.literal("sessions.warm"),sessionId:B}).strict(),i.object({op:i.literal("sessions.interrupt"),sessionId:B,requestId:ue}).strict(),i.object({op:i.literal("supplements.cancel"),sessionId:B,job:Ui,anchor:Bi}).strict(),i.object({op:i.literal("supplements.restart"),sessionId:B,job:Ui,anchor:Bi}).strict(),i.object({op:i.literal("supplements.steer"),sessionId:B,job:Ui,anchor:Bi,text:i.string().min(1).max(500)}).strict(),i.object({op:i.literal("sessions.variables.list"),sessionId:B}).strict(),i.object({op:i.literal("sessions.variables.create"),sessionId:B,key:Cs,value:Ud,type:Fd}).strict(),i.object({op:i.literal("sessions.variables.update"),sessionId:B,key:Cs,value:Ud,type:Fd}).strict(),i.object({op:i.literal("sessions.variables.delete"),sessionId:B,key:Cs}).strict(),i.object({op:i.literal("sessions.presence"),subscriptionId:i.string().regex(/^[a-f0-9]{1,64}$/),canNotify:i.boolean(),canNotifyKinds:i.array(i.enum(["complete","error"])).max(4),sessionId:i.string().regex(/^([a-f0-9]{12})?$/),window:i.object({exists:i.boolean(),focused:i.boolean(),visible:i.boolean(),minimized:i.boolean()}).strict()}).strict(),i.object({op:i.literal("legacy.models"),provider:i.string().max(128).optional(),sort:i.enum(["id","name","provider","recommended"]).optional(),direction:i.enum(["ascending","descending"]).optional()}).strict(),i.object({op:i.literal("legacy.models.providers")}).strict(),i.object({op:i.literal("auth.probe"),provider:E}).strict(),i.object({op:i.literal("legacy.agent.upload"),agentId:E}).strict(),i.object({op:i.literal("agent.publish"),agentId:E,document:Zd.optional(),...Ki,visibility:i.literal("org").optional(),tenantId:E.optional()}).strict(),i.object({op:i.literal("agent.republish"),agentId:E,hubAgentId:E,expectedRemoteRevision:i.string().min(1).max(512).optional(),document:Zd.optional(),...Ki,visibility:i.literal("org").optional(),tenantId:E.optional()}).strict(),i.object({op:i.literal("team.publish"),teamId:E,...Ki,visibility:i.literal("org").optional(),tenantId:E.optional()}).strict(),i.object({op:i.literal("team.pull"),teamId:E,tenantId:E.optional()}).strict(),i.object({op:i.literal("agent.nameAvailability"),name:i.string().min(1).max(Fa)}).strict(),i.object({op:i.literal("legacy.agents.list"),page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(500).optional(),name:i.string().max(256).optional(),sort:i.string().max(64).optional(),direction:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("legacy.agent.get"),agentId:E}).strict(),i.object({op:i.literal("legacy.agent.history"),agentId:E,page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(500).optional()}).strict(),i.object({op:i.literal("legacy.jobs.list"),agentId:E.optional(),status:i.string().max(64).optional()}).strict(),i.object({op:i.literal("legacy.job.get"),jobId:E}).strict(),i.object({op:i.literal("legacy.schedules.list"),page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("legacy.agent.schedules.list"),agentId:E,page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("legacy.agent.schedule.create"),agentId:E,schedule:Wd.extend({prompt:i.string().max(64e3),interval:i.number().int().min(1),unit:Ld})}).strict(),i.object({op:i.literal("legacy.schedule.get"),scheduleId:E}).strict(),i.object({op:i.literal("legacy.schedule.edit"),scheduleId:E,schedule:Wd.extend({prompt:i.string().max(64e3).nullish(),interval:i.number().int().min(1).nullish(),unit:Ld.nullish()})}).strict(),i.object({op:i.literal("legacy.schedule.remove"),scheduleId:E}).strict(),i.object({op:i.literal("legacy.agent.create"),agent:i.record(i.unknown())}).strict(),i.object({op:i.literal("legacy.agent.update"),agentId:E,update:i.record(i.unknown())}).strict(),i.object({op:i.literal("legacy.agent.delete"),agentId:E}).strict(),i.object({op:i.literal("legacy.agent.conversation.clear"),agentId:E}).strict(),i.object({op:i.literal("legacy.agent.systemPrompt.get"),agentId:E}).strict(),i.object({op:i.literal("legacy.agent.systemPrompt.update"),agentId:E,systemPrompt:i.string().max(Mv)}).strict(),i.object({op:i.literal("legacy.agent.download"),agentId:E}).strict(),i.object({op:i.literal("legacy.job.cancel"),jobId:E}).strict(),i.object({op:i.literal("commands.list")}).strict(),i.object({op:i.literal("commands.entities"),sessionId:B,command:E,name:i.string().max(128).optional()}).strict(),i.object({op:i.literal("models.catalogue"),live:i.boolean().optional(),scope:i.enum(["usable","all"]).optional()}).strict(),i.object({op:i.literal("usage.get"),provider:E.optional(),live:i.boolean().optional(),refresh:i.boolean().optional()}).strict(),i.object({op:i.literal("usage.reset"),provider:E,credentialRef:kv.optional(),identity:i.string().min(1).max(256).optional(),redeemRequestId:i.string().uuid()}).strict(),i.object({op:i.literal("quota.notice"),provider:E.optional(),model:i.string().min(1).max(200).optional(),refresh:i.boolean().optional()}).strict(),i.object({op:i.literal("analytics.get"),sessionId:B.optional(),sinceMs:i.number().int().nonnegative().optional(),untilMs:i.number().int().nonnegative().optional(),days:i.number().int().min(1).max(366).optional()}).strict(),i.object({op:i.literal("analytics.models"),sessionId:B.optional(),sinceMs:i.number().int().nonnegative().optional(),untilMs:i.number().int().nonnegative().optional(),days:i.number().int().min(1).max(366).optional()}).strict(),i.object({op:i.literal("info.get")}).strict(),i.object({op:i.literal("sessions.report"),sessionId:B,recentLimit:i.number().int().min(0).max(50).optional()}).strict(),i.object({op:i.literal("skills.list"),sessionId:B.optional(),cwd:Ev.optional(),name:Vr.optional()}).strict(),i.object({op:i.literal("skills.create"),requestId:ue,name:Vr,copyFrom:Vr}).strict(),i.object({op:i.literal("skills.update"),requestId:ue,name:Vr,expectedFingerprint:i.string().regex(/^[a-f0-9]{64}$/),files:i.array(i.object({path:i.string().min(1).max(240),content:i.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),i.object({op:i.literal("skills.remove"),requestId:ue,name:Vr,discardLocalChanges:i.boolean()}).strict(),i.object({op:i.literal("sessions.failovers"),sessionId:B}).strict(),i.object({op:i.literal("sessions.credential"),sessionId:B,action:i.enum(["list","store","forget"]),key:cs.optional(),value:ls.optional(),confirmed:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.fork"),sessionId:B,requestId:ue,message:i.string().max(2e5).optional(),boundary:i.enum(["next_safe","at_entry"]).optional(),entryId:i.string().max(128).optional(),autoTag:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.stop"),requestId:ue,targets:i.array(B).min(1).max(100),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside"),sessionId:B,requestId:ue,text:i.string().min(1).max(32768),asideId:ue.optional(),subscriptionId:i.string().regex(xd).optional()}).strict(),i.object({op:i.literal("sessions.adopt"),sessionId:B,requestId:ue,asideId:ue,confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside.get"),sessionId:B,asideId:ue}).strict(),i.object({op:i.literal("sessions.aside.close"),sessionId:B,asideId:ue}).strict(),i.object({op:i.literal("wakes.list"),limit:i.number().int().min(1).max(500).optional(),includeDormant:i.boolean().optional()}).strict(),i.object({op:i.literal("wakes.create"),requestId:ue,sessionId:B.optional(),cwd:i.string().min(1).max(4096).optional(),target:us.optional(),message:Bd,in:i.string().min(1).max(64).optional(),at:i.string().min(1).max(64).optional(),every:i.string().min(1).max(64).optional(),until:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).optional(),title:i.string().min(1).max(200).optional()}).strict(),i.object({op:i.literal("wakes.edit"),sessionId:B,wakeId:Hd,message:Bd.optional(),in:i.string().min(1).max(64).optional(),at:i.string().min(1).max(64).optional(),every:i.string().min(1).max(64).optional(),until:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).optional()}).strict(),i.object({op:i.literal("wakes.remove"),sessionId:B,wakeId:Hd}).strict(),i.object({op:i.literal("monitors.cancel"),sessionId:B,monitorId:Uv}).strict(),i.object({op:i.literal("jobs.cancel"),sessionId:B,jobId:Bv}).strict(),i.object({op:i.literal("mcp.list"),sessionId:B}).strict(),i.object({op:i.literal("mcp.credentials.store"),sessionId:B,name:i.string().min(1).max(256),values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("mcp.control"),sessionId:B,control:i.object({action:i.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:Hi.optional(),scope:i.enum(["global","project"]).optional(),command:i.string().min(1).max(4096).optional(),args:i.array(i.string().max(8192)).max(128).optional(),env:i.record(ds).optional(),url:i.string().max(4096).optional(),headers:i.record(ds).optional(),oauth:i.boolean().optional(),confirmed:i.boolean().optional(),operation_id:Rd.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog"),cwd:Wi.optional(),sessionId:B.optional()}).strict(),i.object({op:i.literal("mcp.catalog.control"),cwd:Wi.optional(),control:i.object({action:i.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:Hi.optional(),scope:i.enum(["global","project"]).optional(),command:i.string().min(1).max(4096).optional(),args:i.array(i.string().max(8192)).max(128).optional(),env:i.record(ds).optional(),url:i.string().max(4096).optional(),headers:i.record(ds).optional(),confirmed:i.boolean().optional(),operation_id:Rd.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog.credentials"),header:i.string().min(1).max(128).optional(),cwd:Wi.optional(),name:Hi,values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("radient.request"),control:i.object({operation:i.enum(["account","prices","credits","usage","provision","application.create","agents.list","agents.get","agents.create","agents.update","agents.delete","agents.like","agents.unlike","agents.liked","agents.like_count","agents.favourite","agents.unfavourite","agents.favourited","agents.favourite_count","agents.download_count","agents.statuses","comments.list","comments.create","comments.update","comments.delete","account.agents","memberships.list","org_agents.list","org_team.get","org_teams.list","org_skills.list","org_skill.get","signup.resend","team_trial.eligibility","team_trial.start","team_trial.status"]),request_id:ue.optional(),tenant_id:E.optional(),account_id:E.optional(),agent_id:E.optional(),comment_id:E.optional(),team_id:E.optional(),skill_id:E.optional(),query:i.record(i.union([i.string().max(1024),i.number().int()])).optional(),payload:i.record(i.unknown()).optional(),confirmed:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("providers.list")}).strict(),i.object({op:i.literal("accounts.list")}).strict(),i.object({op:i.literal("accounts.remove"),accountId:i.number().int().positive(),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("tunnel.setup.read"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.plan"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.run"),credentialId:i.number().int().positive(),acceptMonthlyPrice:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("auth.start"),provider:E}).strict(),i.object({op:i.literal("auth.status"),id:E}).strict(),i.object({op:i.literal("auth.input"),id:E,promptId:E,value:ls}).strict(),i.object({op:i.literal("auth.cancel"),id:E}).strict(),i.object({op:i.literal("auth.key"),provider:E,value:ls}).strict(),i.object({op:i.literal("auth.logout"),provider:E}).strict(),i.object({op:i.literal("agent_messages.status"),boundary:Ed}).strict(),i.object({op:i.literal("agent_messages.enable"),expected_account_id:E,tenant_id:E,state:i.literal("active"),consent_version:i.string().min(1).max(128),consented_via:i.literal("dialog")}).strict(),i.object({op:i.literal("agent_messages.settings"),tenant_id:E.optional()}).strict(),i.object({op:i.literal("agent_messages.settings.put"),expected_account_id:E,tenant_id:E.optional(),consent_version:i.string().min(1).max(128).optional(),consented_via:i.enum(["dialog","settings"]).optional(),label:i.string().min(1).max(128).optional(),state:i.enum(["active","paused","disabled"])}).strict(),i.object({op:i.literal("agent_messages.onboarding.dismiss")}).strict(),i.object({op:i.literal("agent_messages.allowlist.get"),tenant_id:E.optional()}).strict(),i.object({op:i.literal("agent_messages.allowlist.put"),expected_account_id:E,tenant_id:E.optional(),entries:i.array(i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:i.object({endpoint_id:E.optional(),account_id:E.optional()}).strict().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id")}).strict()).max(200)}).strict(),i.object({op:i.literal("team_bridge.conversations.list"),scope:i.literal("account").optional(),tenant_id:E.optional(),limit:i.number().int().min(1).max(100).optional(),cursor:i.string().min(1).max(512).optional(),before:i.string().min(1).max(64).optional(),status:i.enum(["open","archived"]).optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.get"),conversation_id:E,tenant_id:E.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.create"),expected_account_id:E.optional(),tenant_id:E.optional(),kind:i.enum(["dm","group","channel"]),name:i.string().min(1).max(128).optional(),topic:i.string().min(1).max(512).optional(),visibility:i.enum(["private","tenant"]).optional(),agent_capable:i.boolean().optional(),members:i.array(i.object({account_id:E,kind:i.enum(["human","agent"]),endpoint_id:E.optional(),display_label:i.string().min(1).max(64)}).strict()).max(500)}).strict(),i.object({op:i.literal("team_bridge.conversations.lifecycle"),expected_account_id:E.optional(),tenant_id:E.optional(),conversation_id:E,action:i.enum(["archive","unarchive","join","leave"])}).strict(),i.object({op:i.literal("team_bridge.conversations.join"),expected_account_id:E.optional(),conversation_id:E,tenant_id:E.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.leave"),expected_account_id:E.optional(),conversation_id:E,tenant_id:E.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.notify"),expected_account_id:E.optional(),conversation_id:E,tenant_id:E.optional(),notify:i.enum(["all","mention","mute"])}).strict(),i.object({op:i.literal("team_bridge.conversations.agent_notify"),expected_account_id:E.optional(),conversation_id:E,tenant_id:E.optional(),notify:i.enum(["all","mention","mute"])}).strict(),i.object({op:i.literal("team_bridge.conversations.members.add"),expected_account_id:E.optional(),conversation_id:E,tenant_id:E.optional(),members:i.array(i.object({account_id:E,kind:i.enum(["human","agent"]),endpoint_id:E.optional(),display_label:i.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),i.object({op:i.literal("team_bridge.conversations.members.remove"),expected_account_id:E.optional(),tenant_id:E.optional(),conversation_id:E,account_id:E}).strict(),i.object({op:i.literal("team_bridge.conversations.delete"),expected_account_id:E.optional(),tenant_id:E.optional(),conversation_id:E}).strict(),i.object({op:i.literal("team_bridge.conversations.consent"),expected_account_id:E.optional(),conversation_id:E,account_id:E,decision:i.enum(["accept","decline","withdraw"]),consent_version:i.string().min(1).max(128).optional(),endpoint_id:E.optional(),tenant_id:E.optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.conversations"),expected_account_id:E,tenant_id:E,limit:i.number().int().min(1).max(100).optional(),cursor:i.string().min(1).optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.messages"),expected_account_id:E,tenant_id:E,conversation_id:E,limit:i.number().int().min(1).max(100).optional(),before_seq:i.number().int().nonnegative().optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.replies"),expected_account_id:E,tenant_id:E,conversation_id:E,message_id:E,limit:i.number().int().min(1).max(100).optional(),after_seq:i.number().int().nonnegative().optional(),before_seq:i.number().int().positive().optional(),order:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("team_bridge.messages.list"),conversation_id:E,tenant_id:E.optional(),limit:i.number().int().min(1).max(100).optional(),before_seq:i.number().int().nonnegative().optional(),endpoint_id:E.optional()}).strict(),i.object({op:i.literal("team_bridge.typing.get"),conversation_id:E,tenant_id:E}).strict(),i.object({op:i.enum(["team_bridge.typing.set","team_bridge.typing.clear"]),conversation_id:E,tenant_id:E,expected_account_id:E,thread_root_id:E.optional()}).strict(),i.object({op:i.literal("agent_messages.settings.share_typing"),expected_account_id:E,share_typing:i.boolean()}).strict(),i.object({op:i.literal("team_bridge.reactions.toggle"),conversation_id:E,message_id:E,expected_account_id:E,tenant_id:E,emoji:i.string().min(1),active:i.boolean()}).strict(),i.object({op:i.literal("team_bridge.messages.send"),expected_account_id:E.optional(),conversation_id:E,tenant_id:E.optional(),client_ref:E,body:i.string(),agent_label:i.string().min(1).max(64).optional(),thread_root_id:E.optional(),attachment_ids:zi.optional(),files:i.array(E).min(1).max(10).refine(e=>new Set(e).size===e.length,"Duplicate file").optional(),mentions:Dv.optional()}).strict(),i.object({op:i.literal("team_bridge.messages.replies"),conversation_id:E,message_id:E,expected_account_id:E,tenant_id:E,limit:i.number().int().min(1).max(100).optional(),after_seq:i.number().int().nonnegative().optional(),before_seq:i.number().int().positive().optional(),order:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("team_bridge.scheduled.list"),tenant_id:E}).strict(),i.object({op:i.literal("team_bridge.scheduled.create"),tenant_id:E,conversation_id:E,client_ref:E,body:i.string(),send_at:i.string().datetime({offset:!0}),attachment_ids:zi.optional(),thread_root_id:E.optional()}).strict(),i.object({op:i.literal("team_bridge.scheduled.update"),tenant_id:E,scheduled_id:E,body:i.string().optional(),send_at:i.string().datetime({offset:!0}).optional(),attachment_ids:zi.optional(),expected_version:i.number().int().nonnegative().optional()}).strict(),i.object({op:i.literal("team_bridge.attachments.delete"),tenant_id:E,conversation_id:E,attachment_id:E,expected_account_id:E}).strict(),i.object({op:i.literal("team_bridge.scheduled.cancel"),tenant_id:E,scheduled_id:E}).strict(),i.object({op:i.literal("team_bridge.read"),expected_account_id:E.optional(),conversation_id:E,tenant_id:E.optional(),seq:i.number().int().nonnegative().optional(),muted:i.boolean().optional()}).strict(),i.object({op:i.literal("team_bridge.thread_read"),expected_account_id:E,conversation_id:E,message_id:E,tenant_id:E,seq:i.number().int().nonnegative()}).strict(),i.object({op:i.literal("team_bridge.unread"),scope:i.literal("account").optional(),tenant_id:E.optional()}).strict(),i.object({op:i.literal("team_bridge.directory"),tenant_id:E}).strict(),i.object({op:i.literal("team_bridge.status"),boundary:Ed.optional()}).strict(),i.object({op:i.literal("team_bridge.link_preview.resolve"),url:i.string().min(1).max(bv),index:i.number().int().nonnegative(),expectedAccountId:E}).strict(),i.object({op:i.literal("settings.list")}).strict(),i.object({op:i.literal("settings.edit"),key:cs,value:i.unknown().refine(e=>e!==void 0,"A setting value is required."),base:Nv.optional()}).strict(),i.object({op:i.literal("settings.reset"),key:cs}).strict(),i.object({op:i.literal("tts.paths")}).strict(),i.object({op:i.literal("notification_sounds.list")}).strict(),i.object({op:i.literal("notification_sounds.rename"),id:i.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/),name:i.string().min(1).max(200)}).strict(),i.object({op:i.literal("notification_sounds.remove"),id:i.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)}).strict(),i.object({op:i.literal("config.get")}).strict(),i.object({op:i.literal("config.update"),value:Hv}).strict(),i.object({op:i.literal("instructions.get")}).strict(),i.object({op:i.literal("instructions.update"),content:i.string().max(64e3)}).strict(),i.object({op:i.literal("credentials.list")}).strict(),i.object({op:i.literal("credentials.update"),key:cs,value:ls}).strict(),i.object({op:i.literal("peers.list")}).strict(),i.object({op:i.literal("networks.list")}).strict(),i.object({op:i.literal("networks.invite"),networkId:mr,role:i.enum(["read","drive","admin"]),deviceId:mr.optional()}).strict(),i.object({op:i.literal("networks.member.remove"),networkId:mr,deviceId:mr,confirm:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("sessions.transfer"),sessionId:B,to:i.union([i.literal("local"),mr]),keep:i.boolean().optional(),waitS:i.number().min(0).max(300).optional(),requestId:ue.optional()}).strict(),i.object({op:i.literal("approvals.list")}).strict(),i.object({op:i.literal("approvals.approve"),approvalId:Zr}).strict(),i.object({op:i.literal("approvals.deny"),approvalId:Zr}).strict(),...["approvals.approveOperation","approvals.applyOperation"].map(e=>i.object({op:i.literal(e),approvalId:Zr,operation:i.literal("profile_save"),requestDigest:i.string().regex(Zs),disclosureDigest:i.string().regex(Zs)}).strict()),i.object({op:i.literal("approvals.approveCredential"),approvalId:Zr,...Cd}).strict(),i.object({op:i.literal("approvals.applyCredential"),approvalId:Zr,...Cd}).strict(),i.object({op:i.literal("asks.list")}).strict(),i.object({op:i.literal("projects.list")}).strict(),i.object({op:i.literal("projects.get"),key:En}).strict(),i.object({op:i.literal("projects.create"),name:Vi,description:i.string().max(Qd).optional(),status:Yd.optional(),tags:Jd.optional()}).strict(),i.object({op:i.literal("projects.update"),key:En,fields:i.object({name:Vi.optional(),title:i.string().max(80).optional(),owner:i.string().max(80).optional(),team:i.string().max(80).optional(),description:i.string().max(Qd).optional(),status:Yd.optional(),progress:i.string().max(ay).optional(),tags:Jd.optional(),start_date:ps.optional(),target_date:ps.optional(),completed_at:ps.optional(),estimate:i.number().positive().max(1e3).optional(),estimate_unit:i.enum(["points","days"]).optional()}).strict(),force_done:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.delete"),key:En,confirmed_name:Vi}).strict(),i.object({op:i.literal("projects.link"),key:En,sessionId:B}).strict(),i.object({op:i.literal("projects.unlink"),key:En,sessionId:B}).strict(),i.object({op:i.literal("projects.milestone"),key:En,name:i.string().min(1).max(Xd),targetDate:ps.optional(),completed:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.milestone.remove"),key:En,name:i.string().min(1).max(Xd)}).strict(),i.object({op:i.literal("projects.request_update"),key:En}).strict(),i.object({op:i.literal("projects.search"),q:i.string().min(1).max(cy),limit:i.number().int().min(1).max(dy).optional()}).strict(),i.object({op:i.literal("aida.status")}).strict(),i.object({op:i.literal("aida.control"),action:i.enum(["open","pause","resume","greet","status"])}).strict(),i.object({op:i.literal("code_requests.list"),sessionId:B}).strict(),i.object({op:i.literal("code_requests.refresh"),sessionId:B,keys:i.array(i.string().min(1).max(512)).max(256).optional(),force:i.boolean().optional()}).strict(),i.object({op:i.literal("static.sign"),route:i.enum(["images","videos","audio","html"]),path:i.string().min(1),ttlS:i.number().int().min(1).max(3600).optional()}).strict(),i.object({op:i.literal("library.list"),scope:i.enum(["final","all"]).optional(),q:i.string().max(512).optional(),category:i.string().min(1).max(64).optional(),kind:i.string().min(1).max(64).optional(),origin_group:i.enum(["generated","created","mentioned"]).optional(),origin:i.string().min(1).max(64).optional(),tag:i.string().min(1).max(128).optional(),tag_mode:i.enum(["all","any"]).optional(),highlighted:i.boolean().optional(),organized:i.boolean().optional(),favorite:i.boolean().optional(),session:i.string().min(1).max(12).optional(),session_id:i.string().min(1).max(512).optional(),sort:i.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(512).optional()}).strict(),i.object({op:i.literal("library.get"),id:Yr}).strict(),i.object({op:i.literal("library.update"),id:Yr,fields:i.object({name:i.string().max(200).optional(),description:i.string().max(2e3).optional(),favorite:i.boolean().optional(),locked:i.boolean().optional(),archived:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("library.tags")}).strict(),i.object({op:i.literal("library.tags.create"),name:i.string().trim().min(1).max(24),category:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("library.tags.update"),id:Jr,name:i.string().trim().min(1).max(24).optional(),category:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("library.tags.delete"),id:Jr}).strict(),i.object({op:i.literal("library.tags.merge"),id:Jr,into:Jr}).strict(),i.object({op:i.literal("library.tags.assign"),id:Yr,tags:i.array(Jr).max(64),primary:i.string().max(128).optional()}).strict(),i.object({op:i.literal("library.chat.link"),id:Yr,sessionId:B}).strict(),i.object({op:i.literal("library.chat.clear"),id:Yr}).strict(),i.object({op:i.literal("library.librarian"),action:i.enum(["status","open","pause","resume","run"]).optional()}).strict(),i.object({op:i.literal("sidebar_layout.get")}).strict(),i.object({op:i.literal("sidebar_layout.set"),layout:fy}).strict(),i.object({op:i.literal("notifications.list"),preview:i.literal(!0).optional(),includeAskReads:i.boolean().optional(),countSessionIds:i.array(B).max(50).optional(),kind:i.enum(["all","asks","updates"]).optional(),bulkPriority:i.enum(["any","high","normal_up"]).optional(),state:i.enum(["unread","all","dismissed"]).optional(),source:i.enum(["notify","ask"]).optional(),priority:i.enum(["high","normal","low"]).optional(),sessionId:B.optional(),throughSeq:i.number().int().min(0).optional(),cursor:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("notifications.get"),id:dn}).strict(),i.object({op:i.literal("notifications.count")}).strict(),i.object({op:i.literal("notifications.read"),verb:i.enum(["read","unread","undo"]),target:i.union([tu,eu,py])}).strict(),i.object({op:i.literal("notifications.dismiss"),verb:i.enum(["dismiss","undismiss"]),target:i.union([tu,eu])}).strict(),i.object({op:i.literal("notifications.seen"),items:i.array(i.object({id:dn,revision:i.number().int().min(1),anchorId:i.string().min(1).max(256),visibleSinceMs:i.number().int().min(0)}).strict()).min(1).max(50),evidence:i.object({sessionId:B,inputKind:i.enum(["pointer","key","wheel"]),inputAtMs:i.number().int().min(0),visibleSinceMs:i.number().int().min(0)}).strict()}).strict()]);my.superRefine((e,t)=>{if(e.op==="usage.reset"&&!e.credentialRef&&!e.identity&&t.addIssue({code:i.ZodIssueCode.custom,message:"A usage reset must name an account: send `credentialRef` or `identity`.",path:["credentialRef"]}),e.op==="team_bridge.conversations.consent"&&e.decision==="withdraw"!=(e.consent_version===void 0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"accept and decline require consent_version; withdraw carries none",path:["consent_version"]}),(e.op==="notifications.read"||e.op==="notifications.dismiss")&&"items"in e.target&&!!e.target.receipt!=(e.target.throughSeq!==void 0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"Receipt writes require a sequence boundary",path:["target"]}),e.op==="notifications.read"&&e.verb==="undo"!="operationToken"in e.target&&t.addIssue({code:i.ZodIssueCode.custom,message:"Undo requires an operation token, and only undo accepts one",path:["target"]}),e.op==="team_bridge.messages.send"&&e.files){const n=e.attachment_ids??[];(n.length+e.files.length>10||e.files.some(r=>n.includes(r)))&&t.addIssue({code:i.ZodIssueCode.custom,message:"Invalid combined attachment set",path:["files"]})}if((e.op==="team_bridge.messages.send"||e.op==="team_bridge.scheduled.create"||e.op==="team_bridge.scheduled.update"&&e.body!==void 0)&&e.body?.trim()===""&&(e.attachment_ids?.length??0)===0&&!(e.op==="team_bridge.messages.send"&&e.files?.length)){t.addIssue({code:i.ZodIssueCode.custom,message:"A message needs text or an image",path:["body"]});return}if(e.op.startsWith("team_bridge.")&&"expected_account_id"in e&&e.expected_account_id&&(!("tenant_id"in e)||!e.tenant_id)){t.addIssue({code:i.ZodIssueCode.custom,path:["tenant_id"],message:"Guarded conversation writes require an explicit tenant"});return}if(e.op==="team_bridge.messages.send"&&e.thread_root_id!==void 0&&!e.expected_account_id){t.addIssue({code:i.ZodIssueCode.custom,path:["expected_account_id"],message:"Thread replies require the captured account"});return}if(e.op==="hub.skillPull"||e.op==="hub.skillSubscribe"||e.op==="hub.skillPublish"){if(e.visibility==="public"&&e.tenantId!==null||e.visibility==="org"&&!e.tenantId){t.addIssue({code:i.ZodIssueCode.custom,message:"A skill destination requires explicit paired scope",path:["tenantId"]});return}if(e.op==="hub.skillPublish"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:i.ZodIssueCode.custom,message:"An initial skill publication requires its reviewed draft receipt",path:["previewReceipt"]});return}}if(e.op==="hub.check"||e.op==="hub.apply"||e.op==="hub.retry"){const n=e.name!==void 0,r=e.localId!==void 0,o=e.op!=="hub.check";if(n&&r||o&&!n&&!r||r&&e.kind===void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"A hub action addresses one item by name or local id, never both",path:["localId"]});return}}if(e.op==="hub.apply"&&e.resolveSource===!0){const n=e.visibility==="public"&&e.tenantId===null||e.visibility==="org"&&typeof e.tenantId=="string"&&e.tenantId.length>0;if(!e.hubSource||!n||e.acknowledgeUnknownBaseline!==!0||e.localId!==void 0||e.prefer!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"Confirming a source requires its exact stated destination and the unknown-baseline acknowledgement, addressed by name, with no preference",path:["hubSource"]});return}}if(e.op==="hub.push"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:i.ZodIssueCode.custom,message:"A confirmed publication requires its reviewed preview receipt",path:["previewReceipt"]});return}if(e.op==="hub.policy"&&e.subscribe===void 0&&e.autoPush===void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"A hub policy change must name subscribe or autoPush",path:["subscribe"]});return}if((e.op==="team_bridge.conversations.list"||e.op==="team_bridge.unread")&&e.scope==="account"&&e.tenant_id!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"An account-scoped read cannot name a tenant",path:["scope"]});return}if(e.op==="team_bridge.conversations.list"&&e.scope==="account"&&e.before!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"An account-scoped page uses cursor, not before",path:["before"]});return}if(e.op==="sessions.answer"){if(e.askId!==void 0){if(e.askId||t.addIssue({code:i.ZodIssueCode.custom,message:"ask_id must be a non-empty string",path:["askId"]}),e.dismiss===!0){(e.answers!==void 0||e.decline===!0||e.revise===!0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:i.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:i.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:i.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:i.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:i.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:i.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:i.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:i.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:i.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"reason applies to a queued ask",path:["reason"]});return}if(e.op==="sessions.create"&&e.purpose===void 0){e.cwd===void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"A conversation needs a working directory: only a configuration run (`purpose`) may omit `cwd`.",path:["cwd"]});return}if(e.op==="sessions.create"&&e.purpose!==void 0){for(const n of["cwd","target","model","draftId"])e[n]!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:`A configuration run resolves its own \`${n}\`: send \`purpose\` alone.`,path:[n]});return}if(!(e.op!=="agent.publish"&&e.op!=="agent.republish"&&e.op!=="team.publish")){if((e.subscribe!==void 0||e.autoPush!==void 0||e.confirmPublicEgress!==void 0)&&!e.requestId){t.addIssue({code:i.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:i.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const Ue={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed",serverUpdating:"transient.server-updating"},Cp="service is preparing a safe reload; retry shortly",Op="serve_reloading";function gy(e,t){if(e!==503||t===null||typeof t!="object")return!1;const n=t.detail;return n===Cp?!0:n!==null&&typeof n=="object"&&n.code===Op}function _y(e){return e!==null&&typeof e=="object"&&e.updating===!0}function by(e){return e!==null&&typeof e=="object"&&e.update_stalled===!0}const vy={runtimeUnreachable:"runtime_unreachable"},mi="runtime_busy",Pp="runtime_retiring";i.object({data:i.object({aside_id:i.string().optional(),status:i.union([i.enum(["adopted","queued"]),i.string()]).optional()}).passthrough()}).passthrough();const Mp=i.object({name:i.string(),description:i.string().nullish(),source:i.string().nullish(),link_id:i.string().nullish(),editable:i.boolean().nullish(),installed:i.boolean().nullish(),fingerprint:i.string().nullish(),form:i.string().nullish()}).passthrough(),yy=i.object({path:i.string(),size:i.number().nullish(),preview:i.string().nullish(),preview_truncated:i.boolean().nullish()}).passthrough(),wy=Mp.extend({body:i.string().nullish(),body_in_detail:i.boolean().nullish(),body_length:i.number().nullish(),body_bytes:i.number().nullish(),body_truncated:i.boolean().nullish(),files:i.array(yy).nullish(),files_total:i.number().nullish(),files_truncated:i.boolean().nullish(),publish_budget:i.object({limit:i.number(),total:i.number()}).passthrough().nullish()}).passthrough(),yP=i.object({skills:i.array(Mp),scope:i.string().nullish(),detail:i.string().nullish(),skill_detail:wy.nullish(),warning_count:i.number().nullish(),version:i.string().nullish()}).passthrough(),wP=i.object({reset:i.object({outcome:i.union([i.enum(["reset","already_redeemed","no_credit","nothing_to_reset","failed","refused"]),i.string()]),windows_reset:i.number().int().nonnegative(),detail:i.string().default(""),refused:i.boolean()}).passthrough(),usage:i.object({reports:i.array(i.record(i.unknown())),source:i.string(),fetched_at:i.number()}).passthrough().nullish()}).passthrough(),kP="aside_adopt_refused",ky=["session_closed","open_tool_batch","turn_running"];function SP(e){if(typeof e!="object"||e===null)return;const t=e.reason;return ky.find(n=>n===t)}const Sy={[Ue.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[Ue.refused]:"ui.common.errors.desktop_refusal.refused",[Ue.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[Ue.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed",[Ue.serverUpdating]:"ui.common.errors.desktop_refusal.server_updating"},Ba={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 gi(e){return e!==void 0&&Object.values(Ue).includes(e)}function Ey(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return Ue.refused;if(t===503)return Ue.planeClosed}}const EP=i.object({step:i.string(),blocked_on:i.string(),configured:i.boolean(),ready:i.boolean(),verified:i.boolean(),url:i.string().nullable(),credential_id:i.number().int().positive().nullable(),identity_label:i.string().nullable(),credential_choices:i.array(i.object({id:i.number().int().positive(),identity_label:i.string().nullable().optional()}).passthrough()).default([]),quote:i.object({monthly_price_usd:i.string().nullable(),positive_balance:i.boolean(),eligible:i.boolean(),account_valid:i.boolean()}).passthrough().nullable(),receipts:i.array(i.object({step:i.string(),ok:i.boolean(),text:i.string()})).default([]),remedy:i.object({kind:i.string(),text:i.string(),command:i.string().nullable().optional(),url:i.string().nullable().optional()}).nullable(),source:i.string(),in_progress:i.boolean().default(!1),progress:i.array(i.string()).default([]),active_credential_id:i.number().int().positive().nullable().default(null),billing_outcome:i.string().optional(),reservation_outcome:i.string().optional(),failure_stage:i.string().optional(),transport:i.string().optional()}).passthrough();function AP(e){return e.transport!=="relay"?!1:e.blocked_on==="cloudflared"||e.remedy?.kind==="install_cloudflared"}const IP=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),Ay=88e4,Iy=11e5,Ry=2e4,xy=9e4,Ty=new Set(["analytics.get","analytics.models","sessions.report"]),Cy=new Set(["usage.get"]),Oy=new Set(["networks.list","peers.list"]),Py=new Set(["usage.reset"]),My=new Set([...Ty,...Cy,...Oy,...Py]),jy=90,$y=30,Ny=300,Dy=10,jp=15,Ly=1e4;function Fy(e){const n=e.to==="local"||e.keep?Ny:$y,r=Math.max(0,e.waitS??0);return(jy+n+Dy+jp)*1e3+r*1e3}const Uy=18e4,By=Uy+15e3,Hy=120,Wy=135e3,Gy=93e4,$p=(Hy+30+jp)*1e3,zy=6e4,Ky=5*$p,Vy=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function Zy(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 $p;case"hub.check":return zy;case"hub.applyAll":return Ky;default:return null}}function Yy(e){if(typeof e!="string"&&e.op==="sessions.transfer")return Fy(e)+Ly;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return By;if(t==="tunnel.setup.run")return Gy;if(t==="tunnel.setup.plan")return Wy;const n=Zy(t);return n!==null?n:My.has(t)?xy:Ry}const Jy=5e3;function Np(e){return Yy(e)+Jy}const Gc="deadline_exceeded",Dp="foreground_required",Lp="View these completions in the foreground before marking them read.",Qy=new Set(["capabilities","agent_messages.status","agent_messages.settings","agent_messages.allowlist.get","team_bridge.conversations.list","team_bridge.conversations.get","team_bridge.messages.list","team_bridge.messages.replies","team_bridge.owner_audit.conversations","team_bridge.owner_audit.messages","team_bridge.owner_audit.replies","team_bridge.unread","team_bridge.directory","team_bridge.status","accounts.list","analytics.get","analytics.models","approvals.list","commands.entities","commands.list","config.get","credentials.list","hub.updates","hub.links","info.get","instructions.get","legacy.agent.get","legacy.agent.history","legacy.agent.schedules.list","legacy.agents.list","legacy.job.get","legacy.jobs.list","legacy.models","legacy.models.providers","legacy.schedule.get","legacy.schedules.list","mcp.catalog","mcp.list","models.catalogue","networks.list","peers.list","profiles.get","profiles.list","projects.search","providers.list","quota.notice","runtimes.list","sessions.aside.get","sessions.checkpoints","sessions.failovers","sessions.find","sessions.get","sessions.history","sessions.files","sessions.userAttachments","sessions.list","sessions.preview","sessions.report","sessions.search","sessions.variables.list","skills.list","subagents.transcript","teams.effective","teams.get","teams.list","tunnel.setup.plan","tunnel.setup.read","usage.get"]),Xy=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function qy(e,t){const n=Math.round(t/1e3),r=Gc;return e==="sessions.transfer"?{code:r,message:`The app waits up to ${n} seconds for a move, and it was still running when the app stopped waiting. The move was asked for, so its outcome is unknown from here: read the session again before moving it anywhere else.`}:e==="approvals.approve"||e==="approvals.approveCredential"?{code:r,message:`The app waits up to ${n} seconds for an approval, and the signing prompt was still open when it stopped waiting. The request was sent, so the decision may or may not have landed: read the approvals again — if the record still waits, answering it again is safe, because the store keeps the first decision and refuses a second.`}:Vy.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:Qy.has(e)?{code:r,message:Xy.has(e)?`The app waits up to ${n} seconds for this panel's data, and the read was still running when the app stopped waiting. Nothing was read; reopen the panel to ask again.`:`The app waits up to ${n} seconds for this read, and it was still running when the app stopped waiting. Nothing was read; ask again.`}:{code:r,message:`The app waits up to ${n} seconds for this request, and it was still running when the app stopped waiting. It may or may not have reached the server; check the result before repeating it.`}}const RP=Ay,xP=Iy;i.object({state:i.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:i.string(),kind:i.enum(["balance","subscription","radient","none"]),model_free:i.boolean(),title:i.string(),body:i.string(),actions:i.array(i.object({id:i.enum(["open_url","resend_verification","refresh"]),label:i.string(),url:i.string().nullable().optional()})),resets_at_ms:i.number().int().nullable().optional(),checked_at_ms:i.number().int(),age_ms:i.number().int().nullable().optional(),source:i.enum(["cached","live"])});function ew(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function nu(e){return{...e.in!==void 0?{in:e.in}:{},...e.at!==void 0?{at:e.at}:{},...e.every!==void 0?{every:e.every}:{},...e.until!==void 0?{until:e.until}:{},...e.limit!==void 0?{limit:e.limit}:{}}}function Yi(e){return{...e.requestId?{request_id:e.requestId}:{},...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}}function Ji(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 ru(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 Qr(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 ms(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function tw(e){switch(e.op){case"capabilities":return{path:"/v1/capabilities",method:"GET"};case"runtimes.list":return{path:"/v1/desktop/runtimes?probe=false",method:"GET"};case"peers.list":return{path:"/v1/desktop/peers",method:"GET"};case"networks.list":return{path:"/v1/desktop/networks",method:"GET"};case"asks.list":return{path:"/v1/desktop/asks",method:"GET"};case"networks.invite":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/invite`,method:"POST",body:{role:e.role,device:e.deviceId??null}};case"networks.member.remove":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/members/${encodeURIComponent(e.deviceId)}`,method:"DELETE",body:{confirm:e.confirm}};case"sessions.transfer":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/transfer`,method:"POST",body:{to:e.to,keep:e.keep??!1,wait_s:e.waitS??0,...e.requestId?{request_id:e.requestId}:{}}};case"approvals.list":return{path:"/v1/desktop/approvals",method:"GET"};case"approvals.approve":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/approve`,method:"POST"};case"approvals.deny":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/deny`,method:"POST"};case"approvals.approveOperation":case"approvals.applyOperation":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveOperation"?"approve-operation":"apply-operation"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"approvals.approveCredential":case"approvals.applyCredential":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveCredential"?"approve-credential":"apply-credential"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"profiles.list":return{path:"/v1/desktop/profiles",method:"GET"};case"profiles.get":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"GET"};case"profiles.install":return{path:"/v1/desktop/profiles/install",method:"POST",body:{request_id:e.requestId,name:e.name}};case"imports.sources":return{path:"/v1/desktop/imports/sources",method:"GET"};case"imports.sessions":{const t=new URLSearchParams({source:e.source});return e.includeSubagents&&t.set("include_subagents","true"),{path:`/v1/desktop/imports/sessions?${t.toString()}`,method:"GET"}}case"imports.preview":return{path:"/v1/desktop/imports/preview",method:"POST",body:ru(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:ru(e)};case"imports.status":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"GET"};case"imports.cancel":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"DELETE"};case"profiles.create":return{path:"/v1/desktop/profiles",method:"POST",body:{request_id:e.requestId,name:e.name,...e.fields}};case"profiles.update":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"hub.updates":return{path:"/v1/desktop/hub/updates",method:"GET"};case"hub.skillPull":return{path:"/v1/desktop/hub/skills/pull",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.adoptionStrategy!==void 0?{adoption_strategy:e.adoptionStrategy}:{},...e.allowLlm!==void 0?{allow_llm:e.allowLlm}:{},...e.confirm!==void 0?{confirm:e.confirm}:{},...e.adoptionReceipt!==void 0?{adoption_receipt:e.adoptionReceipt}:{}}};case"hub.skillSubscribe":return{path:"/v1/desktop/hub/skills/subscribe",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias}};case"hub.skillUnpull":return{path:"/v1/desktop/hub/skills/unpull",method:"POST",body:{request_id:e.requestId,link_id:e.linkId}};case"hub.skillPublish":return{path:"/v1/desktop/hub/skills/publish",method:"POST",body:{request_id:e.requestId,dry_run:e.dryRun,source_skill:e.sourceSkill,local_alias:e.localAlias,visibility:e.visibility,tenant_id:e.tenantId,subscribe:e.subscribe,auto_push:e.autoPush,confirm_public_egress:e.confirmPublicEgress,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"hub.links":return{path:`/v1/desktop/hub/links${e.kind?`?kind=${e.kind}`:""}`,method:"GET"};case"hub.policy":return{path:`/v1/desktop/hub/links/${encodeURIComponent(e.linkId)}`,method:"PATCH",body:{request_id:e.requestId,expected_policy_revision:e.expectedPolicyRevision,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}};case"hub.check":return{path:"/v1/desktop/hub/updates/check",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{}}};case"hub.apply":return{path:"/v1/desktop/hub/updates/apply",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{},...e.prefer?{prefer:e.prefer}:{},...e.acknowledgeUnknownBaseline!==void 0?{acknowledge_unknown_baseline:e.acknowledgeUnknownBaseline}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.resolveSource===!0?{resolve_source:!0,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId??null}:{}}};case"hub.applyAll":return{path:"/v1/desktop/hub/updates/apply-all",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{}}};case"hub.retry":return{path:"/v1/desktop/hub/updates/retry",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{}}};case"hub.push":return{path:"/v1/desktop/hub/updates/push",method:"POST",body:{request_id:e.requestId,link_id:e.linkId,direction:e.direction,dry_run:e.dryRun,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"teams.list":return{path:"/v1/desktop/teams",method:"GET"};case"teams.get":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"GET"};case"teams.effective":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}/effective`,method:"GET"};case"teams.create":return{path:"/v1/desktop/teams",method:"POST",body:{request_id:e.requestId,...e.fields}};case"teams.update":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"sessions.list":{const t=new URLSearchParams;return t.set("limit",String(e.limit??100)),e.include_archived&&t.set("include_archived","true"),e.scope_kind&&t.set("scope_kind",e.scope_kind),e.scope_name&&t.set("scope_name",e.scope_name),e.cursor&&t.set("cursor",e.cursor),e.with_counts&&t.set("with_counts","true"),e.include_peers&&t.set("include_peers","true"),e.sort&&t.set("sort",e.sort),{path:`/v1/desktop/sessions?${t}`,method:"GET"}}case"delegated_cleanup_notice.ack":return{path:"/v1/desktop/delegated-cleanup-notice/ack",method:"POST"};case"sessions.search":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??Tv)});return e.include_archived&&t.set("include_archived","true"),{path:`/v1/desktop/sessions/search?${t}`,method:"GET"}}case"sessions.archive":return{path:`/v1/desktop/sessions/${e.sessionId}/archive`,method:"POST",body:{archived:e.archived}};case"sessions.delete":return{path:`/v1/desktop/sessions/${e.sessionId}`,method:"DELETE",body:{confirmed:!0}};case"sessions.create":return{path:"/v1/desktop/sessions",method:"POST",body:{request_id:e.requestId,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.peer?{peer:e.peer}:{},...e.target?{target:e.target}:{},...e.model?{model:e.model}:{},...e.draftId?{draft_id:e.draftId}:{},...e.purpose?{purpose:e.purpose}:{}}};case"sessions.preview":return{path:"/v1/desktop/sessions/preview",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.draft":return{path:"/v1/desktop/sessions/draft",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.get":{const t=new URLSearchParams;return e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),Vs(t,`/v1/desktop/sessions/${e.sessionId}`,e.orderIds??[])),{path:`/v1/desktop/sessions/${e.sessionId}${t.size?`?${t}`:""}`,method:"GET"}}case"sessions.files":{const t=new URLSearchParams({limit:String(e.limit??200)});for(const n of["scope","kind","q","sort","order","cursor"]){const r=e[n];r!==void 0&&t.set(n,r)}return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files?${t}`,method:"GET"}}case"sessions.files.materialise":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files/${encodeURIComponent(e.fileId)}/materialise`,method:"POST"};case"sessions.userAttachments":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/user-attachments`,method:"GET"};case"sessions.userAttachments.materialise":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/user-attachments/${encodeURIComponent(e.digest)}/materialise`,method:"POST"};case"sessions.history":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.openFrame&&(t.set("open_frame","1"),t.set("supplements","1")),e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),e.sourceRead==="metadata"?t.set("source_read","metadata"):e.sourceRead==="payload"&&e.expectedJournalGeneration&&t.set("source_read","payload"),e.expectedJournalGeneration&&t.set("expected_journal_generation",e.expectedJournalGeneration),Vs(t,`/v1/desktop/sessions/${e.sessionId}/history`,e.orderIds??[])),{path:`/v1/desktop/sessions/${e.sessionId}/history?${t}`,method:"GET"}}case"sessions.checkpoints":return{path:`/v1/desktop/sessions/${e.sessionId}/checkpoints`,method:"GET"};case"sessions.checkpoints.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/checkpoints/warm`,method:"POST",body:{...e.ids?{ids:e.ids}:{},...e.limit!==void 0?{limit:e.limit}:{}}};case"sessions.find":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??Ov)});return{path:`/v1/desktop/sessions/${e.sessionId}/find?${t}`,method:"GET"}}case"subagents.transcript":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.entryId&&t.set("entry_id",e.entryId),{path:`/v1/desktop/sessions/${e.sessionId}/children/${e.childId}/transcript?${t}`,method:"GET"}}case"sessions.message":return{path:`/v1/desktop/sessions/${e.sessionId}/messages`,method:"POST",body:{request_id:e.requestId,text:e.text,images:e.images??[],...e.files?.length?{files:e.files}:{},mode:e.mode??"prompt",...e.inputMode?{input_mode:e.inputMode}:{},...e.inputPath?{input_path:e.inputPath}:{}}};case"sessions.command":return{path:`/v1/desktop/sessions/${e.sessionId}/commands`,method:"POST",body:{request_id:e.requestId,command:e.command,args:e.args??"",images:e.images??[]}};case"sessions.profileActionStatus":return{path:`/v1/desktop/sessions/${e.sessionId}/profile-action-status`,method:"POST",body:{action_id:e.actionId,receipt_id:e.receiptId,profile_kind:e.profileKind,profile_name:e.profileName,tool_call_id:e.toolCallId}};case"sessions.answer":return e.askId!==void 0?{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{ask_id:e.askId,answers:e.answers,decline:e.decline,...e.revise===!0?{revise:!0}:{},...e.dismiss===!0?{dismiss:!0,...e.reason!==void 0?{reason:e.reason}:{}}:{}}}:{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{epoch:e.epoch,request_id:e.requestId,value:e.value,approved:e.approved,question_index:e.questionIndex}};case"sessions.seen":return{path:`/v1/desktop/sessions/${e.sessionId}/seen`,method:"POST",body:{completion_token:e.completionToken}};case"attention.seen":return{path:"/v1/desktop/attention/seen",method:"POST",body:{items:e.items.map(t=>({session_id:t.sessionId,completion_token:t.completionToken}))}};case"sessions.notified":return{path:`/v1/desktop/sessions/${e.sessionId}/notified`,method:"POST",body:{completion_token:e.completionToken}};case"tags.list":return{path:"/v1/desktop/tags",method:"GET"};case"tags.replace":return{path:"/v1/desktop/tags",method:"PUT",body:{tags:e.tags}};case"sessions.tags":return{path:`/v1/desktop/sessions/${e.sessionId}/tags`,method:"PUT",body:{tags:e.tags,primary:e.primary,...e.expected_revision===void 0?{}:{expected_revision:e.expected_revision}}};case"sessions.pin":return{path:`/v1/desktop/sessions/${e.sessionId}/pin`,method:"POST",body:{pinned:e.pinned}};case"sessions.watch":return{path:`/v1/desktop/sessions/${e.sessionId}/watch`,method:"POST",body:{subscription_id:e.subscriptionId,visible:e.visible,can_notify:e.canNotify}};case"sessions.presence":return{path:"/v1/desktop/presence",method:"POST",body:{subscription_id:e.subscriptionId,can_notify_kinds:e.canNotifyKinds,session_id:e.sessionId,window:e.window,can_notify:e.canNotify}};case"sessions.move":return{path:`/v1/desktop/sessions/${e.sessionId}/working-directory`,method:"POST",body:{request_id:e.requestId,cwd:e.cwd}};case"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":{Ji(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"POST",body:{document:e.document??{},...Yi(e)}}}case"agent.republish":{Ji(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"PUT",body:{hub_agent_id:e.hubAgentId,document:e.document??{},...Yi(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{Ji(e);const t=new URLSearchParams;return e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId)),{path:`/v1/teams/${e.teamId}/publish${t.size?`?${t}`:""}`,method:"POST",body:Yi(e)}}case"team.pull":{const t=new URLSearchParams;e.tenantId&&t.set("tenant_id",e.tenantId);const n=t.toString();return{path:`/v1/teams/pull/${e.teamId}${n?`?${n}`:""}`,method:"GET"}}case"agent.nameAvailability":return{path:`/v1/agent-name-availability?${new URLSearchParams({name:e.name})}`,method:"GET"};case"legacy.agents.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return e.name&&t.set("name",e.name),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:`/v1/agents?${t}`,method:"GET"}}case"legacy.agent.get":return{path:`/v1/agents/${e.agentId}`,method:"GET"};case"legacy.agent.history":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/history?${t}`,method:"GET"}}case"wakes.list":{const t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",String(e.limit)),e.includeDormant!==void 0&&t.set("include_dormant",String(e.includeDormant)),{path:t.size>0?`/v1/desktop/wakes?${t}`:"/v1/desktop/wakes",method:"GET"}}case"wakes.create":return{path:"/v1/desktop/wakes",method:"POST",body:{request_id:e.requestId,...ew(e),message:e.message,...nu(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...nu(e)}};case"wakes.remove":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"DELETE"};case"monitors.cancel":return{path:`/v1/desktop/monitors/${encodeURIComponent(e.sessionId)}/${encodeURIComponent(e.monitorId)}`,method:"DELETE"};case"jobs.cancel":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/jobs/${encodeURIComponent(e.jobId)}/cancel`,method:"POST"};case"legacy.jobs.list":{const t=new URLSearchParams;return e.agentId&&t.set("agent_id",e.agentId),e.status&&t.set("status",e.status),{path:t.size>0?`/v1/jobs?${t}`:"/v1/jobs",method:"GET"}}case"legacy.job.get":return{path:`/v1/jobs/${e.jobId}`,method:"GET"};case"legacy.schedules.list":return{path:`/v1/schedules?${new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)})}`,method:"GET"};case"legacy.agent.schedules.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/schedules?${t}`,method:"GET"}}case"legacy.agent.schedule.create":return{path:`/v1/agents/${e.agentId}/schedules`,method:"POST",body:e.schedule};case"legacy.schedule.get":return{path:`/v1/schedules/${e.scheduleId}`,method:"GET"};case"legacy.schedule.edit":return{path:`/v1/schedules/${e.scheduleId}`,method:"PATCH",body:e.schedule};case"legacy.schedule.remove":return{path:`/v1/schedules/${e.scheduleId}`,method:"DELETE"};case"legacy.agent.create":return{path:"/v1/agents",method:"POST",body:e.agent};case"legacy.agent.update":return{path:`/v1/agents/${e.agentId}`,method:"PATCH",body:e.update};case"legacy.agent.delete":return{path:`/v1/agents/${e.agentId}`,method:"DELETE"};case"legacy.agent.conversation.clear":return{path:`/v1/agents/${e.agentId}/conversation`,method:"DELETE"};case"legacy.agent.systemPrompt.get":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"GET"};case"legacy.agent.systemPrompt.update":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"PUT",body:{system_prompt:e.systemPrompt}};case"legacy.agent.download":return{path:`/v1/agents/${e.agentId}/download`,method:"GET"};case"legacy.job.cancel":return{path:`/v1/jobs/${e.jobId}`,method:"DELETE"};case"commands.list":return{path:"/v1/desktop/commands",method:"GET"};case"commands.entities":return{path:`/v1/desktop/sessions/${e.sessionId}/command-entities?command=${encodeURIComponent(e.command)}${e.name?`&name=${encodeURIComponent(e.name)}`:""}`,method:"GET"};case"models.catalogue":{const t=e.scope?`&scope=${e.scope}`:"";return{path:`/v1/desktop/models?live=${e.live??!1}${t}`,method:"GET"}}case"usage.get":{const t=new URLSearchParams({live:String(e.live??!1),refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),{path:`/v1/desktop/usage?${t}`,method:"GET"}}case"usage.reset":{const t={provider:e.provider,redeem_request_id:e.redeemRequestId};return e.credentialRef&&(t.credential_ref=e.credentialRef),e.identity&&(t.identity=e.identity),{path:"/v1/desktop/usage/reset",method:"POST",body:t}}case"quota.notice":{const t=new URLSearchParams({refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),e.model&&t.set("model",e.model),{path:`/v1/desktop/quota-notice?${t}`,method:"GET"}}case"analytics.get":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics?${t}`,method:"GET"}}case"analytics.models":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics/models?${t}`,method:"GET"}}case"info.get":return{path:"/v1/desktop/info",method:"GET"};case"sessions.report":{const t=new URLSearchParams({recent_limit:String(e.recentLimit??12)});return{path:`/v1/desktop/sessions/${e.sessionId}/report?${t}`,method:"GET"}}case"skills.list":{const t=new URLSearchParams;e.sessionId&&t.set("session_id",e.sessionId),e.cwd&&t.set("cwd",e.cwd),e.name&&t.set("name",e.name);const n=t.toString();return{path:`/v1/desktop/skills${n?`?${n}`:""}`,method:"GET"}}case"skills.create":return{path:"/v1/desktop/skills",method:"POST",body:{request_id:e.requestId,name:e.name,copy_from:e.copyFrom}};case"skills.update":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"PUT",body:{request_id:e.requestId,expected_fingerprint:e.expectedFingerprint,files:e.files}};case"skills.remove":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"DELETE",body:{request_id:e.requestId,discard_local_changes:e.discardLocalChanges}};case"sessions.failovers":return{path:`/v1/desktop/sessions/${e.sessionId}/failovers`,method:"GET"};case"sessions.credential":return{path:`/v1/desktop/sessions/${e.sessionId}/credentials`,method:"POST",body:{action:e.action,key:e.key,value:e.value,confirmed:e.confirmed}};case"sessions.fork":return{path:`/v1/desktop/sessions/${e.sessionId}/fork`,method:"POST",body:{request_id:e.requestId,message:e.message,boundary:e.boundary,entry_id:e.entryId,auto_tag:e.autoTag}};case"sessions.stop":return{path:"/v1/desktop/stop",method:"POST",body:{request_id:e.requestId,targets:e.targets,confirmed:e.confirmed}};case"sessions.aside":return{path:`/v1/desktop/sessions/${e.sessionId}/asides`,method:"POST",body:{request_id:e.requestId,text:e.text,aside_id:e.asideId,subscription_id:e.subscriptionId}};case"sessions.adopt":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}/adopt`,method:"POST",body:{request_id:e.requestId,confirmed:e.confirmed}};case"sessions.aside.get":case"sessions.aside.close":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}`,method:e.op==="sessions.aside.get"?"GET":"DELETE"};case"mcp.list":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"GET"};case"mcp.credentials.store":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp/credentials`,method:"POST",body:{name:e.name,values:e.values,confirmed_replace:e.confirmedReplace}};case"mcp.control":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"POST",body:e.control};case"mcp.catalog":{const t=new URLSearchParams;e.cwd&&t.set("cwd",e.cwd),e.sessionId&&t.set("session_id",e.sessionId);const n=t.toString();return{path:n?`/v1/desktop/mcp?${n}`:"/v1/desktop/mcp",method:"GET"}}case"mcp.catalog.control":return{path:"/v1/desktop/mcp",method:"POST",body:{...e.control,...e.cwd?{cwd:e.cwd}:{}}};case"mcp.catalog.credentials":return{path:"/v1/desktop/mcp/credentials",method:"POST",body:{name:e.name,values:e.values,...e.header?{header:e.header}:{},confirmed_replace:e.confirmedReplace,...e.cwd?{cwd:e.cwd}:{}}};case"radient.request":return{path:"/v1/desktop/radient",method:"POST",body:e.control};case"providers.list":return{path:"/v1/auth/providers",method:"GET"};case"accounts.list":return{path:"/v1/auth/status",method:"GET"};case"accounts.remove":return{path:`/v1/auth/accounts/${e.accountId}`,method:"DELETE"};case"tunnel.setup.read":return{path:e.credentialId===void 0?"/v1/desktop/tunnel/setup":`/v1/desktop/tunnel/setup?credential_id=${e.credentialId}`,method:"GET"};case"tunnel.setup.plan":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"plan",...e.credentialId!==void 0?{credential_id:e.credentialId}:{}}};case"tunnel.setup.run":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"run",credential_id:e.credentialId,...e.acceptMonthlyPrice!==void 0?{accept_monthly_price:e.acceptMonthlyPrice}:{}}};case"auth.start":return{path:"/v1/auth/login",method:"POST",body:{provider:e.provider}};case"auth.status":return{path:`/v1/auth/operations/${e.id}`,method:"GET"};case"auth.input":return{path:`/v1/auth/operations/${e.id}/input`,method:"POST",body:{prompt_id:e.promptId,value:e.value}};case"auth.cancel":return{path:`/v1/auth/operations/${e.id}`,method:"DELETE"};case"auth.key":return{path:`/v1/auth/providers/${e.provider}/key`,method:"PUT",body:{value:e.value}};case"auth.logout":return{path:`/v1/auth/providers/${e.provider}/credentials`,method:"DELETE"};case"agent_messages.status":return{path:`/v1/desktop/team-bridge/status?boundary=${e.boundary}`,method:"GET"};case"agent_messages.enable":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,state:e.state,consent_version:e.consent_version,consented_via:e.consented_via}};case"agent_messages.settings":return{path:`/v1/desktop/team-bridge/settings${ms(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${ms(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)}${ms(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"?"":Qr(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${Qr(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)}${Qr(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)}${Qr(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${ms(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"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}${Qr(e)}`,method:"DELETE"}}case"team_bridge.messages.send":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},client_ref:e.client_ref,body:e.body,...e.agent_label?{agent_label:e.agent_label}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{},...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.files?.length?{files:e.files}:{},...e.mentions?.length?{mentions:e.mentions}:{}}};case"team_bridge.scheduled.list":return{path:`/v1/desktop/team-bridge/scheduled?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"GET"};case"team_bridge.scheduled.create":return{path:"/v1/desktop/team-bridge/scheduled",method:"POST",body:{tenant_id:e.tenant_id,conversation_id:e.conversation_id,client_ref:e.client_ref,body:e.body,send_at:e.send_at,...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{}}};case"team_bridge.scheduled.update":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"PATCH",body:{...e.body===void 0?{}:{body:e.body},...e.send_at===void 0?{}:{send_at:e.send_at},...e.attachment_ids===void 0?{}:{attachment_ids:e.attachment_ids},...e.expected_version===void 0?{}:{expected_version:e.expected_version}}};case"team_bridge.attachments.delete":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/attachments/${encodeURIComponent(e.attachment_id)}?${new URLSearchParams({tenant_id:e.tenant_id,expected_account_id:e.expected_account_id})}`,method:"DELETE"};case"team_bridge.scheduled.cancel":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"DELETE"};case"team_bridge.messages.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit)),e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/replies${n}`,method:"GET"}}case"team_bridge.read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.seq===void 0?{}:{seq:e.seq},...e.muted===void 0?{}:{muted:e.muted}}};case"team_bridge.thread_read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/read`,method:"POST",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,seq:e.seq}};case"team_bridge.unread":{const t=new URLSearchParams;return e.scope==="account"?t.set("scope","account"):e.tenant_id&&t.set("tenant_id",e.tenant_id),{path:`/v1/desktop/team-bridge/unread${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.directory":return{path:`/v1/desktop/team-bridge/directory?tenant_id=${encodeURIComponent(e.tenant_id)}`,method:"GET"};case"team_bridge.status":{const t=new URLSearchParams;return e.boundary&&t.set("boundary",e.boundary),{path:`/v1/desktop/team-bridge/status${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.link_preview.resolve":return{path:"/v1/desktop/team-bridge/link-preview/resolve",method:"POST",body:{url:e.url,index:e.index,expected_account_id:e.expectedAccountId}};case"settings.list":return{path:"/v1/settings",method:"GET"};case"settings.edit":return{path:`/v1/settings/${e.key}`,method:"PATCH",body:{value:e.value,base:e.base}};case"settings.reset":return{path:`/v1/settings/${e.key}/reset`,method:"POST"};case"tts.paths":return{path:"/v1/tts/paths",method:"GET"};case"notification_sounds.list":return{path:"/v1/notification-sounds",method:"GET"};case"notification_sounds.rename":return{path:`/v1/notification-sounds/${e.id}`,method:"PATCH",body:{name:e.name}};case"notification_sounds.remove":return{path:`/v1/notification-sounds/${e.id}`,method:"DELETE"};case"config.get":return{path:"/v1/config",method:"GET"};case"config.update":return{path:"/v1/config",method:"PATCH",body:e.value};case"instructions.get":return{path:"/v1/config/system-prompt",method:"GET"};case"instructions.update":return{path:"/v1/config/system-prompt",method:"PATCH",body:{content:e.content}};case"credentials.list":return{path:"/v1/credentials",method:"GET"};case"credentials.update":return{path:"/v1/credentials",method:"PATCH",body:{key:e.key,value:e.value}};case"library.list":{const t=new URLSearchParams;e.scope&&t.set("scope",e.scope),e.q&&t.set("q",e.q),e.category&&t.set("category",e.category),e.kind&&t.set("kind",e.kind),e.origin_group&&t.set("origin_group",e.origin_group),e.origin&&t.set("origin",e.origin),e.tag&&t.set("tag",e.tag),e.tag_mode&&t.set("tag_mode",e.tag_mode),e.highlighted!==void 0&&t.set("highlighted",e.highlighted?"1":"0"),e.organized!==void 0&&t.set("organized",e.organized?"1":"0"),e.favorite!==void 0&&t.set("favorite",e.favorite?"1":"0"),e.session&&t.set("session",e.session),e.session_id&&t.set("session_id",e.session_id),e.sort&&t.set("sort",e.sort),e.order&&t.set("order",e.order),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);const n=t.toString();return{path:`/v1/desktop/library/assets${n?`?${n}`:""}`,method:"GET"}}case"library.get":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"GET"};case"library.update":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"PATCH",body:e.fields};case"library.tags":return{path:"/v1/desktop/library/tags",method:"GET"};case"library.tags.create":return{path:"/v1/desktop/library/tags",method:"POST",body:{name:e.name,...e.category!==void 0?{category:e.category}:{}}};case"library.tags.update":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"PATCH",body:{...e.name!==void 0?{name:e.name}:{},...e.category!==void 0?{category:e.category}:{}}};case"library.tags.delete":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"DELETE"};case"library.tags.merge":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}/merge`,method:"POST",body:{into:e.into}};case"library.tags.assign":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/tags`,method:"PUT",body:{tags:e.tags,...e.primary!==void 0?{primary:e.primary}:{}}};case"library.chat.link":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"PUT",body:{session_id:e.sessionId}};case"library.chat.clear":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"DELETE"};case"library.librarian":{const t=e.action??"status";return t==="status"?{path:"/v1/desktop/librarian",method:"GET"}:{path:"/v1/desktop/librarian",method:"POST",body:{op:t}}}case"projects.list":return{path:"/v1/desktop/projects",method:"GET"};case"projects.get":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"GET"};case"projects.create":return{path:"/v1/desktop/projects",method:"POST",body:{name:e.name,...e.description!==void 0?{description:e.description}:{},...e.status!==void 0?{status:e.status}:{},...e.tags!==void 0?{tags:e.tags}:{}}};case"projects.update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"PATCH",body:{...e.fields,...e.force_done===!0?{force_done:!0}:{}}};case"projects.delete":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"DELETE",body:{confirm:e.confirmed_name}};case"projects.link":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links`,method:"POST",body:{session_id:e.sessionId}};case"projects.unlink":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links/${encodeURIComponent(e.sessionId)}`,method:"DELETE"};case"projects.milestone":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones`,method:"POST",body:{name:e.name,...e.targetDate!==void 0?{target_date:e.targetDate}:{},...e.completed!==void 0?{completed:e.completed}:{}}};case"projects.milestone.remove":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones/${encodeURIComponent(e.name)}`,method:"DELETE"};case"projects.request_update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/request-update`,method:"POST"};case"projects.search":return{path:`/v1/desktop/projects/search?${new URLSearchParams({q:e.q,limit:String(e.limit??ly)})}`,method:"GET"};case"aida.status":return{path:"/v1/desktop/aida",method:"GET"};case"aida.control":return{path:"/v1/desktop/aida",method:"POST",body:{op:e.action}};case"code_requests.list":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests`,method:"GET"};case"code_requests.refresh":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests/refresh`,method:"POST",body:{...e.keys!==void 0?{keys:e.keys}:{},...e.force!==void 0?{force:e.force}:{}}};case"static.sign":return{path:"/v1/static/sign",method:"POST",body:{route:e.route,path:e.path,ttl_s:e.ttlS}};case"sidebar_layout.get":return{path:"/v1/desktop/sidebar-layout",method:"GET"};case"sidebar_layout.set":return{path:"/v1/desktop/sidebar-layout",method:"PUT",body:{layout:e.layout}};case"notifications.list":{const t=new URLSearchParams;e.preview&&t.set("preview","true"),e.includeAskReads&&t.set("include_ask_reads","true");for(const n of e.countSessionIds??[])t.append("count_session_ids",n);return e.kind&&t.set("kind",e.kind),e.bulkPriority&&t.set("bulk_priority",e.bulkPriority),e.state&&t.set("state",e.state),e.source&&t.set("source",e.source),e.priority&&t.set("priority",e.priority),e.sessionId&&t.set("session_id",e.sessionId),e.cursor&&t.set("cursor",e.cursor),e.throughSeq!==void 0&&t.set("through_seq",String(e.throughSeq)),e.limit!==void 0&&t.set("limit",String(e.limit)),{path:`/v1/desktop/notifications${t.size?`?${t}`:""}`,method:"GET"}}case"notifications.get":return{path:`/v1/desktop/notifications/${encodeURIComponent(e.id)}`,method:"GET"};case"notifications.count":return{path:"/v1/desktop/notifications/count",method:"GET"};case"notifications.read":case"notifications.dismiss":return{path:"/v1/desktop/notifications",method:"PATCH",body:{op:e.verb,...nw(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:hy[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function nw(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 TP=64,CP=64*1024*1024,OP="superseded_completion_token",PP="store_busy",rw="session_is_remote",ow="owner_build_behind";function MP(e,t,n){if(!e||typeof e!="object")return!1;const r=e;return r.unseen===!1&&r.conversation_id===`session/${t}`&&r.completion_token===n}function Ar(e,t,n){return!t||t.conversation_id!==`session/${n}`||!Array.isArray(t.revision)||t.revision.length!==2||!t.revision.every(r=>Number.isSafeInteger(r)&&r>=0)||e?.conversation_id===t.conversation_id&&(t.revision[0]<e.revision[0]||t.revision[1]<e.revision[1])?e:t.supported===void 0&&e?.supported!==void 0?{...t,supported:e.supported}:t}function sw(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const jP=e=>typeof e?.goal_status=="string",$P=e=>(e?.goal??"").trim().length>0;function iw(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function aw(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 go={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 cw(e){return e?e===go.notPaired?"notPaired":e===go.serverDown?"serverDown":e===go.frameBudget?"frameTooLarge":"lost":"lost"}const lw=/^[a-f0-9]{12}$/,dw=/^[a-zA-Z0-9_-]{1,128}$/,uw=()=>performance.timeOrigin+performance.now();function fw(e){e&&(e.rendererEntryEpochMs=uw())}function zc(e,t){e&&(e.delivery=t,e.deliveryAt=performance.now())}function pw(e,t,n,r){const o=a=>a===void 0?"-":a.toFixed(3),s=(a,c)=>a===void 0||c===void 0?void 0:a-c;return["[snapshot-receipt]",`openToken=${t??"-"}`,`session=${lw.test(e.sessionId)?e.sessionId:"?"}`,`streamId=${dw.test(e.streamId)?e.streamId:"?"}`,"kind=snapshot",`chars=${e.chars}`,`mainRecordEpochMs=${o(e.mainRecordEpochMs)}`,`mainFoldMs=${o(e.mainFoldMs)}`,`mainObserverMs=${o(e.mainObserverMs)}`,`mainEmitMs=${o(e.mainEmitMs)}`,`mainSendEpochMs=${o(e.mainSendEpochMs)}`,`ipcApproxMs=${o(s(e.preloadReceiptEpochMs,e.mainSendEpochMs))}`,`preloadReceiptEpochMs=${o(e.preloadReceiptEpochMs)}`,`preloadReadyMs=${o(e.preloadReadyMs)}`,`bridgeApproxMs=${o(s(e.rendererEntryEpochMs,e.preloadReceiptEpochMs===void 0||e.preloadReadyMs===void 0?void 0:e.preloadReceiptEpochMs+e.preloadReadyMs))}`,`rendererEntryEpochMs=${o(e.rendererEntryEpochMs)}`,`delivery=${e.delivery??"-"}`,`bufferMs=${o(s(e.deliveryAt,e.bufferedAt))}`,`deliveryToParseMs=${o(s(n,e.deliveryAt))}`,`parseMs=${o(r-n)}`].join(" ")}const ou=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const h=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(m=>m(t,h))}},o=()=>t,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d))},l=t=e(r,o,c);return c},hw=e=>e?ou(e):ou,mw=e=>e;function gw(e,t=mw){const n=sd.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return sd.useDebugValue(n),n}const su=e=>{const t=hw(e),n=r=>gw(t,r);return Object.assign(n,t),n},Qo=e=>e?su(e):su;function Fp(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var s;const a=l=>l===null?null:JSON.parse(l,void 0),c=(s=n.getItem(o))!=null?s:null;return c instanceof Promise?c.then(a):a(c)},setItem:(o,s)=>n.setItem(o,JSON.stringify(s,void 0)),removeItem:o=>n.removeItem(o)}}const Ha=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Ha(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Ha(r)(n)}}}},_w=(e,t)=>(n,r,o)=>{let s={storage:Fp(()=>localStorage),partialize:b=>b,version:0,merge:(b,v)=>({...v,...b}),...t},a=!1;const c=new Set,l=new Set;let d=s.storage;if(!d)return e((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),n(...b)},r,o);const u=()=>{const b=s.partialize({...r()});return d.setItem(s.name,{state:b,version:s.version})},f=o.setState;o.setState=(b,v)=>{f(b,v),u()};const h=e((...b)=>{n(...b),u()},r,o);o.getInitialState=()=>h;let m;const y=()=>{var b,v;if(!d)return;a=!1,c.forEach(A=>{var k;return A((k=r())!=null?k:h)});const p=((v=s.onRehydrateStorage)==null?void 0:v.call(s,(b=r())!=null?b:h))||void 0;return Ha(d.getItem.bind(d))(s.name).then(A=>{if(A)if(typeof A.version=="number"&&A.version!==s.version){if(s.migrate){const k=s.migrate(A.state,A.version);return k instanceof Promise?k.then(T=>[!0,T]):[!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[T,F]=A;if(m=s.merge(F,(k=r())!=null?k:h),n(m,!0),T)return u()}).then(()=>{p?.(m,void 0),m=r(),a=!0,l.forEach(A=>A(m))}).catch(A=>{p?.(void 0,A)})};return o.persist={setOptions:b=>{s={...s,...b},b.storage&&(d=b.storage)},clearStorage:()=>{d?.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>y(),hasHydrated:()=>a,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(l.add(b),()=>{l.delete(b)})},s.skipHydration||y(),m||h},_i=_w,bw=(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 vw(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.message!="string"||t.message.trim()==="")return null;const n=(r,o)=>typeof r=="number"&&Number.isFinite(r)?r:o;return{message:t.message,removed:n(t.removed,0),max_age_hours:n(t.max_age_hours,48),in_progress:t.in_progress===!0,first_removal_at:typeof t.first_removal_at=="string"?t.first_removal_at:"",freed_bytes_estimate:typeof t.freed_bytes_estimate=="number"&&Number.isFinite(t.freed_bytes_estimate)?t.freed_bytes_estimate:null,record:typeof t.record=="string"?t.record:""}}const Up=Qo()(_i(e=>({notice:null,receive:t=>e(n=>bw(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:Fp(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function Xn(e){return _(Sy[e])}let Wa=null;function yw(e){if(e===null){Wa=null;return}Wa={openFrame:e.openFrame===!0,journalOrder:e.journalOrder===!0,peerJournalSource:e.peerJournalSource===!0}}function Bp(){return Wa}const iu=()=>_("ui.common.errors.desktop_backend_offline"),ww=()=>_("ui.common.errors.desktop_backend_compatibility");async function Hp(e){if(window.api?.desktop)try{return await kw(window.api.desktop.request(e),e)}catch(n){throw n instanceof Te?n:xw(n)?new mn(Lp,Dp):new Te(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 Te(null,iu(),n)}if(!t.ok)throw new Te(t.status,ww());return t.json()}function kw(e,t){const n=Np(t);let r;return Promise.race([e,new Promise((o,s)=>{r=setTimeout(()=>{const a=qy(t.op,n);s(new Te(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const Wp="This server did not answer the request for its desktop controls.",Sw=()=>_("ui.common.errors.desktop_refusal_placeholder");class Te extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,o,s,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=o,this.retryAfterMs=s,this.detail=a}}class mn extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function Kc(e){return e instanceof Te||e instanceof mn?e.code===Ue.serverUpdating?!0:e instanceof Te&&_y(e.detail):!1}function NP(e){return e instanceof Te&&by(e.detail)}function Vc(e,t){return Kc(e)?Xn(Ue.serverUpdating):e instanceof Te||e instanceof mn?gi(e.code)?Xn(e.code):e.message===Wp?Sw():e.message:t}function Ew(e,t,n,r){return r===Op&&t===503?Ue.serverUpdating:typeof r=="string"?r:n===Cp&&t===503?Ue.serverUpdating:n===Ba.noCredential?Ue.noCredential:n===Ba.transportFailed?Ue.transportFailed:Ey(tw(e).path,t)}async function Je(e){const t=await Hp(e),n=t.body;if(t.status<200||t.status>=300){const r=typeof n?.detail=="string"?n.detail:typeof n?.detail?.text=="string"?n.detail.text:typeof n?.detail?.message=="string"?n.detail.message:null;throw new Te(t.status,r??Wp,void 0,Ew(e,t.status,r,typeof n?.detail=="object"?n.detail?.code:void 0),typeof n?.detail=="object"&&typeof n.detail?.retry_after_ms=="number"&&Number.isFinite(n.detail.retry_after_ms)?n.detail.retry_after_ms:void 0,typeof n?.detail=="object"?n.detail:void 0)}return e.op==="sessions.list"&&Aw(n?.result),n?.result}function Aw(e){if(typeof e!="object"||e===null)return;const t=vw(e.delegated_cleanup_notice);t&&Up.getState().receive(t)}async function Iw(){try{await Je({op:"delegated_cleanup_notice.ack"})}catch{}}async function DP(){Up.getState().dismiss(),await Iw()}function Rw(e){return e instanceof Te&&e.code===Gc}function LP(e){if(!(e instanceof Te))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===ow:e.code===rw}function FP(e){return e instanceof mn&&e.code===Dp}function xw(e){return e instanceof Error&&e.message.includes(Lp)}async function UP(e){const t=await Hp(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function BP(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await Je({op:"auth.status",id:e});if(!n.auth_url)throw new Error("This sign-in is no longer waiting for a browser.");const r=new URL(n.auth_url);if(r.username||r.password||r.protocol!=="https:"&&!(r.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(r.hostname)))throw new Error("The provider returned an invalid sign-in address.");window.open(r.href,"_blank","noopener,noreferrer")}function Tw(e,t,n){const r=Pw(e);return r.record?(n?.("adopted"),au(e.sessionId,"adopted","none",Ga(e),null),$w(r.record,t)):(Gt&&un(),n?.("requested"),au(e.sessionId,"requested",r.refusal,Ga(e),r.held),Gp(e,t))}const Cw=6e4,Ow=512;function Ga(e){return{openFrame:e.openFrame===!0,journalOrder:e.journalOrder===!0,peerJournalSource:e.peerJournalSource===!0}}let Gt=null,qn=null;function un(){qn!==null&&(clearTimeout(qn),qn=null);const e=Gt;Gt=null,e&&(e.live=null,e.buffered=[],e.disposeTransport())}function HP(){return Gt?.sessionId??null}function WP(e){!e||Gt?.sessionId!==e||un()}function GP(e,t){if(!e||Gt?.sessionId===e)return;un();const n=Bp(),r={openFrame:n?.openFrame===!0,journalOrder:n?.journalOrder===!0,peerJournalSource:n?.peerJournalSource===!0&&t?.remoteOwned===!0};let o=!1;const s={sessionId:e,negotiation:r,buffered:[],live:null,ended:!1,disposeTransport:()=>{}};if(s.disposeTransport=Gp({sessionId:e,...r.openFrame?{openFrame:!0}:{},...r.journalOrder?{journalOrder:!0}:{},...r.peerJournalSource?{peerJournalSource:!0}:{}},c=>{if(s.live){zc(c.receipt,"live"),s.live(c);return}if(c.kind==="error"||c.kind==="end"){s.ended=!0,o=!0,un();return}if(s.buffered.length>=Ow){o=!0,un();return}c.receipt&&(c.receipt.bufferedAt=performance.now()),s.buffered.push(c)}),o){s.disposeTransport();return}Gt=s;const a=setTimeout(()=>{Gt===s&&un()},Cw);typeof a.unref=="function"&&a.unref(),qn=a}function Pw(e){const t=Gt;if(!t)return{record:null,refusal:"none",held:null};if(t.ended)return un(),{record:null,refusal:"ended",held:t.negotiation};if(t.sessionId!==e.sessionId)return{record:null,refusal:"other-session",held:null};const n=Ga(e);return e.epoch!==void 0||e.afterSeq!==void 0||(e.orderIds?.length??0)>0?(un(),{record:null,refusal:"resuming",held:t.negotiation}):n.openFrame!==t.negotiation.openFrame||n.journalOrder!==t.negotiation.journalOrder||n.peerJournalSource!==t.negotiation.peerJournalSource?(un(),{record:null,refusal:"negotiation",held:t.negotiation}):{record:t,refusal:null,held:t.negotiation}}const Mw=/^[A-Za-z0-9_-]{1,80}$/,jw="[stream-prewarm]";function au(e,t,n,r,o){if(t==="requested"&&n==="none")return;const s=Mw.test(e)?e:"?",a=l=>[l.openFrame?"1":"0",l.journalOrder?"1":"0",l.peerJournalSource?"1":"0"].join(","),c=[jw,`session=${s}`,`decision=${t}`];t==="requested"&&(c.push(`why=${n}`,`asked=${a(r)}`),o&&c.push(`prewarm=${a(o)}`),n==="negotiation"&&c.push(`caps=${Bp()?"recorded":"absent"}`)),console.warn(c.join(" "))}function $w(e,t){const n=e.buffered;e.buffered=[],e.live=t,qn!==null&&(clearTimeout(qn),qn=null),Gt===e&&(Gt=null);let r=!1;return queueMicrotask(()=>{if(!r)for(const o of n)zc(o.receipt,"replay"),t(o)}),()=>{r||(r=!0,e.live=null,e.disposeTransport())}}function Gp(e,t){const n=window.api?.desktop?.stream;if(n){const s=n.subscribe(e,a=>{const c=a.receipt?{...a,receipt:{...a.receipt}}:a;fw(c.receipt),zc(c.receipt,"direct"),t(c)});return()=>s.dispose()}const r=new URLSearchParams({session:e.sessionId});e.epoch&&r.set("epoch",e.epoch),e.afterSeq!==void 0&&r.set("after_seq",String(e.afterSeq)),r.set("frontend_replace","1"),e.openFrame===!0&&r.set("open_frame","1"),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),Vs(r,"/__desktop/stream",e.orderIds??[]));const o=new EventSource(`/__desktop/stream?${r}`);return o.onmessage=s=>{t({kind:"data",data:s.data})},o.onerror=()=>{o.readyState===EventSource.CLOSED&&(t({kind:"error",detail:go.ended}),o.close())},()=>{o.close(),t({kind:"end"})}}async function zP(e,t){const n=window.api?.desktop?.media;if(n)return n(e,t);const r=await fetch("/__desktop/media",{method:"POST",headers:{"x-desktop-media":JSON.stringify(e),"Content-Type":"application/octet-stream"},body:t?new Blob([t]):void 0}),o=r.headers.get("content-type")??"";if(!r.ok){let s="The media request failed.",a,c;if(o.includes("application/json"))try{const l=await r.json();gy(r.status,l)&&(a=Ue.serverUpdating);const d=l?.detail;if(typeof d=="string")s=d;else if(typeof d=="object"&&d!==null){const u=d;typeof u.text=="string"&&u.text.trim()?s=u.text:typeof u.message=="string"&&u.message.trim()&&(s=u.message),typeof u.code=="string"&&a===void 0&&(a=u.code);const f=d.params;typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}}catch{}return{status:r.status,kind:"error",detail:s,code:a!==void 0&&gi(a)?a:s===Ba.noCredential?Ue.noCredential:void 0,...e.op==="notification_sounds.upload"&&a!==void 0?{refusal:{code:a.slice(0,64),...c?{params:c}:{}}}:{}}}return o.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:o||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function KP(e){return e.kind==="error"?gi(e.code)?new mn(Xn(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function Nw(e){if(Kc(e))return"updating";if(Rw(e))return"deadline";const t=e instanceof Te?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const zp={updating:"",unreachable:"",deadline:"",unauthorized:"",get outdated(){return _("ui.common.connection.backend.remedy_outdated")},unknown:""},Os={get updating(){return Xn(Ue.serverUpdating)},get unreachable(){return _("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return _("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return _("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return _("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function Dw(e,t){const n=Nw(t);return[e,Os[n],zp[n]].filter(Boolean).join(" ")}const za={get successor(){return _("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return _("ui.common.connection.backend.pairing_unpaired")}},Lw={get successor(){return _("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return _("ui.common.connection.backend.pane_unpaired")}};function VP(e,t){return e!=="unpaired"?null:Lw[t??"unpaired"]}function ZP(e,t){return e!=="unpaired"?null:za[t??"unpaired"]}function YP(e){const{kind:t,unpaired:n,answered:r,cause:o=null,servedByThisApp:s=!1}=e;return o==="pre-handshake"?s:o!==null||n?!1:r?s:t==="outdated"}function JP(e){const{kind:t,unpaired:n,missing:r,answered:o,cause:s=null}=e;if(s!==null)return za[s];if(!o){if(t==="updating")return Os.updating;if(t==="unreachable")return _("ui.common.connection.backend.compatibility_unreachable",{diagnosis:Os.unreachable});if(t==="unauthorized")return _("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return _("ui.common.connection.backend.compatibility_deadline",{diagnosis:Os.deadline});if(t==="outdated")return _("ui.common.connection.backend.compatibility_outdated",{remedy:zp.outdated})}return n?za.unpaired:o?_("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):_("ui.common.connection.backend.compatibility_unknown")}const Fw=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function QP(e,t=null){return t!==null||!e?!0:Fw.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function Uw(e,t){return t instanceof Te&&t.status===null?!1:e<1}function XP(e,t){return t instanceof Te&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const Bw={get successor(){return _("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.card_credential_refused")},get unpaired(){return _("ui.common.connection.backend.card_unpaired")}};function qP(e,t,n){return e===null?{sentence:Dw(t,n),remedy:!0}:{sentence:Bw[e],remedy:mp(e)}}const Kp={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]},Hw=3e4,Ww=15e3;function Gw(e){return e?.desktop_available===!0}function eM(){const{client:e,provided:t}=Q_();return hp({enabled:t,queryKey:Kp.capabilities,queryFn:async()=>{try{const n=await Je({op:"capabilities"});return yw(Kw(n)),n}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>Gw(n.state.data)?Hw:Ww,refetchIntervalInBackground:!0},e)}function zw(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function Qi(e,t,n=1){return zw(e,t,n)==="enabled"}function Kw(e){return{openFrame:Qi(e,"open_frame"),journalOrder:Qi(e,"journal_order"),peerJournalSource:Qi(e,"peer_journal_source")}}function tM(e){return hp({queryKey:Kp.providers,queryFn:()=>Je({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:Uw})}let bi=!1,Ys=!1;const Js=[];function nM(){typeof window>"u"||!window.__loDevDriver?.armed||(bi=!0,Ys=!1,Js.length=0)}function Vw(){return bi}function Zw(e){if(bi)try{if(Js.length>=256){Ys=!0;return}Js.push({carrier:e.carrier,sessionId:e.sessionId,epoch:typeof e.epoch=="string"?e.epoch:null,seq:typeof e.seq=="number"?e.seq:null,disposition:e.disposition})}catch{Ys=!0}}function rM(){return{armed:bi,fault:Ys,receipts:Js.map(e=>({...e}))}}const Xr=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function Yw(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=Xr(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=Xr(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>Xr(d)===c);l===-1?r.push(a):r[l]=a}if(!t.order)return r;const o=new Map;for(const a of r){const c=Xr(a);c!==null&&o.set(c,a)}const s=[];for(const a of t.order){const c=String(a),l=o.get(c);l&&(s.push(l),o.delete(c))}for(const a of r){const c=Xr(a);c!==null&&o.has(c)?(s.push(a),o.delete(c)):c===null&&s.push(a)}return s}const Ka=e=>({revision:Ct(e),demand:e.orderDemand}),er=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Lr(e,t,n,r,o,s={}){let a=e;const c=t.journal_generation;if(t.reconcile===!0){const h=typeof c=="string"&&c.length>0?c:void 0;return a.orderNeedsReconcile&&a.orderWantedGeneration===h?a.journalMode?a:{...a,journalMode:!0}:{...a,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:h,orderDemand:h!==void 0?{generation:h}:{}}}if(typeof c!="string"||c.length===0)return t.journal_order_state&&t.journal_order_state!=="unsupported"&&!a.journalMode?{...a,journalMode:!0}:a;if(r&&t.journal_order_state==="ready"&&o&&a.orderNeedsReconcile&&a.orderDemand===o.demand&&(a={...a,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),c!==a.journalGeneration&&!r)return a.orderNeedsReconcile&&a.orderWantedGeneration===c?a:{...a,orderNeedsReconcile:!0,orderWantedGeneration:c,orderDemand:{generation:c}};let l=a.journalMode?a:{...a,journalMode:!0};if(c!==a.journalGeneration&&(l={...a,journalMode:!0,journalGeneration:c,orderRevision:(a.orderRevision??0)+1,journalPositions:new Map,orderNeedsReconcile:a.orderNeedsReconcile,orderWantedGeneration:a.orderWantedGeneration,orderDemand:a.orderDemand},s.peer===!0)){const h=(a.orderRevision??0)+1,m=new Map;for(const y of a.records){const b=y.sourceEntryId??(y.kind==="tool"||y.kind==="supplement"?null:y.id);typeof b=="string"&&b.length>0&&b.length<=128&&m.set(b,h)}l={...l,...m.size>0?{journalBodyOwed:m}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(h,m,y)=>{if(!er(y))return;const b=d.get(h);b&&b.seq>=y||(d===u&&(d=new Map(d)),d.set(h,{entryId:m,seq:y}))};for(const[h,m]of Object.entries(t.journal_ordinals??{}))f(h,h,m);for(const h of n)typeof h.id=="string"&&(f(h.id,h.id,h.journal_seq),h.role==="tool"&&typeof h.tool_call_id=="string"&&f(`tool:${h.tool_call_id}`,h.id,h.journal_seq),typeof h.anchor=="string"&&f(`supplement:${h.anchor}`,h.id,h.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function Zc(e,t){if(!e.journalMode||typeof t.id!="string"||!Array.isArray(t.tool_calls))return e;let n=e.journalCallOwners??new Map,r=e.journalCallSlots??new Map;const o=n,s=r;return t.tool_calls.forEach((a,c)=>{!a||typeof a.id!="string"||(n.get(a.id)!==t.id&&(n===o&&(n=new Map(n)),n.set(a.id,t.id)),r.get(a.id)!==c&&(r===s&&(r=new Map(r)),r.set(a.id,c)))}),n===o&&r===s?e:{...e,journalCallOwners:n,journalCallSlots:r}}function Vp(e,t){const n=new Set(e.map(s=>s.id));let r=!1,o;for(let s=0;s<e.length;s++){const a=e[s];if(a.kind==="user"&&a.provisional===!0){o=a;continue}if(a.sourcePrecedes!==void 0){if(a.sourceAdmissionAnchor!==void 0){const{sourceAdmissionAnchor:c,...l}=a;e[s]=l,r=!0}o=e[s];continue}!t(a)&&o&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[s]={...a,sourceAdmissionAnchor:o.id},r=!0),o=e[s]}return r}function Zp(e,t,n,r,o){const s=[],a=new Set;let c=e,l;for(;c!==void 0;){if(o.has(c.id)){l=o.get(c.id);break}if(n(c)){l=r(c);break}if(c.kind==="user"&&c.provisional===!0||a.has(c.id))break;a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of s)o.set(d,l);return l}const Jw=Number.MAX_SAFE_INTEGER;function Qw(e,t){const n=new Map,r=new Map,o=new Map;for(const s of e){if(s.sourcePrecedes===void 0)continue;const a=t(s);if(a!==void 0)r.set(s.sourcePrecedes,a);else{const c=r.get(s.sourcePrecedes);c!==void 0&&n.set(s.id,{seq:c,slot:Jw})}}for(let s=e.length-1;s>=0;s--){const a=e[s];if(a.sourcePrecedes===void 0)continue;const c=t(a);if(c!==void 0)o.set(a.sourcePrecedes,c);else if(!n.has(a.id)){const l=o.get(a.sourcePrecedes);l!==void 0&&n.set(a.id,{seq:l,slot:-1})}}return n}function Yp(e,t){return{floor:Xw(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:Qw(e,t)}}function Jp(e,t,n,r){if(r===void 0||e.sourcePrecedes===void 0)return;const o=r.page.get(e.id);if(o!==void 0)return o;const s=new Set;let a=1,c=t.get(e.sourcePrecedes);for(;c!==void 0&&!s.has(c.id);){s.add(c.id);const l=n(c);if(l!==void 0)return{seq:l,slot:-a};const d=r.page.get(c.id);if(d!==void 0)return{seq:d.seq,slot:d.slot-a};a+=1,c=c.sourcePrecedes?t.get(c.sourcePrecedes):void 0}return r.floor===void 0?void 0:{seq:r.floor,slot:-a}}function Qp(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:r}=n,o=new Set;let s=1,a=t.get(e.sourcePrecedes);for(;a!==void 0&&!o.has(a.id);){if(a.sourcePrecedes===void 0){const c=r.get(a.id);return c===void 0?void 0:{slot:c,depth:s}}o.add(a.id),s+=1,a=t.get(a.sourcePrecedes)}}function Xw(e,t){let n;for(const r of e){if(r.sourcePrecedes!==void 0)continue;const o=t(r);o!==void 0&&(n===void 0||o<n)&&(n=o)}return n}function Xp(e,t){const n=new Map;return r=>{if(!r)return;const o=t(r);if(o===void 0)return;const s=[],a=new Set;let c=r,l=!0;for(;c;){if(n.has(c.id)){l=n.get(c.id)===!0;break}if(a.has(c.id)||t(c)===void 0){l=!1;break}a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of s)n.set(d,l);return l?o:void 0}}function Qs(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const o=new Map;t.forEach((a,c)=>{if(a.kind!=="tool")return;const l=n.get(a.toolCallId);if(l===void 0||!r.has(a.toolCallId))return;const d=o.get(l);d?d.push(c):o.set(l,[c])});let s=t;for(const a of o.values()){if(a.length<2)continue;const c=a.map(l=>t[l]).sort((l,d)=>(r.get(l.toolCallId)??0)-(r.get(d.toolCallId)??0));c.every((l,d)=>l===t[a[d]])||(s===t&&(s=t.slice()),a.forEach((l,d)=>{s[l]=c[d]}))}return s}function qp(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return qw(e,t);const n=e.journalGeneration,r=e.journalPositions;let o=!1,s=!1;const a=t.map(b=>{b.sourcePrecedes!==void 0&&(s=!0);let p=[r?.get(b.sourceEntryId??b.id),r?.get(b.id)].filter(T=>T!==void 0).sort((T,F)=>F.seq-T.seq)[0];if(b.journalGeneration===n&&er(b.journalSeq)&&(!p||b.journalSeq>p.seq)&&(p={entryId:b.sourceEntryId??b.id,seq:b.journalSeq}),!p||!n||!(b.kind==="user"&&(b.provisional===!0||b.local===!0))&&b.sourceEntryId===p.entryId&&b.journalSeq===p.seq&&b.journalGeneration===n)return b;o=!0;let k={...b,sourceEntryId:p.entryId,journalSeq:p.seq,journalGeneration:n};if(k.kind==="user"){const{provisional:T,local:F,...C}=k;k=C}return k});Vp(a,b=>b.journalGeneration===n&&er(b.journalSeq))&&(o=!0);const l=new Map,d=new Map(a.map(b=>[b.id,b])),u=Xp(d,b=>b!==void 0&&b.journalGeneration===n&&er(b.journalSeq)?b.journalSeq:void 0),f=b=>u(b)!==void 0,h=s?Yp(a,u):void 0,m=(b,v)=>{const p=u(b);if(b.kind==="user"&&b.provisional===!0&&p===void 0)return[1,0,0,0,v];const A=b.kind==="supplement"?b.anchor:b.kind==="tool"?e.journalCallOwners?.get(b.toolCallId)??e.argsByCall.get(b.toolCallId)?.anchorId:void 0,k=typeof A=="string"?u(d.get(A)):void 0,T=k===void 0&&p===void 0?Jp(b,d,u,h):void 0,F=p===void 0&&T===void 0?Zp(b,d,f,u,l):void 0,C=k??p??T?.seq??F;if(C===void 0){const I=Qp(b,d,h);return[1,I?.slot??v,I?-I.depth:0,0,v]}return[0,C,k!==void 0?1:p!==void 0?0:T!==void 0?T.slot:2,p??Number.MAX_SAFE_INTEGER,v]},y=a.map((b,v)=>({record:b,index:v,rank:m(b,v)}));return y.sort((b,v)=>{for(let p=0;p<b.rank.length;p++){const A=b.rank[p]-v.rank[p];if(A)return A}return 0}),!o&&y.every((b,v)=>b.index===v)?Qs(e,t):Qs(e,y.map(b=>b.record))}function qw(e,t){const n=e.journalGeneration,r=e.journalPositions,o=new Map;let s=!1;for(const p of t){p.sourcePrecedes!==void 0&&(s=!0);let k=[r?.get(p.sourceEntryId??p.id),r?.get(p.id)].filter(T=>T!==void 0).sort((T,F)=>F.seq-T.seq)[0];p.journalGeneration===n&&er(p.journalSeq)&&(!k||p.journalSeq>k.seq)&&(k={entryId:p.sourceEntryId??p.id,seq:p.journalSeq}),k&&o.set(p.id,k)}const a=p=>p===void 0?void 0:o.get(p.id)??r?.get(p.sourceEntryId??p.id)??r?.get(p.id);let c=!1;const l=t.slice();Vp(l,p=>p.journalGeneration===n&&er(p.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(p=>[p.id,p])),h=Xp(f,p=>a(p)?.seq),m=p=>h(p)!==void 0,y=s?Yp(l,h):void 0,b=(p,A)=>{const k=h(p);if(p.kind==="user"&&p.provisional===!0&&k===void 0)return[1,0,0,0,A];const T=p.kind==="supplement"?p.anchor:p.kind==="tool"?e.journalCallOwners?.get(p.toolCallId)??e.argsByCall.get(p.toolCallId)?.anchorId:void 0,F=typeof T=="string"?h(f.get(T)):void 0,C=F===void 0&&k===void 0?Jp(p,f,h,y):void 0,I=k===void 0&&C===void 0?Zp(p,f,m,h,u):void 0,g=F??k??C?.seq??I;if(g===void 0){const w=Qp(p,f,y);return[1,w?.slot??A,w?-w.depth:0,0,A]}return[0,g,F!==void 0?1:k!==void 0?0:C!==void 0?C.slot:2,k??Number.MAX_SAFE_INTEGER,A]},v=l.map((p,A)=>({record:p,index:A,rank:b(p,A)}));return v.sort((p,A)=>{for(let k=0;k<p.rank.length;k++){const T=p.rank[k]-A.rank[k];if(T)return T}return 0}),!c&&v.every((p,A)=>p.index===A)?Qs(e,t):Qs(e,v.map(p=>p.record))}function Zt(e){const t=e.records.filter(o=>o.kind==="user"&&o.provisional===!0),n=e.records.filter(o=>o.journalGeneration!==e.journalGeneration||!er(o.journalSeq)),r=[...t,...n].map(o=>o.sourceEntryId??(o.kind==="tool"||o.kind==="supplement"?null:o.id));if(r.push(...Yc(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let o=r.length-1;o>=0;o--){const s=r[o];typeof s=="string"&&e.journalSourceVoid.has(s)&&r.splice(o,1)}return[...new Set(r.filter(o=>typeof o=="string"&&o.length>0&&o.length<=128))]}function Yc(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const o=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof o=="string"&&o.length>0&&o.length<=128&&t.add(o)}const n=[];for(const r of e.journalBodyOwed.keys())r.length<1||r.length>128||t.has(r)&&(e.journalSourceVoid?.has(r)||n.push(r));return n}function eh(e,t){const n=e.journalPositions;return Zt(e).filter(r=>!n?.has(r)&&!t?.has(r))}const Ct=e=>e.orderRevision??0;async function e0(e){const t=new Map,n=c=>{let l=t.get(c);return l||(l=new Set,t.set(c,l)),l},r=(c,l)=>l==="payload"?Yc(c):l==="lookup"?eh(c):Zt(c);let o=e.getTranscript().journalGeneration,s=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=Ka(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",h=_v(r(c,f).filter(v=>!n(f).has(v)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),m=await e.read(h,f);if(!e.isCurrent()||Ct(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(m,d,l),!e.isCurrent())return{kind:"stale"};const y=e.getTranscript(),b=e.page(m);if(b.journal_order_state==="ready"&&b.journal_generation===y.journalGeneration){b.journal_generation!==o&&(t.clear(),o=b.journal_generation);for(const A of h)n(f).add(A);if(y.orderNeedsReconcile){if(y.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear();continue}if(f==="payload"){const A=(b.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 v=e.sweep?.(y,n);if(v?.kind==="none")return{kind:"complete",transcript:y};const p=v?.kind??"authority";if(r(y,p).some(A=>!n(p).has(A)))continue;return{kind:"complete",transcript:y}}if(!y.orderNeedsReconcile||y.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear()}}function Dt(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const o=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof o=="string"&&o?o:e.id}function Xi(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function cu(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function oM(e){if(!e||e.runs_state!=="ready")return null;const t=e.runs;if(!t||t.length===0)return null;const n=new Map;for(const s of t){if(!s.settled||typeof s.run_key!="string"||s.run_key.length===0)continue;const a=Xi(s.action_count);if(a===null)continue;const c={actions:a,workedSeconds:cu(s.worked_seconds),failed:Xi(s.failed_count)??0,complete:s.complete!==!1,openingUserId:typeof s.opening_user_id=="string"&&s.opening_user_id.length>0?s.opening_user_id:null,closingAnswerId:typeof s.closing_answer_id=="string"&&s.closing_answer_id.length>0?s.closing_answer_id:null,crossSessionActions:Xi(s.cross_session_action_count),crossSessionWorkedSeconds:cu(s.cross_session_worked_seconds)};n.set(s.run_key,c),c.openingUserId!==null&&n.set(c.openingUserId,c),c.closingAnswerId!==null&&n.set(c.closingAnswerId,c)}if(n.size===0)return null;const r=new Set;for(const s of e.entries)r.add(Dt(s));const o=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:o?Dt(o):null}}}function t0(e){if(!e||e.runs_state!=="ready"||e.head_cut===!0)return null;const t=e.runs,n=e.entries[0];if(!n||!t||t.length===0||!t.find(s=>s.opening_user_id===n.id))return null;const o=Math.round((n.ts??0)*1e3);return o>0?{id:n.id,tsMs:o}:null}function n0(e,t,n){const r=t0(e),o=e?.entries;if(r===null||!o||o.length===0)return!1;const s=Math.round((o[o.length-1].ts??0)*1e3);if(!(s>r.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>r.tsMs)||!(c<s)))return!1;return!0}const Jc=new Set,Dn="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Qc=new RegExp(`[${Dn}]`),r0=new RegExp(`[${Dn}]+`),sM=new RegExp(`[${Dn}]+`,"g"),o0=new RegExp(`^[${Dn}]+|[${Dn}]+$`,"g"),s0=new RegExp(`^[${Dn}]+`),iM=new RegExp(`[^${Dn}]`);function qt(e){return e.replace(o0,"")}function Do(e){return e.replace(s0,"")}function th(e,t){return t===0||Qc.test(e[t-1])}function nh(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&th(e,n)&&t.push(n);return t}function Xc(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
2
2
  `,n-1)+1,o=e.indexOf(`
3
- `,n),s=o===-1?e.length:o;let a=e.slice(r,s);return a.endsWith("\r")&&(a=a.slice(0,-1)),{line:a,lineStart:r,column:n-r}}function s0(e,t){if(t.size===0)return null;for(const n of th(e)){const r=e.slice(n+1),o=r.indexOf(" ");if(o!==-1&&t.has(r.slice(0,o).toLowerCase()))return n}return null}function Xc(e,t,n){const r=s0(e,n);let o=null;for(const s of th(e)){if(s===r)return t>s?s:o;s<=t&&(o=s)}return o}function i0(e,t=null,n=Yc){const{line:r,lineStart:o,column:s}=Qc(e,t),a=Xc(r,s,n);if(a===null)return null;let c=a+1;for(;c<r.length&&!Jc.test(r[c]);)c++;return s>c?null:{start:o+a,query:r.slice(a+1,c),end:o+c}}function iM(e,t=null,n=Yc){const{line:r,lineStart:o,column:s}=Qc(e,t),a=Xc(r,s,n);return a===null?null:{start:o+a,end:o+r.length}}function a0(e,t,n=null,r=Yc){const{line:o,lineStart:s,column:a}=Qc(e,n),c=r.size>0?r:new Set(t.map(m=>m.toLowerCase())),l=Xc(o,a,c);if(l===null)return null;const d=o.slice(l+1),u=d.indexOf(" ");if(u===-1)return null;const f=d.slice(0,u);if(!t.some(m=>m.toLowerCase()===f.toLowerCase()))return null;const h=l+1+f.length;return a<=h?null:{value:d.slice(u+1),start:s+h+1,end:s+o.length,tokenStart:s+l}}function cu(e,t){return qt(e.slice(0,t))===""}function aM(e,t,n,r){const o=a0(e,r,t,n);if(o!==null&&cu(e,o.tokenStart))return"argument";const s=i0(e,t,n);return s!==null&&cu(e,s.start)?"command":null}function cM(e,t,n,r){let o=t,s=n;const a=c=>c>=0&&c<e.length&&`
4
- `.includes(e[c]);return r===""?o>0&&a(o-1)?o-=1:a(s)&&(s+=1):o===0&&a(s)&&(s+=1),{text:`${e.slice(0,o)}${r}${e.slice(s)}`,caret:o+r.length}}const c0=1e3,l0=900,d0=40,nh=3;function u0(e,t){let n=0,r=-2,o=0;for(const s of e){const a=t.indexOf(s,o);if(a<0)return 0;n+=a===r+1?2:1,r=a,o=a+1}return n<=0?0:Math.max(1,Math.min(d0,n))}function rh(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n?n===r?c0:r.startsWith(n)?l0:u0(n,r):0}function f0(e){const n=qt(e).split(n0).pop()??"";return n.startsWith("/")?n.slice(1):n}function p0(e,t){const n=f0(e),r=[];return t.forEach((o,s)=>{let a=0,c=o.name;for(const l of[o.name,...o.aliases]){const d=rh(n,l);d>a&&(a=d,c=l)}a>0&&r.push({score:a,index:s,name:c,command:o})}),r.sort((o,s)=>s.score-o.score||o.index-s.index),r.map(o=>({name:o.name,command:o.command}))}function lM(e,t){if(!e)return t.map(s=>({name:s.name,command:s}));const n=p0(`/${e}`,t);if(e.length>=nh)return n;const r=e.toLowerCase(),o=n.filter(({name:s})=>s.toLowerCase().startsWith(r));return o.length>0?o:n}function lu(e,t){if(!e)return t.map(r=>({name:r.name,choice:r}));const n=[];return t.forEach((r,o)=>{const s=Math.max(0,...[r.name,...r.aliases??[]].map(a=>rh(e,a)));s>0&&n.push({score:s,order:o,choice:r})}),n.sort((r,o)=>o.score-r.score||r.order-o.order),n.map(r=>({name:r.choice.name,choice:r.choice}))}const du=/^-+/;function dM(e,t,n,r,o){if(o)return!0;const s=qt(e).toLowerCase(),a=qt(t).toLowerCase();return s===a||s.length>0&&s.replace(du,"")===a.replace(du,"")?!0:!r&&n<=1}const h0=new RegExp("\\p{Ll}","u");function oh(e){for(const t of e)if(h0.test(t))return!0;return!1}function uM(e,t,n){if(n){if(!e)return t.map(a=>({name:a.name,choice:a}));const r=lu(e,t);if(e.length>=nh)return r;const o=e.toLowerCase(),s=r.filter(a=>a.name.toLowerCase().startsWith(o));return s.length>0?s:r}return oh(e)?lu(e,t).filter(r=>r.name.startsWith(e)):[]}const m0=/<skill name="([^"]*)" invocation="([^"]*)">/,g0=/[A-Za-z0-9]/,_0=/[A-Za-z0-9._-]/,b0=/[._-]/;function v0(e,t){if(t>=e.length||!g0.test(e[t]))return t;let n=t+1;for(;n<e.length&&_0.test(e[n]);)n++;return n}function y0(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!eh(e,n)){n+=1;continue}const r=v0(e,n+1);r>n+1&&t.push({start:n,end:r,name:e.slice(n+1,r)}),n+=Math.max(r-n,1)}return t}function w0(e,t,n,r,o,s){let a=n;for(;;){const c=e.slice(t+1,a);if(r.has(c))return{end:a,name:c};if(s||oh(c)){const l=o.get(c.toLowerCase());if(l!==void 0)return{end:a,name:l}}if(a>t+2&&b0.test(e[a-1])){a-=1;continue}return null}}function k0(e,t,n={}){return sh(e,t,n.skipSpans??[],!0)}function fM(e,t,n={}){return sh(e,t,n.skipSpans??[],!1)}function sh(e,t,n,r){const o=new Set(t),s=new Map;for(const l of t)s.has(l.toLowerCase())||s.set(l.toLowerCase(),l);const a=[],c=new Set;for(const l of y0(e)){if(n.some(([f,h])=>f<=l.start&&l.start<h))continue;const d=Do(e.slice(0,l.start))==="",u=w0(e,l.start,l.end,o,s,d);u===null||r&&c.has(u.name)||(c.add(u.name),a.push({start:l.start,end:u.end,text:e.slice(l.start,u.end),name:u.name,leading:d}))}return a}const Ir="<operator-skills>",Xs="</operator-skills>",lo=`
3
+ `,n),s=o===-1?e.length:o;let a=e.slice(r,s);return a.endsWith("\r")&&(a=a.slice(0,-1)),{line:a,lineStart:r,column:n-r}}function i0(e,t){if(t.size===0)return null;for(const n of nh(e)){const r=e.slice(n+1),o=r.indexOf(" ");if(o!==-1&&t.has(r.slice(0,o).toLowerCase()))return n}return null}function qc(e,t,n){const r=i0(e,n);let o=null;for(const s of nh(e)){if(s===r)return t>s?s:o;s<=t&&(o=s)}return o}function a0(e,t=null,n=Jc){const{line:r,lineStart:o,column:s}=Xc(e,t),a=qc(r,s,n);if(a===null)return null;let c=a+1;for(;c<r.length&&!Qc.test(r[c]);)c++;return s>c?null:{start:o+a,query:r.slice(a+1,c),end:o+c}}function aM(e,t=null,n=Jc){const{line:r,lineStart:o,column:s}=Xc(e,t),a=qc(r,s,n);return a===null?null:{start:o+a,end:o+r.length}}function c0(e,t,n=null,r=Jc){const{line:o,lineStart:s,column:a}=Xc(e,n),c=r.size>0?r:new Set(t.map(m=>m.toLowerCase())),l=qc(o,a,c);if(l===null)return null;const d=o.slice(l+1),u=d.indexOf(" ");if(u===-1)return null;const f=d.slice(0,u);if(!t.some(m=>m.toLowerCase()===f.toLowerCase()))return null;const h=l+1+f.length;return a<=h?null:{value:d.slice(u+1),start:s+h+1,end:s+o.length,tokenStart:s+l}}function lu(e,t){return qt(e.slice(0,t))===""}function cM(e,t,n,r){const o=c0(e,r,t,n);if(o!==null&&lu(e,o.tokenStart))return"argument";const s=a0(e,t,n);return s!==null&&lu(e,s.start)?"command":null}function lM(e,t,n,r){let o=t,s=n;const a=c=>c>=0&&c<e.length&&`
4
+ `.includes(e[c]);return r===""?o>0&&a(o-1)?o-=1:a(s)&&(s+=1):o===0&&a(s)&&(s+=1),{text:`${e.slice(0,o)}${r}${e.slice(s)}`,caret:o+r.length}}const l0=1e3,d0=900,u0=40,rh=3;function f0(e,t){let n=0,r=-2,o=0;for(const s of e){const a=t.indexOf(s,o);if(a<0)return 0;n+=a===r+1?2:1,r=a,o=a+1}return n<=0?0:Math.max(1,Math.min(u0,n))}function oh(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n?n===r?l0:r.startsWith(n)?d0:f0(n,r):0}function p0(e){const n=qt(e).split(r0).pop()??"";return n.startsWith("/")?n.slice(1):n}function h0(e,t){const n=p0(e),r=[];return t.forEach((o,s)=>{let a=0,c=o.name;for(const l of[o.name,...o.aliases]){const d=oh(n,l);d>a&&(a=d,c=l)}a>0&&r.push({score:a,index:s,name:c,command:o})}),r.sort((o,s)=>s.score-o.score||o.index-s.index),r.map(o=>({name:o.name,command:o.command}))}function dM(e,t){if(!e)return t.map(s=>({name:s.name,command:s}));const n=h0(`/${e}`,t);if(e.length>=rh)return n;const r=e.toLowerCase(),o=n.filter(({name:s})=>s.toLowerCase().startsWith(r));return o.length>0?o:n}function du(e,t){if(!e)return t.map(r=>({name:r.name,choice:r}));const n=[];return t.forEach((r,o)=>{const s=Math.max(0,...[r.name,...r.aliases??[]].map(a=>oh(e,a)));s>0&&n.push({score:s,order:o,choice:r})}),n.sort((r,o)=>o.score-r.score||r.order-o.order),n.map(r=>({name:r.choice.name,choice:r.choice}))}const uu=/^-+/;function uM(e,t,n,r,o){if(o)return!0;const s=qt(e).toLowerCase(),a=qt(t).toLowerCase();return s===a||s.length>0&&s.replace(uu,"")===a.replace(uu,"")?!0:!r&&n<=1}const m0=new RegExp("\\p{Ll}","u");function sh(e){for(const t of e)if(m0.test(t))return!0;return!1}function fM(e,t,n){if(n){if(!e)return t.map(a=>({name:a.name,choice:a}));const r=du(e,t);if(e.length>=rh)return r;const o=e.toLowerCase(),s=r.filter(a=>a.name.toLowerCase().startsWith(o));return s.length>0?s:r}return sh(e)?du(e,t).filter(r=>r.name.startsWith(e)):[]}const g0=/<skill name="([^"]*)" invocation="([^"]*)">/,_0=/[A-Za-z0-9]/,b0=/[A-Za-z0-9._-]/,v0=/[._-]/;function y0(e,t){if(t>=e.length||!_0.test(e[t]))return t;let n=t+1;for(;n<e.length&&b0.test(e[n]);)n++;return n}function w0(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!th(e,n)){n+=1;continue}const r=y0(e,n+1);r>n+1&&t.push({start:n,end:r,name:e.slice(n+1,r)}),n+=Math.max(r-n,1)}return t}function k0(e,t,n,r,o,s){let a=n;for(;;){const c=e.slice(t+1,a);if(r.has(c))return{end:a,name:c};if(s||sh(c)){const l=o.get(c.toLowerCase());if(l!==void 0)return{end:a,name:l}}if(a>t+2&&v0.test(e[a-1])){a-=1;continue}return null}}function S0(e,t,n={}){return ih(e,t,n.skipSpans??[],!0)}function pM(e,t,n={}){return ih(e,t,n.skipSpans??[],!1)}function ih(e,t,n,r){const o=new Set(t),s=new Map;for(const l of t)s.has(l.toLowerCase())||s.set(l.toLowerCase(),l);const a=[],c=new Set;for(const l of w0(e)){if(n.some(([f,h])=>f<=l.start&&l.start<h))continue;const d=Do(e.slice(0,l.start))==="",u=k0(e,l.start,l.end,o,s,d);u===null||r&&c.has(u.name)||(c.add(u.name),a.push({start:l.start,end:u.end,text:e.slice(l.start,u.end),name:u.name,leading:d}))}return a}const Ir="<operator-skills>",Xs="</operator-skills>",lo=`
5
5
 
6
- `,ih="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>`.",qc="​",S0=Ir.replace("<",`<${qc}`),E0=Xs.replace("<",`<${qc}`),A0=`<${qc}skill name=`,I0=/^<skill name="([^"]*)">/;function R0(e){return e.replace(/<\/operator-skills>/g,E0).replace(/<operator-skills>/g,S0).replace(/<skill name="/g,A0)}function pM(e){const t=e.map(({name:n,body:r})=>`<skill name="${n}">
7
- ${R0(r)}
8
- </skill>`);return Ir+lo+ih+lo+t.join(lo)+lo+Xs}function el(e){const t=[],n=Ir+lo+ih;let r=0;for(;;){const o=e.indexOf(n,r);if(o===-1)return t;const s=e.indexOf(Xs,o+n.length),a=e.indexOf(Ir,o+Ir.length);if(s===-1||a!==-1&&a<s){r=o+Ir.length;continue}const c=s+Xs.length;t.push([o,c]),r=c}}function x0(e){const t=[];for(const[n,r]of el(e)){let o=0;for(const s of e.slice(n,r).split(`
9
- `)){if(o>0){s.startsWith("</skill>")&&(o-=1);continue}const a=I0.exec(s);a!==null&&(t.push(a[1]),o=1)}}return t}function hM(e,t){const n=el(e),r=k0(e,t,{skipSpans:n});if(r.length===0)return[];const o=new Set(x0(e));return r.filter(s=>!o.has(s.name))}const uu=new RegExp(`[${Dn}]+$`);function ah(e){const t=el(e);if(t.length===0)return e;const n=[];let r=0;for(const[s,a]of[...t].sort((c,l)=>c[0]-l[0])){if(a<=r)continue;const c=Math.max(s,r);n.push(e.slice(r,c).replace(uu,"")),r=a}n.push(e.slice(r).replace(uu,""));let o="";for(const s of n)s&&(o&&!Jc.test(s[0])&&(o+=" "),o+=s);return o}function mM(e){if(!e||qt(e)==="")return!1;let t=Do(e);if(t.startsWith("---")){const n=t.slice(3),r=n.indexOf(`
10
- ---`);r!==-1&&(t=n.slice(r+4))}return qt(t)!==""}function T0(e){return e.replace(/&#10;/g,`
11
- `).replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&quot;/g,'"').replace(/&amp;/g,"&")}const nt=[];for(let e=0;e<256;++e)nt.push((e+256).toString(16).slice(1));function C0(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 Xi;const O0=new Uint8Array(16);function P0(){if(!Xi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Xi=crypto.getRandomValues.bind(crypto)}return Xi(O0)}const M0=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),fu={randomUUID:M0};function j0(e,t,n){if(fu.randomUUID&&!e)return fu.randomUUID();e=e||{};const r=e.random??e.rng?.()??P0();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,C0(r)}const ch=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,Ka=e=>{let t=e;for(;;){const n=ch.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},pu=e=>{const t=[];let n=e;for(;;){const r=ch.exec(n);if(r===null)break;t.push({id:j0(),text:r[1]}),n=n.slice(r[0].length)}return{replies:t,remainingContent:n.trim()}};function vi(e){return tl(e)?.skill}const $0=/^\s/,N0=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,D0=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function L0(e){const t=Do(e);if(!t.startsWith("---"))return null;const r=t.slice(3).indexOf(`
12
- ---`);return r===-1?null:e.length-t.length+3+r+4}function F0(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function hu(e,t){const n=[];for(let r=1;r<e.length;r+=1){const o=e[r];if(t==='"'&&o==="\\"&&r+1<e.length){n.push(o,e[r+1]),r+=1;continue}if(o!==t){n.push(o);continue}if(t==="'"&&e[r+1]==="'"){n.push(o,o),r+=1;continue}const s=e.slice(r+1).trim();if(s!==""&&!s.startsWith("#"))return null;const a=n.join(""),c=t==="'"?a.replace(/''/g,"'"):F0(a);return c===""?null:c}return null}function U0(e){const t=e.split(`
13
- `);for(const[n,r]of t.entries()){if(!r.startsWith("description:"))continue;const o=r.slice(12).trim(),s=o!==""&&N0.test(o),a=[];o!==""&&!s&&a.push(o);for(let u=n+1;u<t.length;u+=1){const f=t[u];if(f.trim()!==""){if(!$0.test(f))break;a.push(f.trim())}}if(a.length===0)return null;const c=a.join(" ");if(s)return c.trim()===""?null:c.trim();if(c.startsWith('"'))return hu(c,'"');if(c.startsWith("'"))return hu(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function tl(e){const{prefix:t,rest:n}=Ka(e),r=n.slice(0,n.length-Do(n).length),o=Do(n),s=D0.exec(o);if(s===null)return null;const a=m0.exec(o.slice(s[0].length));if(a===null||a.index!==0||a[1]!==s[1])return null;const c=s[0].length+a[0].length,l=o.indexOf("</skill>",c);if(l===-1)return null;const d=o.slice(c,l),u=L0(d),f=u===null?null:U0(d.slice(0,u)),h=a[1],m=T0(a[2]);return{text:t+r+m,skill:{name:h,token:`$${h}`,request:qt(o.slice(l+8)),purpose:f,body:qt(u===null?d:d.slice(u))}}}function gM(e){const t=tl(e);if(t!==null)return t.text;const n=ah(e);return n===e?e:qt(n)}function B0(e){const t=tl(e);if(t===null){const r=ah(e);if(r===e)return null;const{prefix:o}=Ka(e);return{replies:pu(e).replies,text:r.slice(o.length).trimStart()}}const{prefix:n}=Ka(e);return{replies:pu(e).replies,text:t.text.slice(n.length).trimStart()}}function _M(e){return B0(e)?.text??e}const H0=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"]]),W0=/\blabel=(['"])(.*?)\1/,G0=/\bjob=(['"])(.*?)\1/,z0=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function Va(e){const t=typeof e.text=="string"?e.text:"",n=z0.exec(t);let r=n?.[2];const o=r?.indexOf(`
6
+ `,ah="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>`.",el="​",E0=Ir.replace("<",`<${el}`),A0=Xs.replace("<",`<${el}`),I0=`<${el}skill name=`,R0=/^<skill name="([^"]*)">/;function x0(e){return e.replace(/<\/operator-skills>/g,A0).replace(/<operator-skills>/g,E0).replace(/<skill name="/g,I0)}function hM(e){const t=e.map(({name:n,body:r})=>`<skill name="${n}">
7
+ ${x0(r)}
8
+ </skill>`);return Ir+lo+ah+lo+t.join(lo)+lo+Xs}function tl(e){const t=[],n=Ir+lo+ah;let r=0;for(;;){const o=e.indexOf(n,r);if(o===-1)return t;const s=e.indexOf(Xs,o+n.length),a=e.indexOf(Ir,o+Ir.length);if(s===-1||a!==-1&&a<s){r=o+Ir.length;continue}const c=s+Xs.length;t.push([o,c]),r=c}}function T0(e){const t=[];for(const[n,r]of tl(e)){let o=0;for(const s of e.slice(n,r).split(`
9
+ `)){if(o>0){s.startsWith("</skill>")&&(o-=1);continue}const a=R0.exec(s);a!==null&&(t.push(a[1]),o=1)}}return t}function mM(e,t){const n=tl(e),r=S0(e,t,{skipSpans:n});if(r.length===0)return[];const o=new Set(T0(e));return r.filter(s=>!o.has(s.name))}const fu=new RegExp(`[${Dn}]+$`);function ch(e){const t=tl(e);if(t.length===0)return e;const n=[];let r=0;for(const[s,a]of[...t].sort((c,l)=>c[0]-l[0])){if(a<=r)continue;const c=Math.max(s,r);n.push(e.slice(r,c).replace(fu,"")),r=a}n.push(e.slice(r).replace(fu,""));let o="";for(const s of n)s&&(o&&!Qc.test(s[0])&&(o+=" "),o+=s);return o}function gM(e){if(!e||qt(e)==="")return!1;let t=Do(e);if(t.startsWith("---")){const n=t.slice(3),r=n.indexOf(`
10
+ ---`);r!==-1&&(t=n.slice(r+4))}return qt(t)!==""}function C0(e){return e.replace(/&#10;/g,`
11
+ `).replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&quot;/g,'"').replace(/&amp;/g,"&")}const tt=[];for(let e=0;e<256;++e)tt.push((e+256).toString(16).slice(1));function O0(e,t=0){return(tt[e[t+0]]+tt[e[t+1]]+tt[e[t+2]]+tt[e[t+3]]+"-"+tt[e[t+4]]+tt[e[t+5]]+"-"+tt[e[t+6]]+tt[e[t+7]]+"-"+tt[e[t+8]]+tt[e[t+9]]+"-"+tt[e[t+10]]+tt[e[t+11]]+tt[e[t+12]]+tt[e[t+13]]+tt[e[t+14]]+tt[e[t+15]]).toLowerCase()}let qi;const P0=new Uint8Array(16);function M0(){if(!qi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");qi=crypto.getRandomValues.bind(crypto)}return qi(P0)}const j0=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),pu={randomUUID:j0};function $0(e,t,n){if(pu.randomUUID&&!e)return pu.randomUUID();e=e||{};const r=e.random??e.rng?.()??M0();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,O0(r)}const lh=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,Va=e=>{let t=e;for(;;){const n=lh.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},hu=e=>{const t=[];let n=e;for(;;){const r=lh.exec(n);if(r===null)break;t.push({id:$0(),text:r[1]}),n=n.slice(r[0].length)}return{replies:t,remainingContent:n.trim()}};function vi(e){return nl(e)?.skill}const N0=/^\s/,D0=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,L0=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function F0(e){const t=Do(e);if(!t.startsWith("---"))return null;const r=t.slice(3).indexOf(`
12
+ ---`);return r===-1?null:e.length-t.length+3+r+4}function U0(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function mu(e,t){const n=[];for(let r=1;r<e.length;r+=1){const o=e[r];if(t==='"'&&o==="\\"&&r+1<e.length){n.push(o,e[r+1]),r+=1;continue}if(o!==t){n.push(o);continue}if(t==="'"&&e[r+1]==="'"){n.push(o,o),r+=1;continue}const s=e.slice(r+1).trim();if(s!==""&&!s.startsWith("#"))return null;const a=n.join(""),c=t==="'"?a.replace(/''/g,"'"):U0(a);return c===""?null:c}return null}function B0(e){const t=e.split(`
13
+ `);for(const[n,r]of t.entries()){if(!r.startsWith("description:"))continue;const o=r.slice(12).trim(),s=o!==""&&D0.test(o),a=[];o!==""&&!s&&a.push(o);for(let u=n+1;u<t.length;u+=1){const f=t[u];if(f.trim()!==""){if(!N0.test(f))break;a.push(f.trim())}}if(a.length===0)return null;const c=a.join(" ");if(s)return c.trim()===""?null:c.trim();if(c.startsWith('"'))return mu(c,'"');if(c.startsWith("'"))return mu(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function nl(e){const{prefix:t,rest:n}=Va(e),r=n.slice(0,n.length-Do(n).length),o=Do(n),s=L0.exec(o);if(s===null)return null;const a=g0.exec(o.slice(s[0].length));if(a===null||a.index!==0||a[1]!==s[1])return null;const c=s[0].length+a[0].length,l=o.indexOf("</skill>",c);if(l===-1)return null;const d=o.slice(c,l),u=F0(d),f=u===null?null:B0(d.slice(0,u)),h=a[1],m=C0(a[2]);return{text:t+r+m,skill:{name:h,token:`$${h}`,request:qt(o.slice(l+8)),purpose:f,body:qt(u===null?d:d.slice(u))}}}function _M(e){const t=nl(e);if(t!==null)return t.text;const n=ch(e);return n===e?e:qt(n)}function H0(e){const t=nl(e);if(t===null){const r=ch(e);if(r===e)return null;const{prefix:o}=Va(e);return{replies:hu(e).replies,text:r.slice(o.length).trimStart()}}const{prefix:n}=Va(e);return{replies:hu(e).replies,text:t.text.slice(n.length).trimStart()}}function bM(e){return H0(e)?.text??e}const W0=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"]]),G0=/\blabel=(['"])(.*?)\1/,z0=/\bjob=(['"])(.*?)\1/,K0=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function Za(e){const t=typeof e.text=="string"?e.text:"",n=K0.exec(t);let r=n?.[2];const o=r?.indexOf(`
14
14
 
15
- `)??-1,a=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&o>=0?H0.get((r??"").slice(0,o)):void 0;n?.[1]==="parent-message"&&a&&(r=(r??"").slice(o+2));const c=typeof e.direction=="string"?e.direction:n?.[1]==="subagent-message"?"to_parent":a?"to_child":"";return{body:typeof e.body=="string"?e.body:r?.trim()?r:t,envelope:t,direction:c,label:Fr(e.label??(n&&W0.exec(n[0].split(`
16
- `,1)[0])?.[2])),jobId:Fr(e.job_id??(n&&G0.exec(n[0].split(`
17
- `,1)[0])?.[2])),sender:hh(e).sender,expectsReply:typeof e.expects_reply=="boolean"?e.expects_reply:e.expects_reply===void 0&&a?a==="ask":null,steer:typeof e.steer=="boolean"?e.steer:e.steer===void 0&&a?a==="steer":null}}function bM(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 K0(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 vM(e){return K0(e)!==null}const lh=/\s+/,V0=/[\\/]+$/,Z0=/[\\/]/,dh=`
15
+ `)??-1,a=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&o>=0?W0.get((r??"").slice(0,o)):void 0;n?.[1]==="parent-message"&&a&&(r=(r??"").slice(o+2));const c=typeof e.direction=="string"?e.direction:n?.[1]==="subagent-message"?"to_parent":a?"to_child":"";return{body:typeof e.body=="string"?e.body:r?.trim()?r:t,envelope:t,direction:c,label:Fr(e.label??(n&&G0.exec(n[0].split(`
16
+ `,1)[0])?.[2])),jobId:Fr(e.job_id??(n&&z0.exec(n[0].split(`
17
+ `,1)[0])?.[2])),sender:mh(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 vM(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 V0(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 yM(e){return V0(e)!==null}const dh=/\s+/,Z0=/[\\/]+$/,Y0=/[\\/]/,uh=`
18
18
 
19
- `,Y0=" — cancel with wake(",J0=120,uh=/(?:\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,Q0=new RegExp("\\p{Cf}","gu"),X0=4096;function Fr(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(uh,"").replace(Q0,"").split(lh).filter(Boolean).join(" ").slice(0,J0)}const yM={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function fh(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(V0,"");if(t){const n=t.split(Z0).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function ph(e){const{name:t,quoted:n}=fh(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function q0(e){const{name:t,quoted:n}=fh(e),r=[];return e.pid&&r.push(`pid ${e.pid}`),e.modelLabel&&r.push(e.modelLabel),t?[n?`"${t}"`:t,...r].join(" · "):r.length>0?r.join(" · "):"another session"}function wM(e,t){return t.trim()?!0:q0(e)!==ph(e)}function ek(e){for(const t of e.slice(0,X0).split(`
20
- `)){const n=Fr(t);if(n)return n}return""}function kM(e,t){const n=ph(e),r=ek(t);return r?`${n} · ${r}`:n}function qi(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const tk=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,nk=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,rk=/^<peer-session-message[^>]*>/,ok=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function hh(e){const t=String(e.text??e.detail??""),n=tk.exec(t.trim()),r={};if(n)for(const d of n[1].matchAll(ok))r[d[1]]=d[2]??d[3]??d[4]??"";const o=n?n[2]:"",a=(String(e.body??"").trim()||o||(n?"":t.trim().replace(rk,""))).replace(nk,"").trim(),c=e.sender??{},l=(d,u)=>Fr(d)||Fr(u);return{body:a,sender:{pid:l(c.pid,r.from_pid),conversationName:l(c.conversation_name,r.conversation),cwd:l(c.cwd,void 0),sessionId:l(c.session_id,void 0),modelLabel:l(c.model_label,r.model)}}}function sk(e){return!!e.wake_catchup}function ik(e){return e.hidden===!0}function SM(e){let t=e.split(dh)[0]??"";t=t.split(lh).filter(Boolean).join(" "),t=t.split(Y0)[0];const n="(alarm) ";for(;t.startsWith(n);)t=t.slice(n.length);const r="Scheduled wake ";return t.startsWith(r)&&(t=t.slice(r.length)),t.trim()}function EM(e){const t=e.indexOf(dh);return t===-1?"":e.slice(t+2).trim()}const gs=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},qr=e=>typeof e=="string"?Fr(e):"";function ak(e){const t=gs(e.bridge_receipt),n=t.v===1,r=gs(n?t.sender:e.sender),o=n?gs(t.conversation):{},s=n?t.attachment_count:void 0;return{sender:{name:qr(r.name),...r.kind==="human"||r.kind==="agent"?{kind:r.kind}:{},...qr(r.organization)?{organization:qr(r.organization)}:{}},conversation:{...o.kind==="dm"||o.kind==="group"||o.kind==="channel"?{kind:o.kind}:{},...qr(o.label)?{label:qr(o.label)}:{}},...typeof s=="number"&&Number.isSafeInteger(s)&&s>=0?{attachmentCount:s}:{}}}const ck=new Set(["channel_post","channel_create","channel_history","channel_thread","react","shared_history"]),lk=new Set(["channel_post","dm","send","reply"]),dk=new Set(["take_up","ack","send","reply","channels","channel_create","channel_post","channel_history","react","channel_thread","directory","dm","shared_conversations","shared_history"]),uk=/^(?:bcv|bcmsg|acc|ep)_/i,fk=/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]|\x9b[0-?]*[ -/]*[@-~]/g,pk=/[\x00-\x08\x0e-\x1f\x7f-\x9f]/g,mh=new RegExp("(?![\\u200c\\u200d])\\p{Cf}","gu");function AM(e){return e.replace(mh,"")}const hk=/[\t\n\r\v\f ]+/,mk=/\r\n|\r|\n/,gk=/^bcv_\S+$/,_k=200;function Lo(e){return typeof e!="string"?null:e.replace(fk,"").replace(pk,"").replace(mh,"").split(hk).filter(Boolean).join(" ").slice(0,_k)||null}function Zn(e){const t=Lo(e);return t&&!uk.test(t)?t:null}const bk=/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d{1,9}[.)]\s+)+/u,vk=/!?\[([^\]]*)\]\([^)]*\)/gu,yk=/\*\*|__|~~|`+/gu,wk=/(?<![\p{L}\p{N}_*])[*_](?=[^\s*_])|(?<=[^\s*_])[*_](?![\p{L}\p{N}_*])/gu,kk=/^[-=*_~`#> ]*$/;function Sk(e){return e.replace(bk,"").replace(vk,"$1").replace(yk,"").replace(wk,"")}function ea(e){if(typeof e!="string")return null;for(const t of e.split(mk)){const n=Lo(Sk(t));if(n&&!kk.test(n))return n}return null}const gn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function gh(e){if(typeof e!="string")return null;try{return JSON.parse(e)}catch{}const t=e.indexOf(`
19
+ `,J0=" — cancel with wake(",Q0=120,fh=/(?:\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,X0=new RegExp("\\p{Cf}","gu"),q0=4096;function Fr(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(fh,"").replace(X0,"").split(dh).filter(Boolean).join(" ").slice(0,Q0)}const wM={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function ph(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(Z0,"");if(t){const n=t.split(Y0).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function hh(e){const{name:t,quoted:n}=ph(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function ek(e){const{name:t,quoted:n}=ph(e),r=[];return e.pid&&r.push(`pid ${e.pid}`),e.modelLabel&&r.push(e.modelLabel),t?[n?`"${t}"`:t,...r].join(" · "):r.length>0?r.join(" · "):"another session"}function kM(e,t){return t.trim()?!0:ek(e)!==hh(e)}function tk(e){for(const t of e.slice(0,q0).split(`
20
+ `)){const n=Fr(t);if(n)return n}return""}function SM(e,t){const n=hh(e),r=tk(t);return r?`${n} · ${r}`:n}function ea(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const nk=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,rk=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,ok=/^<peer-session-message[^>]*>/,sk=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function mh(e){const t=String(e.text??e.detail??""),n=nk.exec(t.trim()),r={};if(n)for(const d of n[1].matchAll(sk))r[d[1]]=d[2]??d[3]??d[4]??"";const o=n?n[2]:"",a=(String(e.body??"").trim()||o||(n?"":t.trim().replace(ok,""))).replace(rk,"").trim(),c=e.sender??{},l=(d,u)=>Fr(d)||Fr(u);return{body:a,sender:{pid:l(c.pid,r.from_pid),conversationName:l(c.conversation_name,r.conversation),cwd:l(c.cwd,void 0),sessionId:l(c.session_id,void 0),modelLabel:l(c.model_label,r.model)}}}function ik(e){return!!e.wake_catchup}function ak(e){return e.hidden===!0}function EM(e){let t=e.split(uh)[0]??"";t=t.split(dh).filter(Boolean).join(" "),t=t.split(J0)[0];const n="(alarm) ";for(;t.startsWith(n);)t=t.slice(n.length);const r="Scheduled wake ";return t.startsWith(r)&&(t=t.slice(r.length)),t.trim()}function AM(e){const t=e.indexOf(uh);return t===-1?"":e.slice(t+2).trim()}const gs=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},qr=e=>typeof e=="string"?Fr(e):"";function ck(e){const t=gs(e.bridge_receipt),n=t.v===1,r=gs(n?t.sender:e.sender),o=n?gs(t.conversation):{},s=n?t.attachment_count:void 0;return{sender:{name:qr(r.name),...r.kind==="human"||r.kind==="agent"?{kind:r.kind}:{},...qr(r.organization)?{organization:qr(r.organization)}:{}},conversation:{...o.kind==="dm"||o.kind==="group"||o.kind==="channel"?{kind:o.kind}:{},...qr(o.label)?{label:qr(o.label)}:{}},...typeof s=="number"&&Number.isSafeInteger(s)&&s>=0?{attachmentCount:s}:{}}}const lk=new Set(["channel_post","channel_create","channel_history","channel_thread","react","shared_history"]),dk=new Set(["channel_post","dm","send","reply"]),uk=new Set(["take_up","ack","send","reply","channels","channel_create","channel_post","channel_history","react","channel_thread","directory","dm","shared_conversations","shared_history"]),fk=/^(?:bcv|bcmsg|acc|ep)_/i,pk=/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]|\x9b[0-?]*[ -/]*[@-~]/g,hk=/[\x00-\x08\x0e-\x1f\x7f-\x9f]/g,gh=new RegExp("(?![\\u200c\\u200d])\\p{Cf}","gu");function IM(e){return e.replace(gh,"")}const mk=/[\t\n\r\v\f ]+/,gk=/\r\n|\r|\n/,_k=/^bcv_\S+$/,bk=200;function Lo(e){return typeof e!="string"?null:e.replace(pk,"").replace(hk,"").replace(gh,"").split(mk).filter(Boolean).join(" ").slice(0,bk)||null}function Zn(e){const t=Lo(e);return t&&!fk.test(t)?t:null}const vk=/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d{1,9}[.)]\s+)+/u,yk=/!?\[([^\]]*)\]\([^)]*\)/gu,wk=/\*\*|__|~~|`+/gu,kk=/(?<![\p{L}\p{N}_*])[*_](?=[^\s*_])|(?<=[^\s*_])[*_](?![\p{L}\p{N}_*])/gu,Sk=/^[-=*_~`#> ]*$/;function Ek(e){return e.replace(vk,"").replace(yk,"$1").replace(wk,"").replace(kk,"")}function ta(e){if(typeof e!="string")return null;for(const t of e.split(gk)){const n=Lo(Ek(t));if(n&&!Sk.test(n))return n}return null}const gn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function _h(e){if(typeof e!="string")return null;try{return JSON.parse(e)}catch{}const t=e.indexOf(`
21
21
 
22
- `);if(t<0)return null;try{return JSON.parse(e.slice(t+2))}catch{return null}}function Ek(e,t,n){if(e==="react")return t.remove===!0?"react-remove":"react";if(e==="ack"){const r=t.state||n?.state;if(r==="working")return"ack-working";if(r==="done")return"ack-done"}return e}function _h(e){return ck.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function bh(e,t,n){const r=Zn(n?.conversation_label);if(r)return r;if(e==="dm"&&typeof n?.content=="string"){const a="direct message to ";if(n.content.startsWith(a)){const c=n.content.slice(a.length),l=c.indexOf(" in bcv_"),d=l>0?Zn(c.slice(0,l)):null;if(d)return d}}if(e==="channel_create"){const a=gn(gh(n?.content)),c=Zn(a?.name);if(c)return c}if(e==="channel_create"){const a=Zn(t.name);if(a)return a}const o=_h(e);if(o!=="person"&&o!=="dm")return null;const s=gn(t.to);return Zn(s?.name)}function Ak(e,t,n){const r=_h(e);return r==="none"||r==="message"||r==="directory"?{kind:r,label:null}:{kind:r,label:bh(e,t,n)}}function Ik(e){if(Array.isArray(e))return e.length;const t=gn(e);if(!t)return null;for(const n of["conversations","items","data"])if(Array.isArray(t[n]))return t[n].length;return null}function Rk(e,t){if(!t)return null;const n=gh(t.content),r=gn(n);if(e==="channel_history"||e==="shared_history")return Array.isArray(r?.messages)?r.messages.length:null;if(e==="channel_thread"){if(!r)return null;const o=gn(r.root)?1:0,s=Array.isArray(r.replies)?r.replies.length:null;return s===null&&o===0?null:o+(s??0)}return e==="directory"?typeof r?.count=="number"&&Number.isInteger(r.count)?r.count:Array.isArray(t.members)?t.members.length:null:e==="channels"||e==="shared_conversations"?Ik(n):null}function xk(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=Lo(t.code);if(t.ok===!0){if(t.destination_type==="peer_inbox")return{outcome:"inbox_only",code:null};const r=t.recipient_state;return e==="dm"&&typeof r=="string"&&r!==""&&r!=="active"?{outcome:"awaiting_acceptance",code:null}:{outcome:null,code:null}}return t.ok===!1?n==="send_unconfirmed"||n==="post_failed"?{outcome:"unconfirmed",code:n}:n?.endsWith("_failed")?{outcome:"failed",code:n}:{outcome:"refused",code:n}:{outcome:null,code:n}}function yi(e,t){const n=e??{},r=Lo(n.op)??"",o=gn(t),s=dk.has(r),a=lk.has(r)||r==="take_up"?ea(n.body)??ea(n.text)??ea(o?.text):null;return{op:r,action:Ek(r,n,o),target:s?Ak(r,n,o):{kind:"none",label:null},preview:a,count:s&&o?.ok===!0?Rk(r,o):null,emoji:r==="react"?Lo(n.emoji):null,...s?xk(r,o):{outcome:null,code:null}}}function vh(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&gk.test(n.trim()))return n.trim();return null}const Tk=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"]),yh=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return Tk.has(t)?t:"unknown"},Ck={channel_post:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function Za(e){return Ck[yh(e)]()}function wh(e,t=null){const{kind:n}=e.target,r=e.target.label??Zn(t);return r?n==="channel"&&!r.startsWith("#")?`#${r}`:r:e.op==="shared_history"?"":n==="channel"?_("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?_("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?_("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?_("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function Ya(e,t,n,r){const o=vh(t,r),s=!e.target.label&&o&&n?n(o):null,a=wh(e,s),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?a:_("ui.chat.canonical.tool_row.bridge.summary.messages",{target:a,count:e.count}).trim();switch(yh(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?_("ui.chat.canonical.tool_row.bridge.target.thread",{target:a}):a;return c(d,e.preview)}case"dm":case"send":case"reply":case"take_up":return c(a,e.preview);case"channels":case"shared_conversations":return e.count===null?"":_("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":_("ui.chat.canonical.tool_row.bridge.summary.members",{count:e.count});case"channel_history":case"channel_thread":case"shared_history":return l();case"react":case"react_remove":return c(a,e.emoji);case"channel_create":case"ack_working":case"ack_done":return a;default:return e.op}}function Ok(e){return e.outcome==="refused"?e.code?_("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):_("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?_("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):_("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const Pk=["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 kh(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const r=gn(t);if(!r)return n??null;const{_images:o,...s}=r;return n&&jk(n,s)?n:s}function Mk(e){const t=gn(e);if(!t)return null;const n=t.destination_type==="conversation_dm"?"dm":t.state==="created"?"channel_create":"channel_post";return bh(n,{},t)}function Sh(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:gn(t)?Mk(t):n??null}function jk(e,t){const n=Object.keys(e);return n.length!==Object.keys(t).length?!1:n.every(r=>e[r]===t[r]||typeof e[r]=="object"&&JSON.stringify(e[r])===JSON.stringify(t[r]))}const $k={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"},Nk=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function mu(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function IM(e,t){const n=e.args??{},r=e.details??null,o=yi(n,r),s=o.target.label===null&&e.label&&o.target.kind!=="none"&&o.target.kind!=="message"&&o.target.kind!=="directory"?{...o,target:{...o.target,label:e.label}}:o,a=vh(n,r),c=!s.target.label&&a&&t?t(a):null,l=wh(s,c),d=s.outcome==="refused"||s.outcome==="failed",u=e.failed||d?Za(s.action).failed:null,f=u??Za(s.action).settled,h=Ya({...s,preview:null,emoji:null},n,t,r),m=s.target.label??Zn(c)??_("ui.chat.canonical.tool_row.bridge.fallback.teammate"),y=s.op==="dm"?_("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:m}):h?_("ui.chat.canonical.tool_row.bridge.detail.headline.target",{verb:f,target:h}):f,b=[n.body,n.text,r?.text].find(S=>typeof S=="string"&&S.trim()!==""),v=typeof r?.seq=="number"?r.seq:null,p=mu(r?.error),A=(s.target.kind==="channel"||s.target.kind==="dm")&&l?l:_("ui.chat.canonical.tool_row.bridge.fallback.conversation"),k=p?p.replace(Nk,(S,x)=>x.toLowerCase()==="bcv"?A:"…"):null,C=s.outcome==="refused"||s.outcome==="failed"?k&&s.code?_(s.outcome==="refused"?"ui.chat.canonical.tool_row.bridge.detail.outcome.refused":"ui.chat.canonical.tool_row.bridge.detail.outcome.failed",{code:s.code,error:k}):k:s.outcome==="unconfirmed"?k:r?.ok===!0&&v!==null?_("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:v}):null,L=[],O=new Set,I=(S,x)=>{const F=mu(x);F===null||O.has(S)||(O.add(S),L.push({key:S,value:F}))};for(const S of Pk)I(S,r?.[S]);p&&p!==k&&I("error",p);for(const[S,x]of Object.entries($k))I(x,n[S]);const g=typeof r?.content=="string"&&r.content||e.output||null,w=g&&g.trim()===p?null:g;return{tokens:s,summary:Ya(s,n,t,r),failedVerb:u,failureWord:Ok(s),headline:y,body:b??null,outcome:C,internals:L,raw:w}}const Eh="profile_save",Dk="profile_revert",nl=["agent","team"],Lk=["create","update","revert"],Fk={agent:["label","description","tags","categories","model","instructions"],team:["label","description","manager","members","aliases","instructions","project"]},Ja=i.string().max(1e5),In=e=>i.string().max(e),Tn=i.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/),Fo=i.string().regex(/^sha256:[0-9a-f]{64}$/),gu=i.union([i.string().max(1e5),i.array(i.string().max(512)).max(128),i.array(i.record(i.string(),i.unknown())).max(64),i.null()]);i.object({id:Tn,name:i.string().min(1).max(128),label:In(256),description:In(16e3),tags:i.array(In(512)).max(128),categories:i.array(In(128)).max(32),model:In(512).nullable(),instructions:Ja}).strict();i.object({id:Tn,name:i.string().min(1).max(128),label:In(256),description:In(16e3),manager:i.string().min(1).max(128),members:i.array(i.object({role:i.string().min(1).max(128),count:i.number().int().min(1).max(16).optional(),kind:i.enum(["agent","team"]).optional(),tier:i.enum(["lo","med","hi"]).nullable().optional(),effort:i.string().max(64).nullable().optional(),saver:i.boolean().nullable().optional()}).strict()).max(64),aliases:i.array(In(128)).max(32),instructions:Ja,project:Ja}).strict();const Ah=i.object({version:i.literal(1),operation:i.literal(Eh),approval_id:i.string().min(1).max(64),profile_kind:i.enum(nl),scope:i.literal("global"),profile_operation:i.enum(Lk),target_id:Tn,profile_name:i.string().min(1).max(128),session_id:Tn,tool_call_id:Tn,receipt_id:Tn,changed_fields:i.array(i.string().max(64)).max(32),before:i.record(i.string(),gu).nullable(),after:i.record(i.string(),gu),base_commitment:Fo,after_commitment:Fo,expires_at:i.number().finite(),signing_principal:i.string().min(1).max(160)}).strict(),Uk=i.object({action:i.string().min(1).max(64),operation:i.literal(Eh),request_digest:Fo,assurance:i.string().max(64).optional(),unproven_human:i.boolean().optional(),disclosure:Ah.nullable().optional(),disclosure_digest:Fo.optional(),signable_here:i.boolean(),refusal:i.string().max(64).optional(),refusal_message:i.string().max(2e3).optional(),apply_outcome:i.object({code:i.string().max(64),retryable:i.boolean(),reason:i.string().max(2e3),remedy:i.string().max(2e3)}).strict().nullable().optional(),upgrade:i.object({available:i.boolean(),helper:i.string().max(64)}).strict().optional()}).strict(),Bk=["queued","applied"],Hk=i.object({status:i.enum(Bk),approval_id:i.string().min(1).max(64).optional(),request_digest:Fo.optional(),expires_at:i.number().finite().optional(),receipt_id:Tn.optional(),profile_kind:i.enum(nl),profile_name:i.string().min(1).max(128),scope:i.literal("global"),fields:i.array(i.string().max(64)).max(32).optional(),diff:i.array(i.string().max(2e3)).max(64).optional(),profile_action:i.unknown().optional(),revert:i.unknown().optional()}).strict(),Wk=i.object({kind:i.string().max(64).optional(),name:i.string().min(1).max(128),scope:i.literal("global"),fields:i.array(i.string().max(64)).max(32).optional(),diff:i.array(i.string().max(2e3)).max(64).optional(),backup_id:i.string().max(160).optional(),revision:i.string().max(200).optional(),authorized_by:i.string().max(160).optional(),class:i.string().max(64).optional(),profile_action:i.unknown().optional(),revert:i.unknown().optional()}).strict();function Gk(e){const t=Wk.safeParse(e);return t.success?t.data:null}const Ih=i.object({schema:i.literal(1),kind:i.literal(Dk),action_id:i.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),label:i.string().min(1).max(64),profile_kind:i.enum(nl),profile_name:i.string().min(1).max(128),receipt_id:Tn}).strict();function zk(e){const t=typeof e.role=="string"?e.role:"";if(!t)return"";const n=typeof e.count=="number"?e.count:1,r=e.kind==="team"?"team":"agent",o=typeof e.tier=="string"?e.tier:"",s=typeof e.effort=="string"?e.effort:"",a=e.saver===!0?"saver":e.saver===!1?"saver off":"",c=[r==="team"?"team":"",o,s,a].filter(d=>d!==""),l=n>1?` x${n}`:"";return c.length?`${t}${l} (${c.join(", ")})`:`${t}${l}`}function Kk(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:typeof t=="object"&&t!==null?zk(t):"").filter(t=>t!=="").join(", "):""}function _u(e,t){return e===null?{presence:"absent",text:""}:Object.prototype.hasOwnProperty.call(e,t)?e[t]===null?{presence:"unset",text:""}:{presence:"set",text:Kk(e[t])}:{presence:"absent",text:""}}function RM(e){const t=Fk[e.profile_kind],n=[];for(const r of e.changed_fields){if(!t.includes(r))continue;const o=_u(e.before,r),s=_u(e.after,r);if(o.presence==="set"&&s.presence==="set"){if(o.text===s.text)continue}else if(o.presence===s.presence&&o.presence==="absent")continue;n.push({field:r,before:o,after:s})}return n}function xM(e){const t=Ih.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 Vk(e){const t=Ah.safeParse(e);return t.success?t.data:null}function TM(e){const t=Uk.safeParse(e);return t.success?t.data:null}function Cr(e){const t=Hk.safeParse(e);return t.success?t.data:null}function Zk(e){const t=Ih.safeParse(e);return t.success?t.data:null}const Yk=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),Jk=new Set(["true","yes","y","t","on","1"]),Qk={hub:{steps:e=>{const t=Or(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=Or(e);return t!==null&&t>0?`· ${Oh(t/1e3)}`:""}}};function Or(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 bu="mcp__",Xk=/^\/(?:Users|home)\/[^/]+\//,qk=/\s+/;function eS(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(Xk,"~/")}function Et(e){return typeof e=="string"?eS(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function tS(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function nS(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(qk).filter(Boolean).join(" ")||"?"}function rS(e){return[tS(e),Et(nS(e))||"?",Et(e.message)].filter(Boolean).join(" · ")}const oS=new Set(["delivered","mailbox","unconfirmed","failed"]);function sS(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:r}=yi({op:n},t);return r==="inbox_only"?"inbox_only":r==="awaiting_acceptance"?"awaiting_acceptance":r==="unconfirmed"?"unconfirmed":null}function iS(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return sS(e);const n=e.delivery;if(!n||typeof n!="object")return null;const r=n.state;return typeof r=="string"&&oS.has(r)?r:null}function Rh(e,t,n){return!e||typeof e!="object"?t??null:iS(e,n)}function aS(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 cS=["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 lS(e,t){if(e===t)return!0;if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++){const r=e[n],o=t[n];if(!(!!r&&typeof r=="object")||!(!!o&&typeof o=="object")){if(r!==o)return!1;continue}const c=r,l=o;if(c.message!==l.message||c.timestamp!==l.timestamp)return!1}return!0}const dS=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function uS(e,t){return e===t?!0:!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return!n||typeof n!="object"||!o||typeof o!="object"?n===o:dS.every(s=>s==="cost"?n.cost?.basis===o.cost?.basis:n[s]===o[s])})}function fS(e,t){for(const n of cS){const r=e[n],o=t[n];if(n==="artifacts"){if(!uS(r,o))return!1;continue}if(n==="cost"){const s=a=>a&&typeof a=="object"?a.basis:void 0;if(s(r)!==s(o))return!1;continue}if(n==="log_lines"){if(!lS(r,o))return!1;continue}if(r!==o)return!1}return!0}function xh(e,t){const n=aS(e);return n?t&&fS(n,t)?t:n:t??null}const pS={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},hS={mailbox:"In their mailbox. The wake got no answer, so they will read it on their next turn.",unconfirmed:"No wake answer and not yet in their transcript — it may still arrive. Check before resending."},mS={mailbox:"Delivered to their mailbox. The wake got no answer, so they will read the message on their next turn. Do not send it again.",unconfirmed:"Not confirmed: there was no answer and the message is not in their transcript. It may still arrive, so check before resending.",failed:"Nothing was delivered. Fix the cause named below, or retry the send."},gS={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function Th(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const Xo=e=>e.trim().toLowerCase()==="bridge";function CM(e,t=""){return e?e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&Xo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):pS[e]??null:null}function OM(e,t){return e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&Xo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function PM(e,t=""){if(e)return e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&Xo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):hS[e]}function MM(e,t=""){return e?e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&Xo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):gS[e]??null:null}function jM(e,t=""){return e?e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&Xo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):mS[e]??null:null}function $M(e){return Th(e)?"partial":null}function NM(e){return e==="failed"?"Attempted":null}function DM(e,t){return e!==!0?!1:!Th(t)}function vu(e){const t=Or(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:Et(e.session)||Et(e.target)||"?"}function _S(e){const t=Et(e.query);if(t){const a=Or(e.steps);return a!==null&&Number.isInteger(a)&&a>=0?`search ${t} · ${a} around`:`search ${t}`}const n=Or(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=Or(e.head);if(r!==null&&Number.isInteger(r)&&r>=0)return`first ${r}`;if(e.digest===!0)return"digest";const o=Et(e.before_id);if(o)return`before ${o}`;const s=Et(e.around_id);return s?`around ${s}`:""}function bS(e){const t=kS(e);if(t==="spawn"){const n=Et(e.visibility)||"workstream",r=Et(e.name)||Et(e.prompt);return[n,r].filter(Boolean).join(" · ")}if(t==="stop"||t==="resume"||t==="info")return vu(e);if(t==="peek")return[vu(e),_S(e)].filter(Boolean).join(" · ");if(t==="list"){const n=[];e.include_stored===!0&&n.push("stored");const r=Et(e.query);return r&&n.push(r),n.join(" · ")}return null}function LM(e,t,n,r){const o=e.trim();if(o.toLowerCase()==="bridge")return Ya(yi(t,n),t,r,n);if(!t)return o;if(o==="send")return rS(t)||o;if(o.toLowerCase()==="sessions"){const c=bS(t);if(c!==null)return c||o}const s=SS(o)?Object.entries(t).filter(([c])=>!Ph.has(c)):Object.entries(t);let a=s.filter(([c])=>Yk.has(c)).map(([,c])=>Et(c)).filter(Boolean);if(a.length===0){const c=Qk[o.toLowerCase()];a=s.map(([l,d])=>c?.[l]?.(d)||Et(d)).filter(Boolean)}return a.slice(0,2).join(" ")||o}function Ch(e){const t=e.trim();if(!t.toLowerCase().startsWith(bu))return t;const n=t.slice(bu.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function vS(e,t){return e===t||e===Ch(t)}const yS=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,wS="… ";function FM(e,t=!1){if(!e||t)return null;for(const n of e.split(`
23
- `)){const r=n.trim();if(r&&!yS.test(r))return`${wS}${r.slice(0,160)}`}return null}function Oh(e){const t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;if(t<3600){const o=Math.floor(t/60),s=t%60;return s===0?`${o}m`:`${o}m${s}s`}if(t<86400){const o=Math.floor(t/3600),s=Math.floor(t%3600/60);return s===0?`${o}h`:`${o}h${s}m`}const n=Math.floor(t/86400);if(n>99)return"100d+";const r=Math.floor(t%86400/3600);return r===0?`${n}d`:`${n}d${r}h`}function UM(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`:Oh(t)}function yu(e){const t=e*10,n=Math.floor(t),r=t-n;return((r>.5?n+1:r<.5||n%2===0?n:n+1)/10).toFixed(1)}function BM(e){const t={minimumFractionDigits:1,maximumFractionDigits:1};return e<1024?mo(e,"B",{maximumFractionDigits:0}):e<1024*1024?mo(Number(yu(e/1024)),"KB",t):mo(Number(yu(e/(1024*1024))),"MB",t)}function Qa(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const wu={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 HM(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(wu,t)?wu[t]:"plain"}function kS(e){if(!e)return"";for(const t of Ph){const n=e[t];if(typeof n=="string"&&n.trim()){const r=n.trim().toLowerCase(),o=e.remove,s=o===!0||o===1||typeof o=="string"&&Jk.has(o.toLowerCase());return r==="milestone"&&s?"milestone-remove":t==="op"&&(r==="react"||r==="ack")?yi(e).action:r}}return""}const Ph=new Set(["op","action","method"]),SS=e=>Object.prototype.hasOwnProperty.call(Mh,e.trim().toLowerCase()),ku=({settled:e,running:t})=>({settled:_(e),running:_(t)}),ES={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"}},Mh={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 AS(e,t){const n=e.trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(n==="bridge"){const{settled:a,running:c}=Za(r);return{settled:a,running:c,named:!0}}const o=r?Mh[n]?.[r]:void 0;if(o)return{...ku(o),named:!0};const s=ES[n];return s?{...ku(s),named:!0}:{settled:_("ui.chat.canonical.tool_row.generic_verb.settled"),running:_("ui.chat.canonical.tool_row.generic_verb.running"),named:!1}}function WM(e,t,n,r,o="",s=null){const a=AS(e,o),c=vS(t,e)?n??"":t;return{verb:r?a.running:s??a.settled,object:a.named?c:[Ch(e),c].filter(Boolean).join(" ")}}const IS=new Set(["write","edit"]);function RS(e){return IS.has(e.trim().toLowerCase())}function GM(e){return RS(e.toolName)&&e.diff!==null&&!e.isError}function jh(e){if(!e||typeof e!="object")return null;const t=e.diff;if(typeof t=="string")return t?t.split(`
24
- `):null;if(!Array.isArray(t))return null;const n=t.filter(r=>typeof r=="string");return n.length?n:null}function xS(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 $h(e,t){return e===null||xS(e,t)?t:e}function Nh(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:Qa(n.added),removed:Qa(n.removed)}}function Dh(e,t){return!e||typeof e!="object"?t:Qa(e.diff_truncated_rows)}function TS(e){return e.length>=2&&Pr(e[0])==="---"&&Pr(e[1])==="+++"?e.slice(2):e.slice()}const CS=/\s+$/;function Pr(e){return e.replace(CS,"")}function OS(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const Su=40,PS="[output withheld: credential redaction requires a complete bounded diff]";function MS(e){return e.length===0||Pr(e[0])!==PS?!1:e.slice(1).every(t=>Pr(t)===""||Pr(t)==="…")}function zM(e,t={}){const n=TS(e);if(MS(n))return{lines:[],hidden:0,expandable:!1,withheld:!0};const r=n.length>Su,o=t.expanded?n:n.slice(0,Su);return{lines:o.map(s=>{const a=Pr(s);return{text:a,marker:a.slice(0,1),kind:OS(a)}}),hidden:n.length-o.length,expandable:r,withheld:!1}}function KM(e){return _("ui.chat.canonical.tool_row.diff.more",{count:e})}function VM(){return _("ui.chat.canonical.tool_row.diff.show_less")}function ZM(e){return _("ui.chat.canonical.tool_row.diff.truncated",{count:e})}function YM(){return _("ui.chat.canonical.tool_row.diff.withheld")}const jS=new Set(["agent","team"]),$S=1048576;function rl(e,t){if(!jS.has(e)||!t||typeof t!="object"||Array.isArray(t))return null;try{const n=JSON.stringify(t);if(new TextEncoder().encode(n).byteLength>$S)return null}catch{return null}return!Gk(t)&&!Cr(t)&&!Vk(t)?null:t}function Lh(e,t,n){return rl(e,t)??xh(t,n)}const NS=`Continue working toward this goal:
22
+ `);if(t<0)return null;try{return JSON.parse(e.slice(t+2))}catch{return null}}function Ak(e,t,n){if(e==="react")return t.remove===!0?"react-remove":"react";if(e==="ack"){const r=t.state||n?.state;if(r==="working")return"ack-working";if(r==="done")return"ack-done"}return e}function bh(e){return lk.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function vh(e,t,n){const r=Zn(n?.conversation_label);if(r)return r;if(e==="dm"&&typeof n?.content=="string"){const a="direct message to ";if(n.content.startsWith(a)){const c=n.content.slice(a.length),l=c.indexOf(" in bcv_"),d=l>0?Zn(c.slice(0,l)):null;if(d)return d}}if(e==="channel_create"){const a=gn(_h(n?.content)),c=Zn(a?.name);if(c)return c}if(e==="channel_create"){const a=Zn(t.name);if(a)return a}const o=bh(e);if(o!=="person"&&o!=="dm")return null;const s=gn(t.to);return Zn(s?.name)}function Ik(e,t,n){const r=bh(e);return r==="none"||r==="message"||r==="directory"?{kind:r,label:null}:{kind:r,label:vh(e,t,n)}}function Rk(e){if(Array.isArray(e))return e.length;const t=gn(e);if(!t)return null;for(const n of["conversations","items","data"])if(Array.isArray(t[n]))return t[n].length;return null}function xk(e,t){if(!t)return null;const n=_h(t.content),r=gn(n);if(e==="channel_history"||e==="shared_history")return Array.isArray(r?.messages)?r.messages.length:null;if(e==="channel_thread"){if(!r)return null;const o=gn(r.root)?1:0,s=Array.isArray(r.replies)?r.replies.length:null;return s===null&&o===0?null:o+(s??0)}return e==="directory"?typeof r?.count=="number"&&Number.isInteger(r.count)?r.count:Array.isArray(t.members)?t.members.length:null:e==="channels"||e==="shared_conversations"?Rk(n):null}function Tk(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=Lo(t.code);if(t.ok===!0){if(t.destination_type==="peer_inbox")return{outcome:"inbox_only",code:null};const r=t.recipient_state;return e==="dm"&&typeof r=="string"&&r!==""&&r!=="active"?{outcome:"awaiting_acceptance",code:null}:{outcome:null,code:null}}return t.ok===!1?n==="send_unconfirmed"||n==="post_failed"?{outcome:"unconfirmed",code:n}:n?.endsWith("_failed")?{outcome:"failed",code:n}:{outcome:"refused",code:n}:{outcome:null,code:n}}function yi(e,t){const n=e??{},r=Lo(n.op)??"",o=gn(t),s=uk.has(r),a=dk.has(r)||r==="take_up"?ta(n.body)??ta(n.text)??ta(o?.text):null;return{op:r,action:Ak(r,n,o),target:s?Ik(r,n,o):{kind:"none",label:null},preview:a,count:s&&o?.ok===!0?xk(r,o):null,emoji:r==="react"?Lo(n.emoji):null,...s?Tk(r,o):{outcome:null,code:null}}}function yh(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&_k.test(n.trim()))return n.trim();return null}const Ck=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"]),wh=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return Ck.has(t)?t:"unknown"},Ok={channel_post:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:_("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:_("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:_("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function Ya(e){return Ok[wh(e)]()}function kh(e,t=null){const{kind:n}=e.target,r=e.target.label??Zn(t);return r?n==="channel"&&!r.startsWith("#")?`#${r}`:r:e.op==="shared_history"?"":n==="channel"?_("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?_("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?_("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?_("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function Ja(e,t,n,r){const o=yh(t,r),s=!e.target.label&&o&&n?n(o):null,a=kh(e,s),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?a:_("ui.chat.canonical.tool_row.bridge.summary.messages",{target:a,count:e.count}).trim();switch(wh(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?_("ui.chat.canonical.tool_row.bridge.target.thread",{target:a}):a;return c(d,e.preview)}case"dm":case"send":case"reply":case"take_up":return c(a,e.preview);case"channels":case"shared_conversations":return e.count===null?"":_("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":_("ui.chat.canonical.tool_row.bridge.summary.members",{count:e.count});case"channel_history":case"channel_thread":case"shared_history":return l();case"react":case"react_remove":return c(a,e.emoji);case"channel_create":case"ack_working":case"ack_done":return a;default:return e.op}}function Pk(e){return e.outcome==="refused"?e.code?_("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):_("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?_("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):_("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const Mk=["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 Sh(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const r=gn(t);if(!r)return n??null;const{_images:o,...s}=r;return n&&$k(n,s)?n:s}function jk(e){const t=gn(e);if(!t)return null;const n=t.destination_type==="conversation_dm"?"dm":t.state==="created"?"channel_create":"channel_post";return vh(n,{},t)}function Eh(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:gn(t)?jk(t):n??null}function $k(e,t){const n=Object.keys(e);return n.length!==Object.keys(t).length?!1:n.every(r=>e[r]===t[r]||typeof e[r]=="object"&&JSON.stringify(e[r])===JSON.stringify(t[r]))}const Nk={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"},Dk=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function gu(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function RM(e,t){const n=e.args??{},r=e.details??null,o=yi(n,r),s=o.target.label===null&&e.label&&o.target.kind!=="none"&&o.target.kind!=="message"&&o.target.kind!=="directory"?{...o,target:{...o.target,label:e.label}}:o,a=yh(n,r),c=!s.target.label&&a&&t?t(a):null,l=kh(s,c),d=s.outcome==="refused"||s.outcome==="failed",u=e.failed||d?Ya(s.action).failed:null,f=u??Ya(s.action).settled,h=Ja({...s,preview:null,emoji:null},n,t,r),m=s.target.label??Zn(c)??_("ui.chat.canonical.tool_row.bridge.fallback.teammate"),y=s.op==="dm"?_("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:m}):h?_("ui.chat.canonical.tool_row.bridge.detail.headline.target",{verb:f,target:h}):f,b=[n.body,n.text,r?.text].find(S=>typeof S=="string"&&S.trim()!==""),v=typeof r?.seq=="number"?r.seq:null,p=gu(r?.error),A=(s.target.kind==="channel"||s.target.kind==="dm")&&l?l:_("ui.chat.canonical.tool_row.bridge.fallback.conversation"),k=p?p.replace(Dk,(S,x)=>x.toLowerCase()==="bcv"?A:"…"):null,T=s.outcome==="refused"||s.outcome==="failed"?k&&s.code?_(s.outcome==="refused"?"ui.chat.canonical.tool_row.bridge.detail.outcome.refused":"ui.chat.canonical.tool_row.bridge.detail.outcome.failed",{code:s.code,error:k}):k:s.outcome==="unconfirmed"?k:r?.ok===!0&&v!==null?_("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:v}):null,F=[],C=new Set,I=(S,x)=>{const N=gu(x);N===null||C.has(S)||(C.add(S),F.push({key:S,value:N}))};for(const S of Mk)I(S,r?.[S]);p&&p!==k&&I("error",p);for(const[S,x]of Object.entries(Nk))I(x,n[S]);const g=typeof r?.content=="string"&&r.content||e.output||null,w=g&&g.trim()===p?null:g;return{tokens:s,summary:Ja(s,n,t,r),failedVerb:u,failureWord:Pk(s),headline:y,body:b??null,outcome:T,internals:F,raw:w}}const Ah="profile_save",Lk="profile_revert",rl=["agent","team"],Fk=["create","update","revert"],Uk={agent:["label","description","tags","categories","model","instructions"],team:["label","description","manager","members","aliases","instructions","project"]},Qa=i.string().max(1e5),In=e=>i.string().max(e),Tn=i.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/),Fo=i.string().regex(/^sha256:[0-9a-f]{64}$/),_u=i.union([i.string().max(1e5),i.array(i.string().max(512)).max(128),i.array(i.record(i.string(),i.unknown())).max(64),i.null()]);i.object({id:Tn,name:i.string().min(1).max(128),label:In(256),description:In(16e3),tags:i.array(In(512)).max(128),categories:i.array(In(128)).max(32),model:In(512).nullable(),instructions:Qa}).strict();i.object({id:Tn,name:i.string().min(1).max(128),label:In(256),description:In(16e3),manager:i.string().min(1).max(128),members:i.array(i.object({role:i.string().min(1).max(128),count:i.number().int().min(1).max(16).optional(),kind:i.enum(["agent","team"]).optional(),tier:i.enum(["lo","med","hi"]).nullable().optional(),effort:i.string().max(64).nullable().optional(),saver:i.boolean().nullable().optional()}).strict()).max(64),aliases:i.array(In(128)).max(32),instructions:Qa,project:Qa}).strict();const Ih=i.object({version:i.literal(1),operation:i.literal(Ah),approval_id:i.string().min(1).max(64),profile_kind:i.enum(rl),scope:i.literal("global"),profile_operation:i.enum(Fk),target_id:Tn,profile_name:i.string().min(1).max(128),session_id:Tn,tool_call_id:Tn,receipt_id:Tn,changed_fields:i.array(i.string().max(64)).max(32),before:i.record(i.string(),_u).nullable(),after:i.record(i.string(),_u),base_commitment:Fo,after_commitment:Fo,expires_at:i.number().finite(),signing_principal:i.string().min(1).max(160)}).strict(),Bk=i.object({action:i.string().min(1).max(64),operation:i.literal(Ah),request_digest:Fo,assurance:i.string().max(64).optional(),unproven_human:i.boolean().optional(),disclosure:Ih.nullable().optional(),disclosure_digest:Fo.optional(),signable_here:i.boolean(),refusal:i.string().max(64).optional(),refusal_message:i.string().max(2e3).optional(),apply_outcome:i.object({code:i.string().max(64),retryable:i.boolean(),reason:i.string().max(2e3),remedy:i.string().max(2e3)}).strict().nullable().optional(),upgrade:i.object({available:i.boolean(),helper:i.string().max(64)}).strict().optional()}).strict(),Hk=["queued","applied"],Wk=i.object({status:i.enum(Hk),approval_id:i.string().min(1).max(64).optional(),request_digest:Fo.optional(),expires_at:i.number().finite().optional(),receipt_id:Tn.optional(),profile_kind:i.enum(rl),profile_name:i.string().min(1).max(128),scope:i.literal("global"),fields:i.array(i.string().max(64)).max(32).optional(),diff:i.array(i.string().max(2e3)).max(64).optional(),profile_action:i.unknown().optional(),revert:i.unknown().optional()}).strict(),Gk=i.object({kind:i.string().max(64).optional(),name:i.string().min(1).max(128),scope:i.literal("global"),fields:i.array(i.string().max(64)).max(32).optional(),diff:i.array(i.string().max(2e3)).max(64).optional(),backup_id:i.string().max(160).optional(),revision:i.string().max(200).optional(),authorized_by:i.string().max(160).optional(),class:i.string().max(64).optional(),profile_action:i.unknown().optional(),revert:i.unknown().optional()}).strict();function zk(e){const t=Gk.safeParse(e);return t.success?t.data:null}const Rh=i.object({schema:i.literal(1),kind:i.literal(Lk),action_id:i.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),label:i.string().min(1).max(64),profile_kind:i.enum(rl),profile_name:i.string().min(1).max(128),receipt_id:Tn}).strict();function Kk(e){const t=typeof e.role=="string"?e.role:"";if(!t)return"";const n=typeof e.count=="number"?e.count:1,r=e.kind==="team"?"team":"agent",o=typeof e.tier=="string"?e.tier:"",s=typeof e.effort=="string"?e.effort:"",a=e.saver===!0?"saver":e.saver===!1?"saver off":"",c=[r==="team"?"team":"",o,s,a].filter(d=>d!==""),l=n>1?` x${n}`:"";return c.length?`${t}${l} (${c.join(", ")})`:`${t}${l}`}function Vk(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:typeof t=="object"&&t!==null?Kk(t):"").filter(t=>t!=="").join(", "):""}function bu(e,t){return e===null?{presence:"absent",text:""}:Object.prototype.hasOwnProperty.call(e,t)?e[t]===null?{presence:"unset",text:""}:{presence:"set",text:Vk(e[t])}:{presence:"absent",text:""}}function xM(e){const t=Uk[e.profile_kind],n=[];for(const r of e.changed_fields){if(!t.includes(r))continue;const o=bu(e.before,r),s=bu(e.after,r);if(o.presence==="set"&&s.presence==="set"){if(o.text===s.text)continue}else if(o.presence===s.presence&&o.presence==="absent")continue;n.push({field:r,before:o,after:s})}return n}function TM(e){const t=Rh.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 Zk(e){const t=Ih.safeParse(e);return t.success?t.data:null}function CM(e){const t=Bk.safeParse(e);return t.success?t.data:null}function Cr(e){const t=Wk.safeParse(e);return t.success?t.data:null}function Yk(e){const t=Rh.safeParse(e);return t.success?t.data:null}const Jk=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),Qk=new Set(["true","yes","y","t","on","1"]),Xk={hub:{steps:e=>{const t=Or(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=Or(e);return t!==null&&t>0?`· ${Ph(t/1e3)}`:""}}};function Or(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 vu="mcp__",qk=/^\/(?:Users|home)\/[^/]+\//,eS=/\s+/;function tS(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(qk,"~/")}function Et(e){return typeof e=="string"?tS(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function nS(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function rS(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(eS).filter(Boolean).join(" ")||"?"}function oS(e){return[nS(e),Et(rS(e))||"?",Et(e.message)].filter(Boolean).join(" · ")}const sS=new Set(["delivered","mailbox","unconfirmed","failed"]);function iS(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:r}=yi({op:n},t);return r==="inbox_only"?"inbox_only":r==="awaiting_acceptance"?"awaiting_acceptance":r==="unconfirmed"?"unconfirmed":null}function aS(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return iS(e);const n=e.delivery;if(!n||typeof n!="object")return null;const r=n.state;return typeof r=="string"&&sS.has(r)?r:null}function xh(e,t,n){return!e||typeof e!="object"?t??null:aS(e,n)}function cS(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 lS=["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 dS(e,t){if(e===t)return!0;if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++){const r=e[n],o=t[n];if(!(!!r&&typeof r=="object")||!(!!o&&typeof o=="object")){if(r!==o)return!1;continue}const c=r,l=o;if(c.message!==l.message||c.timestamp!==l.timestamp)return!1}return!0}const uS=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function fS(e,t){return e===t?!0:!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return!n||typeof n!="object"||!o||typeof o!="object"?n===o:uS.every(s=>s==="cost"?n.cost?.basis===o.cost?.basis:n[s]===o[s])})}function pS(e,t){for(const n of lS){const r=e[n],o=t[n];if(n==="artifacts"){if(!fS(r,o))return!1;continue}if(n==="cost"){const s=a=>a&&typeof a=="object"?a.basis:void 0;if(s(r)!==s(o))return!1;continue}if(n==="log_lines"){if(!dS(r,o))return!1;continue}if(r!==o)return!1}return!0}function Th(e,t){const n=cS(e);return n?t&&pS(n,t)?t:n:t??null}const hS={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},mS={mailbox:"In their mailbox. The wake got no answer, so they will read it on their next turn.",unconfirmed:"No wake answer and not yet in their transcript — it may still arrive. Check before resending."},gS={mailbox:"Delivered to their mailbox. The wake got no answer, so they will read the message on their next turn. Do not send it again.",unconfirmed:"Not confirmed: there was no answer and the message is not in their transcript. It may still arrive, so check before resending.",failed:"Nothing was delivered. Fix the cause named below, or retry the send."},_S={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function Ch(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const Xo=e=>e.trim().toLowerCase()==="bridge";function OM(e,t=""){return e?e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&Xo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):hS[e]??null:null}function PM(e,t){return e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&Xo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function MM(e,t=""){if(e)return e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&Xo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):mS[e]}function jM(e,t=""){return e?e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&Xo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):_S[e]??null:null}function $M(e,t=""){return e?e==="inbox_only"?_("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?_("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&Xo(t)?_("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):gS[e]??null:null}function NM(e){return Ch(e)?"partial":null}function DM(e){return e==="failed"?"Attempted":null}function LM(e,t){return e!==!0?!1:!Ch(t)}function yu(e){const t=Or(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:Et(e.session)||Et(e.target)||"?"}function bS(e){const t=Et(e.query);if(t){const a=Or(e.steps);return a!==null&&Number.isInteger(a)&&a>=0?`search ${t} · ${a} around`:`search ${t}`}const n=Or(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=Or(e.head);if(r!==null&&Number.isInteger(r)&&r>=0)return`first ${r}`;if(e.digest===!0)return"digest";const o=Et(e.before_id);if(o)return`before ${o}`;const s=Et(e.around_id);return s?`around ${s}`:""}function vS(e){const t=SS(e);if(t==="spawn"){const n=Et(e.visibility)||"workstream",r=Et(e.name)||Et(e.prompt);return[n,r].filter(Boolean).join(" · ")}if(t==="stop"||t==="resume"||t==="info")return yu(e);if(t==="peek")return[yu(e),bS(e)].filter(Boolean).join(" · ");if(t==="list"){const n=[];e.include_stored===!0&&n.push("stored");const r=Et(e.query);return r&&n.push(r),n.join(" · ")}return null}function FM(e,t,n,r){const o=e.trim();if(o.toLowerCase()==="bridge")return Ja(yi(t,n),t,r,n);if(!t)return o;if(o==="send")return oS(t)||o;if(o.toLowerCase()==="sessions"){const c=vS(t);if(c!==null)return c||o}const s=ES(o)?Object.entries(t).filter(([c])=>!Mh.has(c)):Object.entries(t);let a=s.filter(([c])=>Jk.has(c)).map(([,c])=>Et(c)).filter(Boolean);if(a.length===0){const c=Xk[o.toLowerCase()];a=s.map(([l,d])=>c?.[l]?.(d)||Et(d)).filter(Boolean)}return a.slice(0,2).join(" ")||o}function Oh(e){const t=e.trim();if(!t.toLowerCase().startsWith(vu))return t;const n=t.slice(vu.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function yS(e,t){return e===t||e===Oh(t)}const wS=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,kS="… ";function UM(e,t=!1){if(!e||t)return null;for(const n of e.split(`
23
+ `)){const r=n.trim();if(r&&!wS.test(r))return`${kS}${r.slice(0,160)}`}return null}function Ph(e){const t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;if(t<3600){const o=Math.floor(t/60),s=t%60;return s===0?`${o}m`:`${o}m${s}s`}if(t<86400){const o=Math.floor(t/3600),s=Math.floor(t%3600/60);return s===0?`${o}h`:`${o}h${s}m`}const n=Math.floor(t/86400);if(n>99)return"100d+";const r=Math.floor(t%86400/3600);return r===0?`${n}d`:`${n}d${r}h`}function BM(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`:Ph(t)}function wu(e){const t=e*10,n=Math.floor(t),r=t-n;return((r>.5?n+1:r<.5||n%2===0?n:n+1)/10).toFixed(1)}function HM(e){const t={minimumFractionDigits:1,maximumFractionDigits:1};return e<1024?mo(e,"B",{maximumFractionDigits:0}):e<1024*1024?mo(Number(wu(e/1024)),"KB",t):mo(Number(wu(e/(1024*1024))),"MB",t)}function Xa(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const ku={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 WM(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(ku,t)?ku[t]:"plain"}function SS(e){if(!e)return"";for(const t of Mh){const n=e[t];if(typeof n=="string"&&n.trim()){const r=n.trim().toLowerCase(),o=e.remove,s=o===!0||o===1||typeof o=="string"&&Qk.has(o.toLowerCase());return r==="milestone"&&s?"milestone-remove":t==="op"&&(r==="react"||r==="ack")?yi(e).action:r}}return""}const Mh=new Set(["op","action","method"]),ES=e=>Object.prototype.hasOwnProperty.call(jh,e.trim().toLowerCase()),Su=({settled:e,running:t})=>({settled:_(e),running:_(t)}),AS={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"}},jh={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 IS(e,t){const n=e.trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(n==="bridge"){const{settled:a,running:c}=Ya(r);return{settled:a,running:c,named:!0}}const o=r?jh[n]?.[r]:void 0;if(o)return{...Su(o),named:!0};const s=AS[n];return s?{...Su(s),named:!0}:{settled:_("ui.chat.canonical.tool_row.generic_verb.settled"),running:_("ui.chat.canonical.tool_row.generic_verb.running"),named:!1}}function GM(e,t,n,r,o="",s=null){const a=IS(e,o),c=yS(t,e)?n??"":t;return{verb:r?a.running:s??a.settled,object:a.named?c:[Oh(e),c].filter(Boolean).join(" ")}}const RS=new Set(["write","edit"]);function xS(e){return RS.has(e.trim().toLowerCase())}function zM(e){return xS(e.toolName)&&e.diff!==null&&!e.isError}function $h(e){if(!e||typeof e!="object")return null;const t=e.diff;if(typeof t=="string")return t?t.split(`
24
+ `):null;if(!Array.isArray(t))return null;const n=t.filter(r=>typeof r=="string");return n.length?n:null}function TS(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 Nh(e,t){return e===null||TS(e,t)?t:e}function Dh(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:Xa(n.added),removed:Xa(n.removed)}}function Lh(e,t){return!e||typeof e!="object"?t:Xa(e.diff_truncated_rows)}function CS(e){return e.length>=2&&Pr(e[0])==="---"&&Pr(e[1])==="+++"?e.slice(2):e.slice()}const OS=/\s+$/;function Pr(e){return e.replace(OS,"")}function PS(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const Eu=40,MS="[output withheld: credential redaction requires a complete bounded diff]";function jS(e){return e.length===0||Pr(e[0])!==MS?!1:e.slice(1).every(t=>Pr(t)===""||Pr(t)==="…")}function KM(e,t={}){const n=CS(e);if(jS(n))return{lines:[],hidden:0,expandable:!1,withheld:!0};const r=n.length>Eu,o=t.expanded?n:n.slice(0,Eu);return{lines:o.map(s=>{const a=Pr(s);return{text:a,marker:a.slice(0,1),kind:PS(a)}}),hidden:n.length-o.length,expandable:r,withheld:!1}}function VM(e){return _("ui.chat.canonical.tool_row.diff.more",{count:e})}function ZM(){return _("ui.chat.canonical.tool_row.diff.show_less")}function YM(e){return _("ui.chat.canonical.tool_row.diff.truncated",{count:e})}function JM(){return _("ui.chat.canonical.tool_row.diff.withheld")}const $S=new Set(["agent","team"]),NS=1048576;function ol(e,t){if(!$S.has(e)||!t||typeof t!="object"||Array.isArray(t))return null;try{const n=JSON.stringify(t);if(new TextEncoder().encode(n).byteLength>NS)return null}catch{return null}return!zk(t)&&!Cr(t)&&!Zk(t)?null:t}function Fh(e,t,n){return ol(e,t)??Th(t,n)}const DS=`Continue working toward this goal:
25
25
 
26
- `,DS=`
26
+ `,LS=`
27
27
 
28
- Make concrete progress with the tools available, then state plainly what advanced and what remains. If the goal is fully met, say so and stop.`,LS=`Work toward this goal:
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.`,FS=`Work toward this goal:
29
29
 
30
30
  {goal}
31
31
 
32
- Make concrete progress with the tools available, then briefly state what advanced and what remains. If the goal is already fully met, say so plainly.`,[FS="",US=""]=LS.split("{goal}"),BS="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.",HS="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.",WS="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 Fh(e){const t=e.trim();return t===BS||t===HS||t===WS||t.startsWith(NS)&&t.endsWith(DS)||t.startsWith(FS.trim())&&t.endsWith(US.trim())}const GS=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function zS(e,t){const n=t?.match(GS)?.[0]??null;if(!e||typeof e!="object")return n;const r=e,o=r.cost_usd,s=r.billing_basis;if(typeof o!="number"||!Number.isFinite(o)||o<0)return n;if(s!=="billed"&&s!=="estimated")return null;const a=Number(o.toFixed(4));return`Cost ${a===0&&o>0?"<$0.0001":`$${a}`} (${s}).`}function wi(e){switch(e.id){case"interrupted":return _("ui.chat.canonical.notice.interrupted");case"stopped_with_error":return _("ui.chat.canonical.notice.stopped_with_error");case"compaction_not_run":return e.sentence.includes(":")?_("ui.chat.canonical.notice.compaction_not_run_after_colon",{detail:e.sentence}):_("ui.chat.canonical.notice.compaction_not_run",{detail:e.sentence})}}function JM(e){return e.copy?wi(e.copy):e.text}function vr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}const KS=32,VS=32*1024,ZS=256*1024;function YS(e,t,n=[]){const r=new Map(e.filter(m=>m.type==="message").map(m=>[m.id,m])),o=new Map,s=new Map,a=new Map,c=new Set(n.filter(m=>m.conflict).map(m=>m.entry.payload.target));for(const m of[...n.map(y=>y.entry),...e]){if(m.type!=="prune"||!vr(m.payload))continue;const{target:y,replacement:b}=m.payload;if(typeof y!="string"||!Number.isFinite(m.ts)||!vr(b)||b.kind!=="message"||b.role!=="tool"||!Array.isArray(b.content)||!vr(b.provider_payload)||Object.keys(b).some(O=>!["kind","role","content","tool_call_id","tool_name","provider_payload"].includes(O))||b.content.length===0||b.content.some(O=>!vr(O)||typeof O.text!="string"||O.text.length>1e5||O.type!==void 0&&O.type!=="text"))continue;const v=b.tool_name;if(typeof v!="string"||typeof b.tool_call_id!="string"||b.tool_call_id.length===0)continue;const p=rl(v,b.provider_payload.details),A=Cr(p),k=Zk(A?.profile_action);if(!A||A.status!=="applied"||A.profile_kind!==v||!k||k.receipt_id!==A.receipt_id||k.profile_kind!==A.profile_kind||k.profile_name!==A.profile_name)continue;const C=a.get(y),L=c.has(y)||!!(C&&JSON.stringify(C.entry.payload.replacement)!==JSON.stringify(b));a.set(y,{entry:C?.entry??m,...L||C?.conflict?{conflict:!0}:{}})}const l=[];let d=2;const u=m=>{if(new TextEncoder().encode(JSON.stringify(m.entry)).length>VS)return;const y=new TextEncoder().encode(JSON.stringify(m)).length+(l.length?1:0);l.length<KS&&d+y<=ZS&&(l.push(m),d+=y)};for(const m of a.values()){const{entry:y}=m,{target:b,replacement:v}=y.payload,p=v.tool_name,A=Cr(v.provider_payload.details);if(!A)continue;const k=r.get(b),C=k?void 0:t.find(F=>F.kind==="tool"&&F.sourceEntryId===b);if(m.conflict||!k&&(!C||C.kind!=="tool")){u(m);continue}const L=k?.payload,O=L&&vr(L.provider_payload)?L.provider_payload.details:C?.kind==="tool"?C.details:null,I=Cr(O),g=L?.tool_call_id??(C?.kind==="tool"?C.toolCallId:null),w=L?.tool_name??(C?.kind==="tool"?C.toolName:null),S=k?.ts??(C?C.ts/1e3:0);if(k&&(L?.role!=="tool"||k.type!=="message")||!I||w!==p||g!==v.tool_call_id||y.ts<S||!I.receipt_id||!I.approval_id||!I.request_digest||I.receipt_id!==A.receipt_id||I.approval_id!==A.approval_id||I.request_digest!==A.request_digest||I.profile_kind!==A.profile_kind||I.profile_name!==A.profile_name||I.scope!==A.scope)continue;const x=k?{...k,payload:v}:{id:b,type:"message",ts:S,payload:v,...C?.journalSeq!==void 0?{journal_seq:C.journalSeq}:{}};k?o.set(b,x):s.set(y.id,x)}const f=e.map(m=>o.get(m.id)??s.get(m.id)??m);for(const[m,y]of s)e.some(b=>b.id===m)||f.push(y);const h=n.length===l.length&&l.every((m,y)=>m.entry===n[y].entry&&m.conflict===n[y].conflict);return{entries:f,pending:h?n:l}}function JS(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||!vr(e.payload.provider_payload))return!1;const n=Cr(e.payload.provider_payload.details),r=Cr(t.details);return!!(n?.status==="queued"&&r?.status==="applied"&&n.receipt_id&&n.receipt_id===r.receipt_id&&n.approval_id&&n.approval_id===r.approval_id&&n.request_digest&&n.request_digest===r.request_digest&&n.profile_kind===r.profile_kind&&n.profile_name===r.profile_name&&n.scope===r.scope)}function Uh(e){return e}const Xa="supplement_v1",QS="superseded",qs=120,ol=480,XS=20,QM=500,qS=10,eE=["outside","sensitive","missing","too-large"];function Bh(e,t){const n=[];let r=0;if(Array.isArray(e))for(const s of e.slice(0,qS)){if(!s||typeof s!="object")continue;const a=s,c=a.reason;if(!eE.includes(c)){r+=1;continue}n.push({name:typeof a.name=="string"?a.name:"",reason:c})}const o=typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;return{withheld:n,withheldMore:o+r}}function sl(e){return`supplement:${e}`}function tE(e){const t=e.payload??{};if(String(t.custom_type??"")!==Xa)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?sl(r):null}function ei(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function nE(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.path=="string"?t.path:"",r=typeof t.name=="string"?t.name:"";return!n&&!r?null:{path:n,name:r,kind:typeof t.kind=="string"?t.kind:"",sizeBytes:ei(t.size_bytes)??0,mtime:ei(t.mtime)??0,why:typeof t.why=="string"?t.why:"",...t.pinned===!0?{pinned:!0}:{}}}function Hh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=nE(n);r&&t.push(r)}return t}function rE(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!zh(n))return null;const r=ei(t.height_hint);return{attachment:n,title:typeof t.title=="string"?t.title:"",source:typeof t.source=="string"?t.source:"",mime:typeof t.mime=="string"?t.mime:"text/html",heightHint:r===null?qs:Math.min(ol,Math.max(qs,Math.round(r)))}}function Wh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=rE(n);r&&t.push(r)}return t}function oE(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return zh(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:ei(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 Gh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=oE(n);r&&t.push(r)}return t}const sE=/^[a-f0-9]{32}$/,iE=/\s+/;function zh(e){return typeof e=="string"&&sE.test(e)}const aE={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function Eu(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 XM(e,t){const n=e.state;if(e.error===QS||e.dismissed||n==="skipped")return"nothing";if(n==="done")return e.files.length||e.components.length||e.sounds?.length||e.withheld?.length||e.withheldMore?"block":"nothing";let r;if(n==="failed")r="failed_retry";else if(n==="cancelled")r="cancelled_retry";else if(n==="decided"||n==="queued"||n==="running"||n==="cancelling")r=t?"preparing":"cancelled_retry";else return"nothing";return e.files.length?aE[r]??r:r}const qM="Preparing highlights…",ej="Highlights cancelled",tj="Couldn't prepare highlights",nj="Adjust…",rj="Cancel",oj="Retry",cE=64,lE={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 sj(e){return typeof e=="string"&&e?lE[e]??"":""}function ta(e){return typeof e!="string"?"":e.replace(uh,"").split(iE).filter(Boolean).join(" ")}function ij(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function dE(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return mo(Math.trunc(e),"B",{maximumFractionDigits:0});const t=[["KB",1024],["MB",1024**2],["GB",1024**3]];for(const[n,r]of t)if(e<r*1024||n==="GB"){const o=e/r;return mo(o,n,{maximumFractionDigits:1})}return""}function aj(e){const t=ta(e.name)||ta(e.path),n=ta(e.path);return{name:t,path:n===t?"":n,size:dE(e.sizeBytes)}}function na(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function cj(e,t,n=e){return t?`Hide ${na(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${na(e,"graphic")}`:`Show ${na(e,"graphic")}`}function lj(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const uE="supplement",fE=1,pE=["ready","resize","error","pong"],hE=["resize","error","pong"],mE=64,il=300,dj=5e3,uj=2e4;function fj(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==uE||n.v!==fE)return null;const r=n.t;if(typeof r!="string"||!pE.includes(r))return null;const o=r;if(hE.includes(o)&&(!t||t.length>mE||n.n!==t))return null;if(o==="error"){const s=n.msg;if(typeof s!="string"||s.length>il)return null}if(o==="resize"){const s=n.h;if(typeof s!="number"||!Number.isFinite(s)||s<0)return null}return{lo:"supplement",v:1,t:o,...typeof n.n=="string"?{n:n.n}:{},...typeof n.h=="number"?{h:n.h}:{},...typeof n.msg=="string"?{msg:n.msg}:{}}}function pj(){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 gE=["--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"],_E=120;function bE(e=typeof document>"u"?null:document.documentElement){if(!e||typeof getComputedStyle!="function")return{mode:"dark",vars:{}};const t=getComputedStyle(e),n={};for(const o of gE){const s=t.getPropertyValue(o).trim();s&&(n[o]=s.slice(0,_E))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function hj(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(bE()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function mj(e){return`data:text/html;base64,${vE(e)}`}function vE(e){const t=yE(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let o=0;o<t.length;o+=3){const s=t[o]??0,a=t[o+1]??0,c=t[o+2]??0;r+=n[s>>2],r+=n[(s&3)<<4|a>>4],r+=o+1<t.length?n[(a&15)<<2|c>>6]:"=",r+=o+2<t.length?n[c&63]:"="}return r}function yE(e){const t=[];for(const n of e){const r=n.codePointAt(0)??0;r<=127?t.push(r):r<=2047?t.push(192|r>>6,128|r&63):r<=65535?t.push(224|r>>12,128|r>>6&63,128|r&63):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return t}function gj(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function wE(e){return Math.min(ol,Math.max(qs,e.heightHint))}function kE(e){return Math.min(ol,Math.max(qs,e))}function _j(e,t,n){let r=0;const o=[];for(let s=0;s<e.length;s+=1){const a=e[s],c=n?.get(a.attachment),l=c!==void 0?kE(c):wE(a);if(s>0&&(!o.every(u=>n?.get(u.attachment)!==void 0)||r+l>t))break;r+=l,o.push(a)}return{visible:o,hidden:e.slice(o.length)}}const SE=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,Kh=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,EE=/kind=(auth|quota)\b/,AE=/kind=(transient|timeout)\b/;function Vh(e){const t=a=>typeof a=="string"&&SE.test(a)&&!a.includes("://")?a:"",n=t(e.model),r=Array.isArray(e.attempts)?e.attempts.map(t).filter(Boolean).slice(0,8):void 0,o=Array.isArray(e.detail)?e.detail.filter(a=>typeof a=="string"&&(Kh.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,s=typeof e.cause=="string"?e.cause.slice(0,cE):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...o?{detail:o}:{},...s?{cause:s}:{}}}function bj(e){if(!Kh.exec(e))return"";const n=e.split(" "),r=n[1].replace(":",""),o=n[3].slice(7),s=n[4].slice(5);return`Attempt ${r}: ${s}${o==="None"?"":` (HTTP ${o})`}`}function vj(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return EE.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":AE.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 IE(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return Zh(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:Hh(e.files),..."withheld"in e||"withheld_more"in e?Bh(e.withheld,e.withheld_more):{}}:{},...n==="done"?{components:Wh(e.components),sounds:Gh(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,il)}:{},...Vh(e),live:!Yh(n)}:null}function RE(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!Zh(n))return null;const r=typeof e.files_more=="number"&&Number.isInteger(e.files_more)&&e.files_more>=0?e.files_more:0,o=Array.isArray(e.more)?e.more.filter(a=>typeof a=="string").slice(0,XS):[];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:Hh(e.files),filesMore:r,more:o,components:Wh(e.components),sounds:Gh(e.sounds),...Bh(e.withheld,e.withheld_more),...Vh(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,il)}:{}}}function Au(e,t,n){const r=RE(t);if(!r)return null;const o=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return Jh(o,r,e)}function Zh(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Yh(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function xE(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.path===o.path&&n.name===o.name&&n.kind===o.kind&&n.sizeBytes===o.sizeBytes&&n.mtime===o.mtime&&n.why===o.why&&(n.pinned??!1)===(o.pinned??!1)})}function TE(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.attachment===o.attachment&&n.title===o.title&&n.source===o.source&&n.mime===o.mime&&n.heightHint===o.heightHint})}function CE(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.attachment===o.attachment&&n.mime===o.mime&&n.title===o.title&&n.durationS===o.durationS&&n.origin===o.origin&&(n.path??"")===(o.path??"")&&(n.pinned??!1)===(o.pinned??!1)})}function OE(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n.name===t[r].name&&n.reason===t[r].reason)}function Jh(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&Eu(t.state)<Eu(e.state)))return null;const r=!e||t.version>e.version,o=t.files!==void 0?t.files:e?.files??[],s=t.components!==void 0?t.components:e?.components??[],a=t.sounds!==void 0?t.sounds:e?.sounds??[],c=t.withheld!==void 0?t.withheld:e?.withheld??[],l=t.withheldMore!==void 0?t.withheldMore:e?.withheldMore??0,d=t.filesMore!==void 0?t.filesMore:e?.filesMore??0,u=t.more!==void 0?t.more:e?.more??[],f=t.error??(r?"":e?.error??""),h=t.cause??(r?"":e?.cause??""),m=t.dismissed??(r?!1:e?.dismissed??!1),y=t.live!==void 0?t.live===!0?!0:Yh(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:sl(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:xE(o,e?.files??[])?e?.files??[]:o,filesMore:d,more:PE(u,e?.more??[])?e?.more??[]:u,components:TE(s,e?.components??[])?e?.components??[]:s,sounds:CE(a,e?.sounds??[])?e?.sounds??[]:a,withheld:OE(c,e?.withheld??[])?e?.withheld??[]:c,withheldMore:l,error:f,cause:h,model:t.model??(r?"":e?.model??""),attempts:t.attempts??(r?[]:e?.attempts??[]),detail:t.detail??(r?[]:e?.detail??[]),dismissed:m,live:y}}function PE(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const yj=e=>e.kind===void 0||e.kind==="image",Lt={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function Qh(e){return e==="skipped"||e==="aborted"}function Iu(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Ru(e,t,n,r){return Iu(n.args)??(r?.kind==="tool"?r.args:null)??Iu(e.argsByCall.get(t)?.arguments)}function Xh(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function qh(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 _s(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Yt(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!Xh(n)&&qh(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Jn(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:_o;const o=[];for(const s of r){const a=qh(s);if(s.type==="document"||a===null&&!Xh(s))continue;const c={id:`${t}:${o.length}`,data:typeof s.data=="string"&&s.data?s.data:null,attachment:typeof s.attachment=="string"&&s.attachment?s.attachment:null,mimeType:typeof s.content_type=="string"&&s.content_type||typeof s.mime_type=="string"&&s.mime_type||"image/png"};a!==null&&(c.kind=a,c.width=_s(s.width),c.height=_s(s.height),c.sizeBytes=_s(s.size_bytes),c.durationS=_s(s.duration_s),c.name=typeof s.name=="string"&&s.name?s.name:null,c.sourceUrl=typeof s.source_url=="string"&&s.source_url?s.source_url:null),o.push(c)}return o.length===0?_o:n&&al(n,o)?n:o}const _o=[],qa=[];function em(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:qa;const o=[];for(const s of r){const a=typeof s.filename=="string"&&typeof s.mime_type=="string"&&typeof s.attachment=="string"&&s.type===void 0;s.type!=="document"&&!a||o.push({id:`${t}:doc:${o.length}`,attachment:typeof s.attachment=="string"&&s.attachment?s.attachment:null,filename:typeof s.filename=="string"&&s.filename?s.filename:s.name??"Attached file",mimeType:s.mime_type??"application/octet-stream",path:typeof s.path=="string"&&s.path?s.path:null,storedPath:typeof s.stored_path=="string"&&s.stored_path?s.stored_path:null,bytes:typeof s.bytes=="number"?s.bytes:0,...s.injection?{injection:s.injection}:{}})}return o.length===0?n?.length?n:qa:n&&ME(n,o)?n:o}function ME(e,t){return e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.id===o.id&&n.attachment===o.attachment&&n.filename===o.filename&&n.mimeType===o.mimeType&&n.path===o.path&&n.storedPath===o.storedPath&&n.bytes===o.bytes&&n.injection===o.injection})}function xu(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 tm(e,t,n){if(t.length===0)return e;if(e.length===0||al(e,t))return t;const r=xu(e),o=xu(t);return r!==o?r>o?e:t:n==="incoming"?e:t}function jE(e,t){return tm(e,t,"incoming")}function al(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 It(e){const t=new Map;return e.forEach((n,r)=>t.set(n.id,r)),t}function $E(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const _n=new Set;function cl(e){return e.kind==="user"&&e.provisional===!0}function nm(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{cl(n)&&r<t&&(t=r)}),t}function Uo(e,t=_n,n){if(n?.journalMode)return Xp(n,e).map(Uh);const r=e.map((a,c)=>({record:a,position:c})),o=nm(e),s=a=>cl(a.record)||a.position>o&&!t.has(a.record.id);return r.sort((a,c)=>{const l=s(a),d=s(c);return l!==d?l?1:-1:l?a.position-c.position:a.record.ts!==c.record.ts?a.record.ts-c.record.ts:a.position-c.position}).map(a=>a.record)}function NE(e,t,n){if(!n||t<=0)return _n;let r=null;for(const o of e){if(!cl(o)||!(t>o.ts))continue;let s=!1,a=!1;for(const c of e)if(c.ts>o.ts?s=!0:c.ts<o.ts&&fl(c)&&(a=!0),s&&a)break;s&&a&&(r??=new Set,r.add(o.id))}return r??_n}function DE(e){const{provisional:t,...n}=e;return n}function ec(e,t){const n=e,r=t,o=Object.keys(n);if(o.length!==Object.keys(r).length)return!1;for(const s of o)if(n[s]!==r[s]){if(s==="images"){const a=n[s],c=r[s];if(Array.isArray(a)&&Array.isArray(c)&&al(a,c))continue}if(s==="frame"){const a=n[s],c=r[s];if(a!==void 0&&c!==void 0&&a.epoch===c.epoch&&a.seq===c.seq)continue}if(s==="skill"){const a=n[s],c=r[s];if(a!==void 0&&c!==void 0&&LE(a,c))continue}return!1}return!0}function LE(e,t){return e.name===t.name&&e.token===t.token&&e.request===t.request&&e.purpose===t.purpose&&e.body===t.body}function Ne(e,t){const n=e.index.get(t.id);if(n!==void 0){const s=e.records[n];if(ec(s,t))return e;const a=e.records.slice();if(a[n]=e.journalMode?{...t,...s.sourceEntryId?{sourceEntryId:t.sourceEntryId??s.sourceEntryId}:{},...s.sourceAdmissionAnchor&&!t.sourceAdmissionAnchor?{sourceAdmissionAnchor:s.sourceAdmissionAnchor}:{},...s.sourcePrecedes&&!t.sourcePrecedes?{sourcePrecedes:s.sourcePrecedes}:{},...s.journalGeneration?{journalGeneration:t.journalGeneration??s.journalGeneration,journalSeq:t.journalSeq??s.journalSeq}:{}}:t,!e.journalMode)return{...e,records:a};const c=Uo(a,_n,e);return{...e,records:c,index:It(c)}}const r=e.journalMode?Uo([...e.records,t],_n,e):[...e.records,t],o=It(r);return{...e,records:r,index:o}}function ll(e,t){if(!e.records.some(t))return e;const n=e.records.filter(r=>!t(r));return{...e,records:n,index:It(n)}}function ra(e,t){const n=`tool:${t}`,r=e.index.get(n);if(r===void 0)return e;const o=e.records[r];return o.kind==="tool"&&(o.phase==="composing"||o.phase==="queued")?ll(e,s=>s.id===n):e}function FE(e,t,n){const r=e.index.get(`tool:${t}`);if(r===void 0)return e;const o=e.records[r];if(!(o.kind==="tool"&&(o.phase==="composing"||o.phase==="queued")))return e;const s=e.records.slice();return s[r]=n,{...e,records:s,index:It(s)}}const UE=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function rm(e){const t=e.trim()||"compaction did not run",n={id:"compaction_not_run",sentence:t};return{text:wi(n),copy:n,level:t.startsWith("compaction failed")?"error":"warning"}}function BE(e,t){const n=Lu(e),r=Lu(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const om="Context compacted",HE=12e4;function sm(e){const t=[],n=[];for(const d of e)d.kind==="compaction"&&(d.id.startsWith("compaction:")?t.push(d):n.push(d));if(t.length===0||n.length===0)return e;const r=new Set,o=new Set,s=new Map,a=(d,u)=>{r.add(u.id),o.add(d.id),s.set(u.id,d.text)},c=[...t].sort((d,u)=>d.ts-u.ts);for(const d of c){if(d.before===void 0)continue;const u=n.find(f=>!r.has(f.id)&&f.before===d.before);u&&a(d,u)}const l=[];for(const d of c)if(!o.has(d.id))for(const u of n){if(u.before!==void 0)continue;const f=Math.abs(u.ts-d.ts);f>HE||l.push({live:d,durable:u,distance:f})}l.sort((d,u)=>d.distance-u.distance);for(const{live:d,durable:u}of l)o.has(d.id)||r.has(u.id)||a(d,u);return o.size===0?e:e.filter(d=>!o.has(d.id)).map(d=>{const u=s.get(d.id);return u===void 0||d.kind!=="compaction"&&d.kind!=="notice"||u===d.text?d:{...d,text:u}})}function WE(e){const t=sm(e.records);return t===e.records?e:{...e,records:t,index:It(t)}}const GE="peer_message",zE="ask_response",KE="ask_timeout",im="Completed — runtime retired/disposed",am="Retired for an update — a turn was in flight and was cut; its earlier output is kept",VE="wake_prompt",ZE="session_mcp_unavailable",YE=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),JE=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,Tu=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,QE=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."]),cm=/^\[[^\]]{1,32}\]\s*/,ti="Reason:",XE=/[\n;,(]| [—–] /,qE=/^\d+\.$/,eA=/[A-Z]/,tA=/\s/,bo=160;function Ps(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",...iA(t,n)};let r;return e===ZE?r=nA(t):YE.has(e)?r=oA(t.trim().replace(cm,"")):r=aA(t),{level:"info",category:null,provider:null,...r}}function nA(e){const t=e.trim().replace(cm,"").split(`
32
+ Make concrete progress with the tools available, then briefly state what advanced and what remains. If the goal is already fully met, say so plainly.`,[US="",BS=""]=FS.split("{goal}"),HS="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.",WS="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.",GS="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 Uh(e){const t=e.trim();return t===HS||t===WS||t===GS||t.startsWith(DS)&&t.endsWith(LS)||t.startsWith(US.trim())&&t.endsWith(BS.trim())}const zS=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function KS(e,t){const n=t?.match(zS)?.[0]??null;if(!e||typeof e!="object")return n;const r=e,o=r.cost_usd,s=r.billing_basis;if(typeof o!="number"||!Number.isFinite(o)||o<0)return n;if(s!=="billed"&&s!=="estimated")return null;const a=Number(o.toFixed(4));return`Cost ${a===0&&o>0?"<$0.0001":`$${a}`} (${s}).`}function wi(e){switch(e.id){case"interrupted":return _("ui.chat.canonical.notice.interrupted");case"stopped_with_error":return _("ui.chat.canonical.notice.stopped_with_error");case"compaction_not_run":return e.sentence.includes(":")?_("ui.chat.canonical.notice.compaction_not_run_after_colon",{detail:e.sentence}):_("ui.chat.canonical.notice.compaction_not_run",{detail:e.sentence})}}function QM(e){return e.copy?wi(e.copy):e.text}function vr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}const VS=32,ZS=32*1024,YS=256*1024;function JS(e,t,n=[]){const r=new Map(e.filter(m=>m.type==="message").map(m=>[m.id,m])),o=new Map,s=new Map,a=new Map,c=new Set(n.filter(m=>m.conflict).map(m=>m.entry.payload.target));for(const m of[...n.map(y=>y.entry),...e]){if(m.type!=="prune"||!vr(m.payload))continue;const{target:y,replacement:b}=m.payload;if(typeof y!="string"||!Number.isFinite(m.ts)||!vr(b)||b.kind!=="message"||b.role!=="tool"||!Array.isArray(b.content)||!vr(b.provider_payload)||Object.keys(b).some(C=>!["kind","role","content","tool_call_id","tool_name","provider_payload"].includes(C))||b.content.length===0||b.content.some(C=>!vr(C)||typeof C.text!="string"||C.text.length>1e5||C.type!==void 0&&C.type!=="text"))continue;const v=b.tool_name;if(typeof v!="string"||typeof b.tool_call_id!="string"||b.tool_call_id.length===0)continue;const p=ol(v,b.provider_payload.details),A=Cr(p),k=Yk(A?.profile_action);if(!A||A.status!=="applied"||A.profile_kind!==v||!k||k.receipt_id!==A.receipt_id||k.profile_kind!==A.profile_kind||k.profile_name!==A.profile_name)continue;const T=a.get(y),F=c.has(y)||!!(T&&JSON.stringify(T.entry.payload.replacement)!==JSON.stringify(b));a.set(y,{entry:T?.entry??m,...F||T?.conflict?{conflict:!0}:{}})}const l=[];let d=2;const u=m=>{if(new TextEncoder().encode(JSON.stringify(m.entry)).length>ZS)return;const y=new TextEncoder().encode(JSON.stringify(m)).length+(l.length?1:0);l.length<VS&&d+y<=YS&&(l.push(m),d+=y)};for(const m of a.values()){const{entry:y}=m,{target:b,replacement:v}=y.payload,p=v.tool_name,A=Cr(v.provider_payload.details);if(!A)continue;const k=r.get(b),T=k?void 0:t.find(N=>N.kind==="tool"&&N.sourceEntryId===b);if(m.conflict||!k&&(!T||T.kind!=="tool")){u(m);continue}const F=k?.payload,C=F&&vr(F.provider_payload)?F.provider_payload.details:T?.kind==="tool"?T.details:null,I=Cr(C),g=F?.tool_call_id??(T?.kind==="tool"?T.toolCallId:null),w=F?.tool_name??(T?.kind==="tool"?T.toolName:null),S=k?.ts??(T?T.ts/1e3:0);if(k&&(F?.role!=="tool"||k.type!=="message")||!I||w!==p||g!==v.tool_call_id||y.ts<S||!I.receipt_id||!I.approval_id||!I.request_digest||I.receipt_id!==A.receipt_id||I.approval_id!==A.approval_id||I.request_digest!==A.request_digest||I.profile_kind!==A.profile_kind||I.profile_name!==A.profile_name||I.scope!==A.scope)continue;const x=k?{...k,payload:v}:{id:b,type:"message",ts:S,payload:v,...T?.journalSeq!==void 0?{journal_seq:T.journalSeq}:{}};k?o.set(b,x):s.set(y.id,x)}const f=e.map(m=>o.get(m.id)??s.get(m.id)??m);for(const[m,y]of s)e.some(b=>b.id===m)||f.push(y);const h=n.length===l.length&&l.every((m,y)=>m.entry===n[y].entry&&m.conflict===n[y].conflict);return{entries:f,pending:h?n:l}}function QS(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||!vr(e.payload.provider_payload))return!1;const n=Cr(e.payload.provider_payload.details),r=Cr(t.details);return!!(n?.status==="queued"&&r?.status==="applied"&&n.receipt_id&&n.receipt_id===r.receipt_id&&n.approval_id&&n.approval_id===r.approval_id&&n.request_digest&&n.request_digest===r.request_digest&&n.profile_kind===r.profile_kind&&n.profile_name===r.profile_name&&n.scope===r.scope)}function Bh(e){return e}const qa="supplement_v1",XS="superseded",qs=120,sl=480,qS=20,XM=500,eE=10,tE=["outside","sensitive","missing","too-large"];function Hh(e,t){const n=[];let r=0;if(Array.isArray(e))for(const s of e.slice(0,eE)){if(!s||typeof s!="object")continue;const a=s,c=a.reason;if(!tE.includes(c)){r+=1;continue}n.push({name:typeof a.name=="string"?a.name:"",reason:c})}const o=typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;return{withheld:n,withheldMore:o+r}}function il(e){return`supplement:${e}`}function nE(e){const t=e.payload??{};if(String(t.custom_type??"")!==qa)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?il(r):null}function ei(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function rE(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.path=="string"?t.path:"",r=typeof t.name=="string"?t.name:"";return!n&&!r?null:{path:n,name:r,kind:typeof t.kind=="string"?t.kind:"",sizeBytes:ei(t.size_bytes)??0,mtime:ei(t.mtime)??0,why:typeof t.why=="string"?t.why:"",...t.pinned===!0?{pinned:!0}:{}}}function Wh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=rE(n);r&&t.push(r)}return t}function oE(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!Kh(n))return null;const r=ei(t.height_hint);return{attachment:n,title:typeof t.title=="string"?t.title:"",source:typeof t.source=="string"?t.source:"",mime:typeof t.mime=="string"?t.mime:"text/html",heightHint:r===null?qs:Math.min(sl,Math.max(qs,Math.round(r)))}}function Gh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=oE(n);r&&t.push(r)}return t}function sE(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return Kh(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:ei(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 zh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=sE(n);r&&t.push(r)}return t}const iE=/^[a-f0-9]{32}$/,aE=/\s+/;function Kh(e){return typeof e=="string"&&iE.test(e)}const cE={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function Au(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 qM(e,t){const n=e.state;if(e.error===XS||e.dismissed||n==="skipped")return"nothing";if(n==="done")return e.files.length||e.components.length||e.sounds?.length||e.withheld?.length||e.withheldMore?"block":"nothing";let r;if(n==="failed")r="failed_retry";else if(n==="cancelled")r="cancelled_retry";else if(n==="decided"||n==="queued"||n==="running"||n==="cancelling")r=t?"preparing":"cancelled_retry";else return"nothing";return e.files.length?cE[r]??r:r}const ej="Preparing highlights…",tj="Highlights cancelled",nj="Couldn't prepare highlights",rj="Adjust…",oj="Cancel",sj="Retry",lE=64,dE={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 ij(e){return typeof e=="string"&&e?dE[e]??"":""}function na(e){return typeof e!="string"?"":e.replace(fh,"").split(aE).filter(Boolean).join(" ")}function aj(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function uE(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return mo(Math.trunc(e),"B",{maximumFractionDigits:0});const t=[["KB",1024],["MB",1024**2],["GB",1024**3]];for(const[n,r]of t)if(e<r*1024||n==="GB"){const o=e/r;return mo(o,n,{maximumFractionDigits:1})}return""}function cj(e){const t=na(e.name)||na(e.path),n=na(e.path);return{name:t,path:n===t?"":n,size:uE(e.sizeBytes)}}function ra(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function lj(e,t,n=e){return t?`Hide ${ra(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${ra(e,"graphic")}`:`Show ${ra(e,"graphic")}`}function dj(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const fE="supplement",pE=1,hE=["ready","resize","error","pong"],mE=["resize","error","pong"],gE=64,al=300,uj=5e3,fj=2e4;function pj(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==fE||n.v!==pE)return null;const r=n.t;if(typeof r!="string"||!hE.includes(r))return null;const o=r;if(mE.includes(o)&&(!t||t.length>gE||n.n!==t))return null;if(o==="error"){const s=n.msg;if(typeof s!="string"||s.length>al)return null}if(o==="resize"){const s=n.h;if(typeof s!="number"||!Number.isFinite(s)||s<0)return null}return{lo:"supplement",v:1,t:o,...typeof n.n=="string"?{n:n.n}:{},...typeof n.h=="number"?{h:n.h}:{},...typeof n.msg=="string"?{msg:n.msg}:{}}}function hj(){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 _E=["--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"],bE=120;function vE(e=typeof document>"u"?null:document.documentElement){if(!e||typeof getComputedStyle!="function")return{mode:"dark",vars:{}};const t=getComputedStyle(e),n={};for(const o of _E){const s=t.getPropertyValue(o).trim();s&&(n[o]=s.slice(0,bE))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function mj(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(vE()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function gj(e){return`data:text/html;base64,${yE(e)}`}function yE(e){const t=wE(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let o=0;o<t.length;o+=3){const s=t[o]??0,a=t[o+1]??0,c=t[o+2]??0;r+=n[s>>2],r+=n[(s&3)<<4|a>>4],r+=o+1<t.length?n[(a&15)<<2|c>>6]:"=",r+=o+2<t.length?n[c&63]:"="}return r}function wE(e){const t=[];for(const n of e){const r=n.codePointAt(0)??0;r<=127?t.push(r):r<=2047?t.push(192|r>>6,128|r&63):r<=65535?t.push(224|r>>12,128|r>>6&63,128|r&63):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return t}function _j(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function kE(e){return Math.min(sl,Math.max(qs,e.heightHint))}function SE(e){return Math.min(sl,Math.max(qs,e))}function bj(e,t,n){let r=0;const o=[];for(let s=0;s<e.length;s+=1){const a=e[s],c=n?.get(a.attachment),l=c!==void 0?SE(c):kE(a);if(s>0&&(!o.every(u=>n?.get(u.attachment)!==void 0)||r+l>t))break;r+=l,o.push(a)}return{visible:o,hidden:e.slice(o.length)}}const EE=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,Vh=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,AE=/kind=(auth|quota)\b/,IE=/kind=(transient|timeout)\b/;function Zh(e){const t=a=>typeof a=="string"&&EE.test(a)&&!a.includes("://")?a:"",n=t(e.model),r=Array.isArray(e.attempts)?e.attempts.map(t).filter(Boolean).slice(0,8):void 0,o=Array.isArray(e.detail)?e.detail.filter(a=>typeof a=="string"&&(Vh.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,s=typeof e.cause=="string"?e.cause.slice(0,lE):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...o?{detail:o}:{},...s?{cause:s}:{}}}function vj(e){if(!Vh.exec(e))return"";const n=e.split(" "),r=n[1].replace(":",""),o=n[3].slice(7),s=n[4].slice(5);return`Attempt ${r}: ${s}${o==="None"?"":` (HTTP ${o})`}`}function yj(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return AE.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":IE.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 RE(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return Yh(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:Wh(e.files),..."withheld"in e||"withheld_more"in e?Hh(e.withheld,e.withheld_more):{}}:{},...n==="done"?{components:Gh(e.components),sounds:zh(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,al)}:{},...Zh(e),live:!Jh(n)}:null}function xE(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!Yh(n))return null;const r=typeof e.files_more=="number"&&Number.isInteger(e.files_more)&&e.files_more>=0?e.files_more:0,o=Array.isArray(e.more)?e.more.filter(a=>typeof a=="string").slice(0,qS):[];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:Wh(e.files),filesMore:r,more:o,components:Gh(e.components),sounds:zh(e.sounds),...Hh(e.withheld,e.withheld_more),...Zh(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,al)}:{}}}function Iu(e,t,n){const r=xE(t);if(!r)return null;const o=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return Qh(o,r,e)}function Yh(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Jh(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function TE(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.path===o.path&&n.name===o.name&&n.kind===o.kind&&n.sizeBytes===o.sizeBytes&&n.mtime===o.mtime&&n.why===o.why&&(n.pinned??!1)===(o.pinned??!1)})}function CE(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.attachment===o.attachment&&n.title===o.title&&n.source===o.source&&n.mime===o.mime&&n.heightHint===o.heightHint})}function OE(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.attachment===o.attachment&&n.mime===o.mime&&n.title===o.title&&n.durationS===o.durationS&&n.origin===o.origin&&(n.path??"")===(o.path??"")&&(n.pinned??!1)===(o.pinned??!1)})}function PE(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n.name===t[r].name&&n.reason===t[r].reason)}function Qh(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&Au(t.state)<Au(e.state)))return null;const r=!e||t.version>e.version,o=t.files!==void 0?t.files:e?.files??[],s=t.components!==void 0?t.components:e?.components??[],a=t.sounds!==void 0?t.sounds:e?.sounds??[],c=t.withheld!==void 0?t.withheld:e?.withheld??[],l=t.withheldMore!==void 0?t.withheldMore:e?.withheldMore??0,d=t.filesMore!==void 0?t.filesMore:e?.filesMore??0,u=t.more!==void 0?t.more:e?.more??[],f=t.error??(r?"":e?.error??""),h=t.cause??(r?"":e?.cause??""),m=t.dismissed??(r?!1:e?.dismissed??!1),y=t.live!==void 0?t.live===!0?!0:Jh(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:il(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:TE(o,e?.files??[])?e?.files??[]:o,filesMore:d,more:ME(u,e?.more??[])?e?.more??[]:u,components:CE(s,e?.components??[])?e?.components??[]:s,sounds:OE(a,e?.sounds??[])?e?.sounds??[]:a,withheld:PE(c,e?.withheld??[])?e?.withheld??[]:c,withheldMore:l,error:f,cause:h,model:t.model??(r?"":e?.model??""),attempts:t.attempts??(r?[]:e?.attempts??[]),detail:t.detail??(r?[]:e?.detail??[]),dismissed:m,live:y}}function ME(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const wj=e=>e.kind===void 0||e.kind==="image",Lt={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function Xh(e){return e==="skipped"||e==="aborted"}function Ru(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function xu(e,t,n,r){return Ru(n.args)??(r?.kind==="tool"?r.args:null)??Ru(e.argsByCall.get(t)?.arguments)}function qh(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function em(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 _s(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Yt(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!qh(n)&&em(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Jn(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:_o;const o=[];for(const s of r){const a=em(s);if(s.type==="document"||a===null&&!qh(s))continue;const c={id:`${t}:${o.length}`,data:typeof s.data=="string"&&s.data?s.data:null,attachment:typeof s.attachment=="string"&&s.attachment?s.attachment:null,mimeType:typeof s.content_type=="string"&&s.content_type||typeof s.mime_type=="string"&&s.mime_type||"image/png"};a!==null&&(c.kind=a,c.width=_s(s.width),c.height=_s(s.height),c.sizeBytes=_s(s.size_bytes),c.durationS=_s(s.duration_s),c.name=typeof s.name=="string"&&s.name?s.name:null,c.sourceUrl=typeof s.source_url=="string"&&s.source_url?s.source_url:null),o.push(c)}return o.length===0?_o:n&&cl(n,o)?n:o}const _o=[],ec=[];function tm(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:ec;const o=[];for(const s of r){const a=typeof s.filename=="string"&&typeof s.mime_type=="string"&&typeof s.attachment=="string"&&s.type===void 0;s.type!=="document"&&!a||o.push({id:`${t}:doc:${o.length}`,attachment:typeof s.attachment=="string"&&s.attachment?s.attachment:null,filename:typeof s.filename=="string"&&s.filename?s.filename:s.name??"Attached file",mimeType:s.mime_type??"application/octet-stream",path:typeof s.path=="string"&&s.path?s.path:null,storedPath:typeof s.stored_path=="string"&&s.stored_path?s.stored_path:null,bytes:typeof s.bytes=="number"?s.bytes:0,...s.injection?{injection:s.injection}:{}})}return o.length===0?n?.length?n:ec:n&&jE(n,o)?n:o}function jE(e,t){return e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.id===o.id&&n.attachment===o.attachment&&n.filename===o.filename&&n.mimeType===o.mimeType&&n.path===o.path&&n.storedPath===o.storedPath&&n.bytes===o.bytes&&n.injection===o.injection})}function Tu(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 nm(e,t,n){if(t.length===0)return e;if(e.length===0||cl(e,t))return t;const r=Tu(e),o=Tu(t);return r!==o?r>o?e:t:n==="incoming"?e:t}function $E(e,t){return nm(e,t,"incoming")}function cl(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 It(e){const t=new Map;return e.forEach((n,r)=>t.set(n.id,r)),t}function NE(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const _n=new Set;function ll(e){return e.kind==="user"&&e.provisional===!0}function rm(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{ll(n)&&r<t&&(t=r)}),t}function Uo(e,t=_n,n){if(n?.journalMode)return qp(n,e).map(Bh);const r=e.map((a,c)=>({record:a,position:c})),o=rm(e),s=a=>ll(a.record)||a.position>o&&!t.has(a.record.id);return r.sort((a,c)=>{const l=s(a),d=s(c);return l!==d?l?1:-1:l?a.position-c.position:a.record.ts!==c.record.ts?a.record.ts-c.record.ts:a.position-c.position}).map(a=>a.record)}function DE(e,t,n){if(!n||t<=0)return _n;let r=null;for(const o of e){if(!ll(o)||!(t>o.ts))continue;let s=!1,a=!1;for(const c of e)if(c.ts>o.ts?s=!0:c.ts<o.ts&&pl(c)&&(a=!0),s&&a)break;s&&a&&(r??=new Set,r.add(o.id))}return r??_n}function LE(e){const{provisional:t,...n}=e;return n}function tc(e,t){const n=e,r=t,o=Object.keys(n);if(o.length!==Object.keys(r).length)return!1;for(const s of o)if(n[s]!==r[s]){if(s==="images"){const a=n[s],c=r[s];if(Array.isArray(a)&&Array.isArray(c)&&cl(a,c))continue}if(s==="frame"){const a=n[s],c=r[s];if(a!==void 0&&c!==void 0&&a.epoch===c.epoch&&a.seq===c.seq)continue}if(s==="skill"){const a=n[s],c=r[s];if(a!==void 0&&c!==void 0&&FE(a,c))continue}return!1}return!0}function FE(e,t){return e.name===t.name&&e.token===t.token&&e.request===t.request&&e.purpose===t.purpose&&e.body===t.body}function Ne(e,t){const n=e.index.get(t.id);if(n!==void 0){const s=e.records[n];if(tc(s,t))return e;const a=e.records.slice();if(a[n]=e.journalMode?{...t,...s.sourceEntryId?{sourceEntryId:t.sourceEntryId??s.sourceEntryId}:{},...s.sourceAdmissionAnchor&&!t.sourceAdmissionAnchor?{sourceAdmissionAnchor:s.sourceAdmissionAnchor}:{},...s.sourcePrecedes&&!t.sourcePrecedes?{sourcePrecedes:s.sourcePrecedes}:{},...s.journalGeneration?{journalGeneration:t.journalGeneration??s.journalGeneration,journalSeq:t.journalSeq??s.journalSeq}:{}}:t,!e.journalMode)return{...e,records:a};const c=Uo(a,_n,e);return{...e,records:c,index:It(c)}}const r=e.journalMode?Uo([...e.records,t],_n,e):[...e.records,t],o=It(r);return{...e,records:r,index:o}}function dl(e,t){if(!e.records.some(t))return e;const n=e.records.filter(r=>!t(r));return{...e,records:n,index:It(n)}}function oa(e,t){const n=`tool:${t}`,r=e.index.get(n);if(r===void 0)return e;const o=e.records[r];return o.kind==="tool"&&(o.phase==="composing"||o.phase==="queued")?dl(e,s=>s.id===n):e}function UE(e,t,n){const r=e.index.get(`tool:${t}`);if(r===void 0)return e;const o=e.records[r];if(!(o.kind==="tool"&&(o.phase==="composing"||o.phase==="queued")))return e;const s=e.records.slice();return s[r]=n,{...e,records:s,index:It(s)}}const BE=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function om(e){const t=e.trim()||"compaction did not run",n={id:"compaction_not_run",sentence:t};return{text:wi(n),copy:n,level:t.startsWith("compaction failed")?"error":"warning"}}function HE(e,t){const n=Fu(e),r=Fu(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const sm="Context compacted",WE=12e4;function im(e){const t=[],n=[];for(const d of e)d.kind==="compaction"&&(d.id.startsWith("compaction:")?t.push(d):n.push(d));if(t.length===0||n.length===0)return e;const r=new Set,o=new Set,s=new Map,a=(d,u)=>{r.add(u.id),o.add(d.id),s.set(u.id,d.text)},c=[...t].sort((d,u)=>d.ts-u.ts);for(const d of c){if(d.before===void 0)continue;const u=n.find(f=>!r.has(f.id)&&f.before===d.before);u&&a(d,u)}const l=[];for(const d of c)if(!o.has(d.id))for(const u of n){if(u.before!==void 0)continue;const f=Math.abs(u.ts-d.ts);f>WE||l.push({live:d,durable:u,distance:f})}l.sort((d,u)=>d.distance-u.distance);for(const{live:d,durable:u}of l)o.has(d.id)||r.has(u.id)||a(d,u);return o.size===0?e:e.filter(d=>!o.has(d.id)).map(d=>{const u=s.get(d.id);return u===void 0||d.kind!=="compaction"&&d.kind!=="notice"||u===d.text?d:{...d,text:u}})}function GE(e){const t=im(e.records);return t===e.records?e:{...e,records:t,index:It(t)}}const zE="peer_message",KE="ask_response",VE="ask_timeout",am="Completed — runtime retired/disposed",cm="Retired for an update — a turn was in flight and was cut; its earlier output is kept",ZE="wake_prompt",YE="session_mcp_unavailable",JE=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),QE=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,Cu=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,XE=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*/,ti="Reason:",qE=/[\n;,(]| [—–] /,eA=/^\d+\.$/,tA=/[A-Z]/,nA=/\s/,bo=160;function Ps(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 r;return e===YE?r=rA(t):JE.has(e)?r=sA(t.trim().replace(lm,"")):r=cA(t),{level:"info",category:null,provider:null,...r}}function rA(e){const t=e.trim().replace(lm,"").split(`
33
33
  `).map(c=>c.trim()),n=t[0]??"",r=t[1]?.startsWith(ti)?t[1]:null,o=t.slice(r?2:1).filter(Boolean).join(`
34
- `),s=(r?`${n} ${r}`:n).trim();if(s.length<=bo)return{headline:s,detail:o||null};const a=r===null?null:rA(r);if(a!==null){const c=(f,h)=>`${ti} ${[f,h].filter(Boolean).join(" ")}`,l=f=>[f,o].filter(Boolean).join(`
35
- `)||null,d=`${n} ${c(a.leading,a.clause)}`;if(d.length<=bo)return{headline:d,detail:l(a.rest)};const u=`${n} ${c("",a.clause)}`;if(u.length<=bo)return{headline:u,detail:l([a.leading,a.rest].filter(Boolean).join(" "))}}return{headline:dm(s),detail:[r,o].filter(Boolean).join(`
36
- `)||null}}function rA(e){const t=e.startsWith(ti)?e.slice(ti.length):e,n=t.indexOf("/mcp");if(n<0)return null;const r=t.slice(n),o=r.search(XE),s=(o<0?r:r.slice(0,o)).trim();return s?{leading:t.slice(0,n).trim(),clause:s,rest:(o<0?"":r.slice(o)).trim()}:null}function oA(e){const t=e.trim(),n=sA(t);if(n<0)return{headline:t,detail:null};const r=t.slice(n).trim();return{headline:t.slice(0,n).trim(),detail:r||null}}function sA(e){for(let t=0;t<e.length-1;t++)if(".!?…".includes(e[t])&&tA.test(e[t+1])&&!qE.test(e.slice(0,t+1))&&eA.test(e.slice(t+1).trimStart()[0]??""))return t+1;return-1}function iA(e,t){const n=e.split(`
37
- `),r=n[0].match(JE),s=(typeof t.raw=="string"?t.raw.trim():"")||(r?n[0].slice(r[0].length):n[0]).trim()||e.trim(),a=n.slice(1).join(`
38
- `).trim();return{provider:(r?.[1]??"").trim()||null,category:(r?.[2]??"").trim()||null,headline:s,detail:a||null}}function lm(e){if(typeof e!="object"||e===null)return null;const t=e.hub_receipt;if(typeof t!="object"||t===null)return null;const n=t,r=n.direction;if(r!=="to_child"&&r!=="to_parent")return null;const o=n.body;if(typeof o!="string"||!o.trim())return null;const s={...n};for(const a of["expects_reply","steer"])typeof s[a]!="boolean"&&(s[a]=null);for(const a of["label","job_id"])a in s&&typeof s[a]!="string"&&delete s[a];return s}function aA(e){const t=cA(e),n=e.split(`
39
- `).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function cA(e){const t=e.split(`
40
- `).map(c=>c.trim()).filter(Boolean),n=c=>!Tu.test(c)&&!lA(c),r=t.find(n),o=t.find(c=>Tu.test(c)&&!c.startsWith("</"));let s=r??o??e.trim();const a=t.indexOf(s);if(a>=0&&s.endsWith(":")){const c=t.slice(a+1).find(n);c&&(s=`${s} ${c}`)}return dm(s)}function lA(e){return QE.has(e.replace(/\s+/g," ").trim().toLowerCase())}function dm(e){const t=e.trim();if(t.length<=bo)return t;const n=t.slice(0,bo),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const dA="harness_injected",um=e=>!e||typeof e!="object"?!1:e[dA]===!0;function fm(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function pm(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const uA="ask";function Cu(e,t){return t===!0&&String(e??"")===uA}function fA(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function hm(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:om,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:r,text:a,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const a=n.details??{},c=rm(String(a.detail??""));return{kind:"notice",id:e.id,ts:r,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:r,complete:!0,text:im,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:am,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:r,complete:!0,text:wi(c),copy:c,level:a.kind==="error"?"error":"warning"}}}}if(e.type==="custom"&&n.custom_type===Xa){const a=n.details??{};return Au(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(UE.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=Va(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&qi(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...Ps(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(h=>f[h]===u[h])?f:u,images:Jn(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===GE){const{body:u,sender:f}=hh(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&qi(t.sender,f)?t.sender:f}}if(a===VE){if(sk(c)||ik(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===zE){const u=c.answers,f={};if(u&&typeof u=="object")for(const[y,b]of Object.entries(u))f[String(y)]=Array.isArray(b)?b.map(v=>String(v)):[];const h=c.questions,m=Array.isArray(h)?h.flatMap(y=>{if(!y||typeof y!="object")return[];const b=y;return[{id:String(b.id??""),question:String(b.question??""),secret:b.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:r,askId:String(c.ask_id??""),status:String(c.status??"answered"),by:c.by&&typeof c.by=="object"?c.by:null,reason:typeof c.reason=="string"?c.reason:null,questions:m,answers:f,secretLost:c.secret_lost===!0}}if(a===KE){const u=Number(c.waited_s);return{kind:"ask_timeout",id:e.id,ts:r,askId:String(c.ask_id??""),waitedS:Number.isFinite(u)&&u>0?u:0,urgent:c.urgent===!0}}if(a===Xa)return Au(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?zS(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:a,text:d,...a==="team_bridge_message"?{bridgeReceipt:ak(c)}:{},attribution:n.attribution??"system",...Ps(a,d,c)}:null}const s=String(n.role??"");if(s==="user"){const a=lm(n.provider_payload);if(a){const u=Va({...a,text:Yt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&qi(f.sender,u.sender)&&(u.sender=f.sender);const h=t?.kind==="custom"||t?.kind==="user"?t.images:void 0;return{kind:"custom",id:e.id,ts:r,customType:"hub_message",text:u.envelope,attribution:"user",...Ps("hub_message",u.envelope||u.body,{...a,text:Yt(n)}),receipt:f&&Object.keys(u).every(m=>f[m]===u[m])?f:u,images:Jn(n,e.id,h)}}}if(um(n.provider_payload))return null;const c=Yt(n);if(Fh(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=vi(c),d=em(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Jn(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(s==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=Yt(n);return!c&&a.length>0?{kind:"assistant",id:e.id,ts:r,text:"",streaming:!1,stopReason:String(n.stop_reason??"toolUse"),callsTools:!0,error:!1}:{kind:"assistant",id:e.id,ts:r,text:c,complete:!0,streaming:!1,callsTools:a.length>0,stopReason:n.stop_reason??null,error:!!n.is_error}}if(s==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(pm(l))return null;const d=Qh(l.__fault);return{kind:"tool",id:`tool:${a}`,ts:r,toolCallId:a,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:Yt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Jn(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...Nh(c.details,t?.kind==="tool"?t:null),diff:$h(jh(c.details),t?.kind==="tool"?t.diff:null),diffTruncatedRows:Dh(c.details,t?.kind==="tool"?t.diffTruncatedRows??0:0),stopped:d,delivery:Rh(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:kh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:Sh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:Lh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.details??null:null)}}return null}function pA(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 hA=/^(?:tool|compaction|local):/;function mA(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)&&!hA.test(t.id))return t.id}return null}function gA(e,t){const n=tE(t);if(n)return e.records[e.index.get(n)??-1]}function dl(e){const t=Xp(e,e.records);if(t===e.records)return e;const n=t.map(Uh);return{...e,records:n,index:It(n)}}const Bo=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function mm(e,t,n,r){const o={...e,sourceEntryId:t,journalSeq:r,journalGeneration:n};if(e.kind==="user"&&(e.provisional===!0||e.local===!0)){const{provisional:s,local:a,...c}=o;return c}return o}function _A(e){const t=new Set,n=new Set;for(const r of e.records){const o=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof o!="string"||o.length<1||o.length>128||(t.add(o),r.journalGeneration===e.journalGeneration&&Bo(r.journalSeq)&&n.add(o))}return{carried:t,admitted:n}}function ul(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function Ou(e,t){const n=new Set;for(const a of t)typeof a=="string"&&a.length>0&&a.length<=128&&n.add(a);if(n.size===0)return e;let r=!1;const o=e.records.map(a=>{const c=a.sourceEntryId??(a.kind==="tool"||a.kind==="supplement"?null:a.id);if(c===null||!n.has(c))return a;const l=ul(a);return l!==a&&(r=!0),l});let s=r?{...e,records:o}:e;return s=gm(s,n),s}function gm(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=_A(e),o=e.orderRevision??0,s=e.journalBodyOwed;let a=null;const c=e.journalSourceVoid;let l=null;for(const d of t)typeof d!="string"||d.length<1||d.length>128||!n.has(d)||r.has(d)||(a||(a=new Map(s??[])),a.set(d,o),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return a?{...e,journalBodyOwed:a,...l?{journalSourceVoid:l}:{}}:e}function ni(e,t,n){const r=n&&e.journalSourceUnavailable===!0?{...e,journalSourceUnavailable:void 0}:e;if(t.length===0)return r;const o=r.journalBodyOwed;let s=null;const a=r.journalSourceVoid;let c=null;for(const l of t)o?.has(l)&&(s||(s=new Map(o)),s.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!s&&!c?r:{...r,...s?{journalBodyOwed:s}:{},...c?{journalSourceVoid:c}:{}}}function qo(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function _m(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function bA(e,t,n){let r=Lr(e,t,t.entries.map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),!0,n);for(const s of t.entries)r=Vc(r,{...s.payload,id:s.id});const o=qo(r,!1);return dl(o.journalPeerSource===void 0&&!o.journalBodyOwed&&!o.journalSourceVoid&&o.journalSourceUnavailable===void 0?o:{...o,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function Pu(e,t,n){let r=Lr(e,t,(t.entries??[]).map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=qo(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const s=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];s.length>0&&(r=gm(r,s));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=ni(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=_m(r,t),dl(r)}function vA(e,t,n,r){let o=Lr(e,t,[],!1,n,{peer:!0});o=qo(o,!0);const s=o.journalBodyOwed,a=m=>r!==void 0&&(s?.get(m)??Number.NEGATIVE_INFINITY)>r,c=t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===o.journalGeneration,l=c?[...t.entries??[],...t.dependency_entries??[]]:[],d=[];let u=o.records,f=o.index;if(l.length>0){const m=new Map;for(const y of l){if(typeof y.id!="string"||y.id===""||a(y.id))continue;const b=`tool:${String(y.payload?.tool_call_id??"")}`,v=f.get(y.id)??f.get(b),p=v===void 0?void 0:u[v];if(!p)continue;let A=hm(y,p);A&&(A={...A,sourceEntryId:y.id,...p.sourcePrecedes?{sourcePrecedes:p.sourcePrecedes}:{}},Bo(y.journal_seq)?(A=mm(A,y.id,t.journal_generation,y.journal_seq),d.push(y.id)):A=ul(A),m.set(p.id,A))}m.size>0&&(u=u.map(y=>m.get(y.id)??y),f=It(u))}let h=u===o.records?o:{...o,records:u,index:f};if(c){h=ni(h,d,!1);const m=(t.source_missing_ids??[]).filter(y=>typeof y=="string"&&y.length>0&&y.length<=128&&!a(y));if(m.length>0){h=ni(h,m,!1);const y=new Set(h.journalSourceVoid??[]);for(const b of m)y.add(b);h={...h,journalSourceVoid:y}}}return h=_m(h,t),dl(h)}function bs(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function vo(e,t,n={}){let r=e;const o=r,s=[];let a=e.profileHistoryPending;const c=T=>qo(ni(T.profileHistoryPending===a?T:{...T,profileHistoryPending:a},s,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Lr(r,t,t.entries.map(T=>({id:T.id,journal_seq:T.journal_seq,role:T.payload?.role,tool_call_id:T.payload?.tool_call_id})),n.authoritative===!0,n.orderRead,{peer:n.peerSource===!0}),t.journal_generation&&t.journal_generation!==r.journalGeneration)return c(r);const l=n.peerSource===!0&&typeof t.journal_generation=="string"&&t.journal_generation.length>0&&t.journal_generation===r.journalGeneration;for(const T of t.entries)r=Vc(r,{...T.payload,id:T.id});const d=n.keepPaging===!0&&r.viewEpoch>0,u=n.pagedBefore!==void 0&&r.index.has(n.pagedBefore)?n.pagedBefore:r.records[0]?.id,f=YS(t.entries,r.records,d||o.journalGeneration!==r.journalGeneration?[]:r.profileHistoryPending);a=!d&&f.pending.length?f.pending:void 0;const h=[];for(const T of f.entries){if(d&&!DA(T,r.clearedAt))continue;const V=r.records[r.index.get(T.id)??-1]??r.records[r.index.get(`tool:${String(T.payload?.tool_call_id??"")}`)??-1]??gA(r,T);let Z=hm(T,V);if(JS(T,V)&&V&&(Z=V),Z&&(r.journalMode||Z.kind==="tool"&&rl(Z.toolName,Z.details))&&(Z={...Z,sourceEntryId:T.id}),Z&&r.journalMode){const ge=V?.sourcePrecedes??(n.pagedBefore!==void 0&&!V?u:void 0);ge!==void 0&&Z.sourcePrecedes!==ge&&(Z={...Z,sourcePrecedes:ge})}Z&&l&&Bo(T.journal_seq)?(Z=mm(Z,T.id,t.journal_generation,T.journal_seq),s.push(T.id)):Z&&n.peerSource===!0&&(Z=ul(Z)),!(Z&&V&&fA(V,n.readWitness))&&Z&&h.push(Z)}let m=r.argsByCall,y=!1;for(const T of t.entries){const V=T.payload?.tool_calls;if(!Array.isArray(V))continue;const Z=Math.round((T.ts??0)*1e3);for(const ge of V)!ge||typeof ge.id!="string"||m.has(ge.id)||(y||(m=new Map(m),y=!0),m.set(ge.id,{...ge,anchoredAt:Z,anchorId:T.id}))}for(let T=0;T<h.length;T++){const V=h[T];if(V.kind!=="tool")continue;const Z=m.get(V.toolCallId);if(!Z)continue;const ge=Z.arguments??null;h[T]={...V,args:ge,intent:typeof ge?.i=="string"?ge.i:null}}const b=y?r.records.map(T=>{if(T.kind!=="tool"||T.args)return T;const Z=m.get(T.toolCallId)?.arguments??null;return Z?{...T,args:Z,intent:T.intent??(typeof Z.i=="string"?Z.i:null)}:T}):r.records,v=new Set(t.entries.map(T=>T.id)),p=n.peerSource===!0&&n.replace===!0?r.records.filter(T=>T.kind==="user"&&(T.provisional===!0||T.local===!0)&&!v.has(T.id)):[],A=n.replace?p.length>0?{...Lt,records:p,index:It(p)}:Lt:{...r,records:b},k=new Map(A.records.map(T=>[T.id,T]));let C=r!==o||n.replace||!n.replace&&b!==r.records;for(const T of h){const V=k.get(T.id);if(!V){C=!0,k.set(T.id,T);continue}if(V.kind==="tool"&&T.kind==="tool"){const Z={...T,args:T.args??V.args,intent:T.intent??V.intent,images:tm(T.images,V.images,"current")};ec(V,Z)||(C=!0,k.set(T.id,Z));continue}ec(V,T)||(C=!0,k.set(T.id,T))}const L=r.compacting&&t.entries.some(T=>r.index.has(T.id)||Math.round((T.ts??0)*1e3)<r.compactingSince?!1:T.type==="compaction"||T.type==="message"&&T.payload?.custom_type==="compaction_refused"),O=t.entries[0],I=O?Math.round((O.ts??0)*1e3):0,g=r.journalMode?_n:NE(A.records,I,n.statedByOwner!==!1);let w=A.oldestId,S=A.oldestTs,x=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(O&&(w=O.id,S=I),x=t.has_more):n.pagedBefore!==void 0?O?(w=O.id,S=I,x=t.has_more):x=!1:O&&(r.journalMode?(r.journalPositions?.get(O.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):I>0&&I<r.oldestTs)&&(w=O.id,S=I,x=t.has_more));const F=w!==r.oldestId||S!==r.oldestTs;if(!C&&!F&&r.hasMore===x&&!L&&g.size===0)return c(r);const j=g.size===0?[...k.values()]:[...k.values()].map(T=>g.has(T.id)?DE(T):T),X=sm(Uo(j,n.statedByOwner===!1?_n:new Set(h.map(T=>T.id)),r));return n.keepPaging?c({...r,records:X,index:It(X),argsByCall:m}):c({...r,records:X,index:It(X),oldestId:w,oldestTs:S,hasMore:x,argsByCall:m,compacting:L?!1:r.compacting,compactingSince:L?0:r.compactingSince})}const yA=/^(?:local|notice|retry|subagent|compaction):/;function fl(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!yA.test(e.id)}}function wA(e,t,n=_n){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(o=>!(o.ts<t.ts&&fl(o)&&!n.has(o.id)));return r.length===e.records.length?e:{...e,records:r,index:It(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const on={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function oa(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function tc(e,t,n=Date.now(),r={}){let o=e;const s=t.message;if(t.type==="journal_order_ready"){const l=typeof t.journal_generation=="string"?t.journal_generation:void 0;if(o={...o,orderNeedsReconcile:!0,orderWantedGeneration:t.reconcile===!0?void 0:l,orderDemand:t.reconcile===!0?{}:{generation:l}},t.reconcile===!0)return o;const d=Lr(o,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=Uo(d.records,_n,d);return d===o&&u===o.records?o:{...d,records:u,index:It(u)}}s&&(o=Vc(o,s));const a=r.frame,c=r.queuedAskEngine;switch(t.type){case"agent_start":{const l=Number(t.generation??o.generation+1);return l===o.generation?o:{...o,generation:l,compacting:!1,compactingSince:0}}case"compaction_start":return o.compacting?o:{...o,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??o.generation)<o.generation)return o;let d=o;for(const u of o.records)if(u.kind==="assistant"&&u.streaming&&(d=Ne(d,{...u,streaming:!1,settledAt:n,callsTools:!1,stopReason:t.aborted?"aborted":u.stopReason})),u.kind==="tool"&&u.phase!=="done"){const f=u.phase==="composing"||u.phase==="queued";d=Ne(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=oa(s);if(s===void 0||l===null)return on.idlessFrameRefused+=1,o;const d=o.records[o.index.get(l)??-1];if(s.role==="user"){const u=lm(s.provider_payload);if(u){const b=Yt(s),v=Va({...u,text:b});if(v.body.trim()){const p=d?.kind==="user"&&d.provisional===!0;return Ne(o,{kind:"custom",id:l,ts:p?ri(o,n):n,customType:"hub_message",text:v.envelope,attribution:"user",...Ps("hub_message",v.envelope||v.body,{...u}),receipt:v,images:Jn(s,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(um(s.provider_payload))return o;const f=Yt(s);if(Fh(f))return o;const h=d?.kind==="user"&&d.provisional===!0,m=em(s,l,d?.kind==="user"?d.documents:void 0),y=vi(f);return Ne(o,{kind:"user",id:l,ts:h?ri(o,n):n,text:f,images:Jn(s,l,d?.kind==="user"?d.images:void 0),...m.length?{documents:m}:{},...h?{provisional:!0}:{},...y?{skill:y}:{}})}return s.role!=="assistant"||d?o:Ne(o,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=oa(s);if(s===void 0||l===null)return on.idlessFrameRefused+=1,o;const d=o.index.get(l),u=String(t.delta??""),f=Yt(s);if(d===void 0)return!f&&!u?o:Ne(o,{kind:"assistant",id:l,ts:n,text:f?f+u:u,streaming:!0,truncated:f===""?"prefix":void 0,...a?{frame:a}:{},stopReason:null,error:!1});const h=o.records[d];if(h.kind!=="assistant")return o;if(!h.streaming)return on.settledAssistantUpdate+=1,o;if(r.seed!==!0&&a&&h.frame&&a.epoch===h.frame.epoch&&a.seq<=h.frame.seq)return on.staleUpdateFrameDropped+=1,o;const m=$E(h.frame,a);if(r.seed===!0&&!f)return!h.text&&!u?o:(on.seededDeltaWithheld+=h.text?1:0,Ne(o,{...h,text:h.text||u,...m?{frame:m}:{},truncated:h.text?"interrupted":"prefix"}));let y;if(f){if(y=f+u,y.length<=h.text.length)return o}else{if(!u)return o;y=h.text+u}return Ne(o,{...h,text:y,...m?{frame:m}:{},truncated:f?void 0:h.truncated})}case"message_end":{const l=oa(s);if(s===void 0)return on.idlessFrameRefused+=1,o;if(l===null){if(s.role!=="assistant")return on.idlessFrameRefused+=1,o;let y;for(const p of o.records)if(!(p.kind!=="assistant"||!p.streaming)){if(y!==void 0)return on.idlessFrameRefused+=1,o;y=p}if(y===void 0)return on.idlessFrameRefused+=1,o;const b=Array.isArray(s.tool_calls)?s.tool_calls:[],v={...y,streaming:!1,settledAt:y.settledAt??n,callsTools:b.length>0,...y.text||b.length===0?{complete:!0}:{}};return Ne(o,v)}if(s.role!=="assistant")return o;const d=o.index.get(l),u=Yt(s),f=d===void 0?void 0:o.records[d],h=Array.isArray(s.tool_calls)?s.tool_calls:[],m={kind:"assistant",id:l,ts:d===void 0?n:o.records[d].ts,text:u,...u||h.length===0?{complete:!0}:{},streaming:!1,callsTools:h.length>0,settledAt:f?.kind==="assistant"&&f.settledAt!==void 0?f.settledAt:n,stopReason:s.stop_reason??null,error:!!s.is_error,...a?{frame:a}:{}};return Ne(o,m)}case"history_delta":{const d=(Array.isArray(t.messages)?t.messages:[]).filter(k=>String(k.id??"")!==""),u=typeof t.journal_generation=="string"&&t.journal_generation.length>0?t.journal_generation:void 0,f=t.journal_ordinals&&typeof t.journal_ordinals=="object"&&!Array.isArray(t.journal_ordinals)?t.journal_ordinals:void 0,h=t.entry_times&&typeof t.entry_times=="object"&&!Array.isArray(t.entry_times)?t.entry_times:void 0,m="journal_generation"in t||"journal_ordinals"in t||"entry_times"in t,y=o.journalPeerSource===!0||m,b=y&&u!==void 0&&u===o.journalGeneration,v=d.map(k=>String(k.id??"")).filter(k=>k.length>0&&k.length<=128),p={entries:d.map(k=>{const C=String(k.id??""),L=f?.[C],O=h?.[C];return{id:C,ts:b&&typeof O=="number"&&Number.isFinite(O)?O:n/1e3,type:"message",payload:{kind:k.custom_type?"custom":"message",...k},...b&&Bo(L)?{journal_seq:L}:{}}}),has_more:o.hasMore,...b?{journal_generation:u}:{}};let A=vo(o,p,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:y});if(y&&v.length>0)if(b){const k=v.filter(C=>!Bo(f?.[C]));k.length>0&&(A=Ou(A,k))}else A=Ou(A,v),u!==void 0&&(A=Lr(A,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),A=qo(A,!0));return A}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return o;const d=String(t.supersedes_tool_call_id??""),u=`tool:${l}`,f=o.records[o.index.get(u)??-1],h=d?o.records[o.index.get(`tool:${d}`)??-1]:void 0,m=f?.kind==="tool"?f:h?.kind==="tool"?h:void 0;if(m&&m.phase!=="composing"&&m.phase!=="queued")return d&&f?.kind==="tool"?ra(o,d):o;const b=String(t.not_run_reason??"").trim()||null,v=String(t.not_run_kind??"").trim()||null;if(Cu(t.tool_name,c)&&!b&&!m)return d?ra(o,d):o;const p=Number(t.argument_bytes??0),A={kind:"tool",id:u,ts:m?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:b?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:p>0?p:m?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:_o,added:0,removed:0,diff:null,diffTruncatedRows:0,stopped:!1,notRunReason:b,notRunKind:b?v:null,neverSent:b!==null};return d&&h?.kind==="tool"&&f?.kind!=="tool"?FE(o,d,A):Ne(d&&f?.kind==="tool"?ra(o,d):o,A)}case"tool_execution_start":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1];if(u&&u.kind==="tool"&&u.phase==="done"&&!u.notRunReason)return o;const f=Ru(o,l,t,u),h=f&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:f,anchoredAt:Mr(t)??n}):o.argsByCall,m=h===o.argsByCall?o:{...o,argsByCall:h};return Cu(t.tool_name,c)&&!u?m:Ne(m,{kind:"tool",id:d,ts:u?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??(typeof f?.i=="string"?f.i:null),args:f,phase:"running",notRunReason:null,notRunKind:null,neverSent:!1,argumentBytes:0,output:null,isError:!1,durationS:null,startedAt:Mr(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:_o,added:0,removed:0,diff:u?.kind==="tool"?u.diff:null,diffTruncatedRows:u?.kind==="tool"?u.diffTruncatedRows??0:0,details:u?.kind==="tool"?u.details??null:null,stopped:!1})}case"tool_execution_update":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1];if(!u||u.kind!=="tool")return o;const f=t.partial_result??{},h=xh(f.details,u.details);return h===(u.details??null)?o:Ne(o,{...u,details:h})}case"tool_execution_end":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1],f=t.result??{};if(pm(f.details))return ym(o,d);const h=Ru(o,l,t,u),m=u&&u.kind==="tool"?u:{kind:"tool",id:d,ts:n,toolCallId:l,toolName:String(t.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:_o,added:0,removed:0,diff:null,diffTruncatedRows:0,stopped:!1},y=h&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:h,anchoredAt:Mr(t)??n}):o.argsByCall,b=y===o.argsByCall?o:{...o,argsByCall:y},v=r.userStoppedAt??null,p=!!(t.is_error??f.is_error),A=Qh(f.details?.__fault),k=v!==null&&(typeof m.startedAt=="number"?m.startedAt<=v:p);return Ne(b,{...m,args:h,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:Yt(f)||null,isError:k||A?!1:p,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof m.startedAt=="number"?m.startedAt+t.duration_s*1e3:null,startedAt:null,images:jE(Jn(f,d,m.images),m.images),...Nh(f.details,m),diff:$h(jh(f.details),m.diff),diffTruncatedRows:Dh(f.details,m.diffTruncatedRows??0),stopped:m.stopped||k||A,delivery:Rh(f.details,m.delivery,m.toolName),bridge:kh(m.toolName,f.details,m.bridge),bridgeLabel:Sh(m.toolName,f.details,m.bridgeLabel),details:Lh(m.toolName,f.details,m.details)})}case"supplement_progress":{const l=IE(t);if(!l)return o;const d=sl(l.anchor),u=o.records[o.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,h=Jh(f,l,n);return h?Ne(o,h):o}case"notice":{const l=String(t.text??"");if(!l)return o;const d=`notice:${o.generation}:${l}`;return o.index.has(d)?o:Ne(o,{kind:"notice",id:d,ts:n,text:l,level:t.kind??"info"})}case"compaction_end":{const l=Number(t.tokens_before??0),d=Number(t.tokens_after??0),f=!!t.success?null:rm(String(t.detail??"")),h=f?f.text:l&&d?BE(l,d):om,m=`compaction:${o.generation}:${l}:${d}`,y=o.compacting?{...o,compacting:!1,compactingSince:0}:o;return y.index.has(m)?y:f?Ne(y,{kind:"notice",id:m,ts:n,text:h,copy:f.copy,level:f.level}):WE(Ne(y,{kind:"compaction",id:m,ts:n,text:h,before:l}))}case"retry_start":{const l=`Retrying after an error (attempt ${String(t.attempt??"?")})${t.fallback_model?`, falling back to ${String(t.fallback_model)}`:""}`,d=`retry:${o.generation}:${String(t.attempt??"")}`;return o.index.has(d)?o:Ne(o,{kind:"notice",id:d,ts:n,text:l,level:"warning"})}case"subagent_end":{const l=`subagent:${String(t.job_id??"")}`,d=String(t.status??""),u=`${String(t.label??"Subagent")} ${d||"finished"}`,f=o.records[o.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?o:Ne(o,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return o}}function Mr(e){return ow(e.started_at_epoch)}function pl(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function kA(e){const t=pl(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function SA(e,t){const n=Mr(e);if(n!==null)return n;const r=pl(e);if(!r)return null;const o=t.argsByCall.get(r)?.anchoredAt;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}function EA(e,t){if(Mr(e)!==null)return!1;const n=pl(e);if(!n)return!1;const r=t.argsByCall.get(n)?.anchorId;if(typeof r!="string")return!1;const o=t.index.get(r);return o!==void 0&&o<=nm(t.records)}function hl(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 ki(e){return e.type==="tool_execution_end"}function AA(e,t,n=Date.now(),r=null){let o=e;t.streaming&&t.generation>o.generation&&(o={...o,generation:t.generation}),o.compacting&&(o={...o,compacting:!1,compactingSince:0});const s=t.streaming===!0,a=fm(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let h=n;const m=kA(f);if(m!==null&&!o.index.has(m)){const y=SA(f,o);if(y!==null)h=y,c=!0,EA(f,o)&&l.add(m);else if(ki(f)||hl(f)||!s)continue}o=tc(o,f,h,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return o;const d=Uo(o.records,l,o);return{...o,records:d,index:It(d)}}function Mu(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!ki(r)&&!hl(r))continue;const o=String(r.tool_call_id??"");if(!o)continue;const s=Mr(r);s!==null&&t.set(o,s)}return t}function IA(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n;if(r.type!=="tool_call_compose")continue;const o=r.not_run_reason;if(typeof o=="string"&&o.trim().length>0)continue;const s=String(r.tool_call_id??"");s&&t.add(s)}return t}const RA=5e3;function xA(e,t){const n=new Set(t),r=new Map;if(n.size===0)return r;for(const o of e){if(o.payload?.role!=="tool")continue;const s=o.payload.tool_call_id;if(typeof s!="string"||!n.has(s))continue;const a=o.ts;typeof a!="number"||!Number.isFinite(a)||r.set(s,Math.round(a*1e3))}return r}function TA(e,t,n,r=new Map,o=new Set){const s=e[0]?.ts;if(typeof s!="number"||!Number.isFinite(s))return!1;let a=null;for(const l of t){const d=n.get(l);if(d===void 0){if(o.has(l))continue;return!1}(a===null||d<a)&&(a=d)}for(const l of r.values())(a===null||l<a)&&(a=l);return a===null?!1:Math.round(s*1e3)<=a-RA}function ju(e,t){const n=[];for(const r of e??[]){if(!r)continue;const o=r;if(!ki(o)&&!hl(o))continue;const s=String(o.tool_call_id??"");!s||n.includes(s)||t.has(s)||n.push(s)}return n}function $u(e,t,n,r){const o=[],s=new Set;for(const a of t)s.has(a)||(s.add(a),!n.has(a)&&((e.get(a)??0)>=r||o.push(a)));return o}const CA=3.25,nc=100,ml=500;function Nu(e){return e<=0?nc:Math.min(ml,nc+Math.ceil(CA*e))}function sa(e,t){const n=[];if(t.size===0)return n;for(const r of e){const o=r.payload?.tool_calls;if(Array.isArray(o))for(const s of o)s&&typeof s.id=="string"&&t.has(s.id)&&n.push(s.id)}return n}function OA(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function PA(e,t){const n=new Set(t);for(const s of e){const a=s.payload?.tool_calls;if(Array.isArray(a))for(const c of a)c&&typeof c.id=="string"&&n.add(c.id)}const r=[],o=new Set;for(const s of e){if(s.payload?.role!=="tool")continue;const a=s.payload.tool_call_id;typeof a!="string"||n.has(a)||o.has(a)||(o.add(a),r.push(a))}return r}function MA(e,t){return e&&t===0}function jA(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,o=r.not_run_reason,s=r.type==="tool_call_compose"&&typeof o=="string"&&o.trim().length>0;if(r.type!=="tool_execution_start"&&!ki(r)&&!s)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function bm(e,t,n){const r=new Set(e),o=[];for(const s of t)!r.has(s)&&!n.has(s)&&o.push(s);for(const s of e){if(n.has(s))return o;t.has(s)&&o.push(s)}return o}function $A(e,t,n){return bm(e,t,n).length}function Du(e){let t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;for(const n of e.records)n.kind!=="assistant"||!n.streaming||n.truncated||(t=Ne(t,{...n,truncated:"interrupted"}));return t}function NA(e,t=Date.now()){return e.records.length===0&&!e.profileHistoryPending?.length?e:{...Lt,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function DA(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 Lu(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function LA(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return ll(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function ri(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function vm(e,t,n,r,o=Date.now(),s=qa){if(e.index.has(t))return e;const a=vi(n);return Ne(e,{kind:"user",id:t,ts:ri(e,o),text:n,images:r,...s.length?{documents:s}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function ym(e,t){return ll(e,n=>n.id===t)}let Fu=0;function FA(e,t,n,r=Date.now()){return Fu+=1,Ne(e,{kind:"notice",id:`local:${r}:${Fu}`,ts:ri(e,r),text:t,level:n})}function wj(e,t,n,r){const o=t?.anchor_id,s=t?.kind;if(!o||s!=="error"&&s!=="interrupted"&&s!=="closed"&&s!=="retired"||n||e.index.has(o)||!t?.unseen&&!r?.has(o))return e;r?.add(o);const a=s==="error"?{id:"stopped_with_error"}:s==="interrupted"?{id:"interrupted"}:void 0;return Ne(e,{kind:"notice",id:o,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:s==="closed"?im:s==="retired"?am:wi(a),...a?{copy:a}:{},level:s==="closed"?"info":s==="retired"?"warning":s==="error"?"error":"warning"})}const UA="compacting context…";function kj(e){return typeof e=="string"&&e.trim()===UA}const BA=[1500,5e3];async function Sj(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of BA){await t(n);try{if(await e())return}catch{}}}function HA(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 WA=["store","routed","request","snapshot","content","painted","sendable"],GA=6e4,zA="[open-trace]",KA=/^[A-Za-z0-9_-]{1,80}$/,VA=["sidebar","open","native"];function ZA(e,t,n){const r=KA.test(e.sessionId)?e.sessionId:"?",o=VA.includes(e.entrance)?e.entrance:"open",s=u=>u===void 0?"-":String(Math.max(0,Math.round(u-e.start))),{painted:a,sendable:c}=e.stages,l=a!==void 0&&c!==void 0?Math.max(a,c):void 0,d=[zA,`t=${e.token}`,`clickEpochMs=${e.clickEpochMs??"-"}`,`session=${r}`,`via=${o}`,`outcome=${t}`,...WA.map(u=>`${u}=${s(e.stages[u])}`),`settled=${s(l)}`];return n!==void 0&&d.push(`by=t${n}`),d.join(" ")}function YA(e){let t=0,n=null;const r=(s,a)=>{const c=n;if(c){n=null,e.clearTimer(c.timer);for(const l of Object.keys(c.fallbacks))c.stages[l]===void 0&&(c.stages[l]=c.fallbacks[l]);e.log(ZA(c,s,a));for(const l of c.endListeners.splice(0))l()}},o=(s,a)=>{s.stages[a]===void 0&&(s.stages[a]=e.now(),s.stages.painted!==void 0&&s.stages.sendable!==void 0&&r("settled"))};return{begin(s,a){t+=1;const c=t;n&&r("superseded",c);const l={token:c,sessionId:s,entrance:a,start:e.now(),clickEpochMs:performance.timeOrigin+performance.now(),stages:{},fallbacks:{},timer:void 0,frameRequested:!1,endListeners:[]};return l.timer=e.setTimer(()=>{n===l&&r("timeout")},GA),n=l,c},note(s,a,c,l){const d=n;if(!(!d||!s||d.sessionId!==s)&&!(c!==void 0&&c!==d.token)){if(l?.fallback===!0){d.stages[a]===void 0&&d.fallbacks[a]===void 0&&(d.fallbacks[a]=e.now());return}if(a==="content"&&!d.frameRequested){d.frameRequested=!0,o(d,"content"),e.nextFrame(()=>{n===d&&o(d,"painted")});return}a==="painted"||a==="content"||o(d,a)}},fail(s,a){!n||!s||n.sessionId!==s||r(a)},activeSessionId(){return n?.sessionId??null},currentToken(){return n?.token??null},onEnd(s,a){n?.token===s?n.endListeners.push(a):a()}}}const JA=typeof window<"u";function QA(e,t,n){t(()=>n(e))}const XA=e=>{const t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)},ia=YA({now:()=>performance.now(),nextFrame:e=>{JA&&typeof requestAnimationFrame=="function"&&typeof MessageChannel=="function"?QA(e,t=>requestAnimationFrame(()=>t()),XA):setTimeout(e,0)},log:e=>console.warn(e),setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e)});function Ej(e,t,n,r){let o=!1;const s=()=>{const c=e.activeSessionId();if(c===null||e.currentToken()!==t)return;const l=n();if(l.activeSessionId!==c||l.activeDraftKey){o&&e.fail(c,"left");return}o=!0,e.note(c,"store"),l.validatingSessionId!==c&&e.note(c,"sendable")},a=r(s);e.onEnd(t,a),s()}const Uu=new Set(["openrouter","radient","radient-key"]),qA=new Set(["auto","openrouter/auto"]),eI=()=>_("ui.chat.session_readout.model.router_auto");function wm(e){return e.slice(e.lastIndexOf("/")+1)||e}function tI(e,t){return e===t||e===wm(t)}function rc(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 nI(e,t){return t?rc(e?.selected_model)===t||rc(e?.effective_model)===t:!1}function Aj(e){if(!e||typeof e.model_id!="string"||!e.model_id)return null;const t=typeof e.provider=="string"?e.provider:"",n=t?`${t}/${e.model_id}`:e.model_id,r=typeof e.display_name=="string"?e.display_name.trim():"",o=Uu.has(t)||!r||tI(r,e.model_id)||r.toLowerCase()==="unknown";return{name:Uu.has(t)&&qA.has(e.model_id)?eI():o?wm(n):r,selector:n}}function Ij(e,t,n=null){const r=e?.effective_model??e?.selected_model??null,o=n&&r?{...r,reasoning_effort:n}:r;return{identity:t??r,effort:o}}function Rj(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function xj(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function Tj(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 Cj(e){const t=e?.effort_displacement,n=t?.note;if(typeof n!="string"||!n.trim())return null;const r=new Map;for(const a of[e?.effective_model,e?.selected_model]){const c=typeof a?.display_name=="string"?a.display_name.trim():"";if(!a||!c||!a.provider||!a.model_id)continue;const l=`${a.provider}/${a.model_id}`;l!==t?.serving&&l!==t?.selected||r.set(l,c)}if(!r.size)return n.trim();const o=[...r.keys()].sort((a,c)=>c.length-a.length).map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),s=new RegExp(`(^|[\\s(])(${o.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(s,(a,c,l)=>`${c}${r.get(l)}`)}function Oj(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function rI(e){const t=e.trim();return t&&(km(t)??t)}const Bu=new Map;function km(e){const t=nn();let n=Bu.get(t);return n===void 0&&(n={auto:_("ui.chat.session_readout.effort.level.auto"),none:_("ui.chat.session_readout.effort.level.none"),minimal:_("ui.chat.session_readout.effort.level.minimal"),low:_("ui.chat.session_status.effort_level.low"),medium:_("ui.chat.session_status.effort_level.medium"),high:_("ui.chat.session_status.effort_level.high"),xhigh:_("ui.chat.session_readout.effort.level.xhigh"),max:_("ui.chat.session_readout.effort.level.max"),unknown:_("ui.chat.session_readout.effort.level.unknown"),reasoning:_("ui.chat.session_readout.effort.level.reasoning")},Bu.set(t,n)),n[e.toLowerCase()]}const uo=e=>rI(e).toLowerCase(),vs=e=>{const t=km(e.trim());return t===void 0?e:t.toLowerCase()};function Sm(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 Pj(e,t){const n=(e??t)?.effective_model;return Sm(n)?null:n?.model_id??null}function Mj(e){if(!e)return null;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim().toLowerCase():"",n=Array.isArray(e.reasoning_efforts)?e.reasoning_efforts.filter(s=>typeof s=="string"):null,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",o=Sm(e);return t?{label:t,adjustable:n===null||n.length>0,knownLadder:!!(n&&n.length>0),levelKnown:!0,detail:n&&n.length>0?_("ui.chat.session_readout.effort.detail.offers",{levels:Ts(n.map(uo))}):_("ui.chat.session_readout.effort.detail.session")}:n&&n.length>0?{label:"auto",adjustable:!0,knownLadder:!0,levelKnown:!0,detail:r?_("ui.chat.session_readout.effort.detail.auto_with_default",{default:uo(r),levels:Ts(n.map(uo))}):_("ui.chat.session_readout.effort.detail.auto",{levels:Ts(n.map(uo))})}:o?{label:"unknown",adjustable:!0,knownLadder:!1,levelKnown:!1,detail:_("ui.chat.session_readout.effort.detail.not_reported",{command:"/effort <level>"})}:n&&e.reasoning?{label:"reasoning",adjustable:!1,knownLadder:!0,levelKnown:!0,detail:_("ui.chat.session_readout.effort.detail.no_levels")}:n===null&&r?{label:r,adjustable:!1,knownLadder:!1,levelKnown:!0,detail:_("ui.chat.session_readout.effort.detail.default_only")}:null}function jj(e,t){if(!e)return null;if(!t||t.length===0||e.knownLadder)return e;const n=t.map(r=>typeof r=="object"&&r!==null&&"value"in r?String(r.value):"").filter(Boolean);return n.length===0?e:{...e,adjustable:!0,detail:_("ui.chat.session_readout.effort.detail.offers",{levels:Ts(n.map(uo))})}}function oI(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=eo(n.provider);if(!a)return null;const c=eo(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:eo(n.label)||a,effectiveState:d,owner:eo(n.owner_label)||eo(n.owner_device)||_("ui.chat.session_readout.access.owner_fallback"),observedAt:aa(n.observed_at),lastGrantAt:aa(n.last_grant_at),lastGrantExpiresAt:aa(n.last_grant_expires_at)}}if(!n||n.state!=="signed_out"&&n.state!=="temporarily_unavailable")return null;const r=typeof n.provider=="string"?n.provider:"";if(!r)return null;const o=e?.effective_model?.provider;if(o&&o!==r)return null;const s=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:s,state:n.state}:{provider:r,label:s}}function $j(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function Nj(e){return e&&e.draft!==!0?oI(e.frontend,e.servingLocality):null}function eo(e){return typeof e=="string"?e.trim():""}function aa(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function ca(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function Dj(e){const{label:t,effectiveState:n}=e,r=e.owner||_("ui.chat.session_readout.access.owner_fallback"),o={local:[_("ui.chat.session_readout.access.local.title",{label:t}),_("ui.chat.session_readout.access.local.description")],pending:[_("ui.chat.session_readout.access.pending.title",{label:t}),_("ui.chat.session_readout.access.pending.description")],eligible_borrow_unverified:[_("ui.chat.session_readout.access.eligible_borrow_unverified.title",{owner:r}),_("ui.chat.session_readout.access.eligible_borrow_unverified.description",{label:t,owner:r})],effective_borrow:[_("ui.chat.session_readout.access.effective_borrow.title",{label:t,owner:r}),_("ui.chat.session_readout.access.effective_borrow.description")],expired:[_("ui.chat.session_readout.access.expired.title",{label:t}),_("ui.chat.session_readout.access.expired.description",{owner:r})],withdrawn:[_("ui.chat.session_readout.access.withdrawn.title",{label:t}),_("ui.chat.session_readout.access.withdrawn.description")],owner_unavailable:[_("ui.chat.session_readout.access.owner_unavailable.title",{owner:r}),_("ui.chat.session_readout.access.owner_unavailable.description",{label:t,owner:r})],device_bound:[_("ui.chat.session_readout.access.device_bound.title",{label:t}),_("ui.chat.session_readout.access.device_bound.description")],absent:[_("ui.chat.session_readout.access.absent.title",{label:t}),e.connectHere===!0?_("ui.chat.session_readout.access.absent.description_connect"):_("ui.chat.session_readout.access.absent.description_remote")]},s=e.state==="temporarily_unavailable",[a,c]=n?o[n]:[s?_("ui.chat.session_status.temporarily_unavailable",{label:t}):_("ui.chat.session_status.not_signed_in",{label:t}),s?_("ui.chat.session_status.temporarily_unavailable_description"):_("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];n&&e.observedAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.last_checked",{time:ca(e.observedAt)})),n&&e.lastGrantAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.last_resolved",{time:ca(e.lastGrantAt)})),n&&e.lastGrantExpiresAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.grant_expiry",{time:ca(e.lastGrantExpiresAt)}));const d=[...l];return n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push(_("ui.chat.session_readout.access.history.only")),{title:a,description:c,history:l.join(" "),historyLines:d,tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!s,canSwitchModel:n!=="effective_borrow"}}function Lj(e){switch(e?.effectiveState){case"effective_borrow":case"pending":case"eligible_borrow_unverified":return!0;default:return!1}}function Fj(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="not-cleared"||e.kind==="settled"&&e.canRetry}function Uj(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function Bj(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function sI(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function iI(e,t){return!!e.streams[t]}function Em(e,t){return e.attached[t]?.turns.at(-1)}function Hj(e,t){const n=Em(e,t);return n?e.streams[n.asideId]:void 0}function Wj(e,t){const n=e.attached[t]?.turns??[];for(let r=n.length-1;r>=0;r-=1){const o=n[r];if(o&&e.streams[o.asideId]?.settled)return o.asideId}}function aI(){return{text:"",streaming:!0,settled:!1,error:null}}function cI(e){return{text:e,streaming:!1,settled:!0,error:null}}function lI(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const dI=Qo(e=>({streams:{},attached:{},attachAside:t=>e(n=>{const r=n.attached[t];return r&&r.notice===null?n:{attached:{...n.attached,[t]:r?{...r,notice:null}:{turns:[],notice:null}}}}),beginAsk:(t,n,r)=>e(o=>({streams:{...o.streams,[n]:aI()},attached:{...o.attached,[t]:{turns:[...o.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const o=sI(r.streams[t],n);return o?{streams:{...r.streams,[t]:o}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:cI(n)}}:r),failAside:(t,n)=>e(r=>iI(r,t)?{streams:{...r.streams,[t]:lI(r.streams[t],n)}}:r),setAsideNotice:(t,n)=>e(r=>{const o=r.attached[t];return o?{attached:{...r.attached,[t]:{...o,notice:n}}}:r}),queueAdoption:(t,n,r)=>e(o=>{const s=o.attached[t];return s?{attached:{...o.attached,[t]:{...s,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:o}),unqueueAdoption:(t,n,r)=>e(o=>{const s=o.attached[t];if(s?.queued?.asideId!==n)return o;const{queued:a,...c}=s;return{attached:{...o.attached,[t]:{...c,notice:r}}}}),detachAside:t=>e(n=>{const r=n.attached[t],o={...n.attached};if(delete o[t],!r)return{attached:o};const s={...n.streams};for(const a of r.turns)delete s[a.asideId];return{streams:s,attached:o}})}));function Gj(e,t){return Em(e,t)?.asideId}const uI=4*1024*1024,Hu=1024*1024,Jt=new Map;function Wu(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function fI(e){const t=e.slice(-200),n=Wu(t);if(n<=Hu)return{records:t,bytes:n};let r=0,o=t.length,s=0;for(;o-r>1;){const a=Math.floor((r+o)/2),c=Wu(t.slice(a));c>Hu?r=a:(o=a,s=c)}return{records:t.slice(o),bytes:s}}function pI(e,t){const{records:n,bytes:r}=fI(LA(t.transcript).records);if(n.length===0){Jt.delete(e);return}const o={...t.transcript,records:n,index:new Map(n.map((a,c)=>[a.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},s={transcript:o,savedAt:Date.now(),bytes:r,owedLabels:Gu(n,t.owedLabels),markLabels:Gu(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>o.index.has(a)))};Jt.delete(e),Jt.set(e,s),mI()}function Gu(e,t){if(!t||t.size===0)return zu;const n=new Set;for(const r of e)r.kind!=="tool"||r.args||r.toolCallId&&t.has(r.toolCallId)&&n.add(r.toolCallId);return n.size>0?n:zu}const zu=new Set;function Am(e){const t=Jt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function hI(e){Jt.delete(e)}function mI(){let e=0;for(const t of Jt.values())e+=t.bytes;for(;e>uI&&Jt.size>0;){const t=Jt.keys().next().value;if(t===void 0)break;const n=Jt.get(t);Jt.delete(t),e-=n?.bytes??0}}const gI=8,_I=128,Im=new Set,bI="",an=new Map,gl=e=>e??bI;function zj(e){return an.get(gl(e))??Im}function Kj(e,t,n){const r=gl(e),o=an.get(r)??new Set,s=new Set(o);if(n)for(s.delete(t),s.add(t);s.size>_I;){const a=s.values().next().value;if(a===void 0)break;s.delete(a)}else s.delete(t);for(an.delete(r),s.size>0&&an.set(r,s);an.size>gI;){const a=an.keys().next().value;if(a===void 0)break;an.delete(a)}return an.get(r)??Im}function vI(e){an.delete(gl(e))}const yI=128,oi=4096,la=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),Ku=e=>e.startsWith("qg:")&&e.length>3;function Vj(e,t,n=null,r=[]){const o=new Map,s=new Map;for(let c=0;c<e.length;c+=1){const l=e[c];for(let d=0;d<l.segmentIds.length;d+=1){const u=l.segmentIds[d];if(o.has(u))return la("duplicate-prior-id");if(o.size===oi)return la("prior-id-limit");o.set(u,{ordinal:c,order:d})}l.eligible!==!1&&Ku(l.key)&&t.has(l.key)&&s.size<yI&&s.set(c,l.key)}for(const c of r)if(!o.has(c)){if(o.size===oi)return la("prior-id-limit");o.set(c,{ordinal:-1,order:-1})}const a=n===null?void 0:o.get(n);if(a!==void 0&&a.ordinal>=0){const c=e[a.ordinal];c.eligible!==!1&&Ku(c.key)&&s.set(a.ordinal,c.key)}return{complete:!0,owners:o,keys:s,reason:null}}function Zj(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>oi)return r("prior-id-limit");const o=new Set,s=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,h,m)=>{const y=a.get(f);y===void 0?a.set(f,{current:h,many:!1,lastOrder:m,reordered:!1,outside:!1}):(y.current!==h&&(y.many=!0),m<=y.lastOrder&&(y.reordered=!0),y.lastOrder=m)};for(let f=0;f<t.length;f+=1){const h=t[f];let m=null,y=!1;for(const v of h.segmentIds){if(s!==null){if(s.has(v))return r("duplicate-current-id");if(s.size===oi)return r("current-uniqueness-unproved");s.add(v)}const p=e.owners.get(v);if(p!==void 0){if(o.has(v))return r("duplicate-current-id");o.add(v),l(p.ordinal,f,p.order),m===null?m=p.ordinal:m!==p.ordinal&&(y=!0)}}if(h.eligible===!1||y||m===null||m<0)continue;const b=e.keys.get(m);b!==void 0&&c.set(f,{owner:m,key:b})}for(const f of n.outsideCurrentIds??[]){const h=e.owners.get(f);if(h===void 0||o.has(f))continue;const m=a.get(h.ordinal);m!==void 0&&(m.outside=!0)}for(const[f,h]of c){const m=a.get(h.owner),y=h.key.slice(3);(m===void 0||m.many||m.reordered||m.outside||!o.has(y))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const h=c.get(f)?.key??t[f].key;if(d.has(h)){if(u.has(h))return r("key-collision");u.add(h)}}return{episodes:t.map((f,h)=>{const m=c.get(h);return m===void 0?f:{...f,key:m.key}}),reason:null}}const wI=8,kI="",Yn=new Map,_l=e=>e??kI;function Yj(e){return Yn.get(_l(e))??null}function Jj(e,t){const n=_l(e);for(Yn.delete(n),Yn.set(n,t);Yn.size>wI;){const r=Yn.keys().next().value;if(r===void 0)break;Yn.delete(r)}}function SI(e){Yn.delete(_l(e))}function EI(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const o=n.getTranscript().orderRevision??0,s=()=>(n.getTranscript().orderRevision??0)===o;try{let a=r,c=await n.readPage(a);if(!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing){const u=mA(n.getTranscript()),f=u!==null&&u!==a?u:pA(c,a);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(a=f,c=await n.readPage(a),!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing)return{kind:"failed",reason:"cursor-missing"}}let l=n.getTranscript();const d=n.commit(u=>(l=u,(u.orderRevision??0)!==o?u:vo(u,c,{...u.oldestId===r?{pagedBefore:a}:{},...n.peerSource?.()===!0?{peerSource:!0}:{}})));return(d.orderRevision??0)!==o||c.journal_generation!==void 0&&c.journal_generation!==d.journalGeneration?{kind:"stale"}:{kind:"applied",newRecords:Math.max(0,d.records.length-l.records.length),exhausted:!d.hasMore}}catch{return{kind:"failed",reason:"request"}}finally{n.setLoading?.(!1)}};return{busy:n=>e!==null&&e.key===n,load(n,r){if(e!==null&&e.key===n)return e.promise;const o=r.getTranscript();if(!o.hasMore||!o.oldestId)return Promise.resolve({kind:"nothing-to-load"});const s={key:n,promise:t(r,o.oldestId)};e=s;const a=()=>{e===s&&(e=null)};return s.promise.then(a,a),s.promise}}}const AI={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"},II={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function bl(e){return{kind:e,statement:_(AI[e]),action:II[e]}}function Vu(e){return bl(aw(e))}const RI=()=>bl("historyUnreadable"),xI=new Set(["subagent_start","subagent_progress","subagent_end"]),TI=(e,t)=>({...e,[t]:(e[t]??0)+1}),CI=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=Rm(n);r&&(t[r]=(t[r]??0)+1)}return t},Rm=e=>{if(!e||typeof e!="object")return null;const t=e;return xI.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},OI=(e,t)=>{const n=Rm(t);return n?TI(e,n):e};function Zu(e,t,n){if(!n||!e)return{};const r=e.context_tokens;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return{};const o=t.context_tokens;return typeof o=="number"&&Number.isFinite(o)&&o>=r?{}:{context_tokens:r,context_is_estimate:e.context_is_estimate??t.context_is_estimate,context_window:e.context_window??t.context_window,last_usage:e.last_usage??null}}function PI(e){for(const t of e)t.type==="aside_delta"&&dI.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function MI(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const zn=new Set,fo=new Set;function jI(e,t){let n=null;for(const r of t)e.has(r)&&(n=n??new Set(e),n.delete(r));return n??e}const $I=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),NI=15e3,oc=[500,1e3,2e3,4e3,8e3,8e3],DI=oc.length,LI=2e4,FI=1e4,UI=1e4;function Yu(e){const t=Math.max(1,Math.min(e,oc.length));return oc[t-1]??8e3}const BI=3,HI=250,WI=32*1024,Ju=512,Qu=new Set(["turn_end","agent_end"]),Xu=2,GI=500,qu=ml,zI=6,da=$p("sessions.history"),KI=2e3,ef={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},tr=new Map,Ms=new Map,VI=8,ZI=2048,tf=1024,YI=1024,JI="",Hn=new Map;function nf(e){const t=e??JI,n=Hn.get(t);if(n)return Hn.delete(t),Hn.set(t,n),n;const r={attempts:new Map,painted:new Set,inFlight:new Set,refused:!1,depth:0,order:[],starts:new Map,waiting:new Set,settled:new Set,settleRows:0};for(Hn.set(t,r);Hn.size>VI;){const o=Hn.keys().next().value;if(o===void 0||o===t)break;Hn.delete(o)}return r}function ua(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function fa(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function QI(e,t){return Ms.set(e,t),()=>{Ms.get(e)===t&&Ms.delete(e)}}function Qj(e){const t=Ms.get(e);return t?(t(),!0):!1}const Xe=new Map,XI=4,qI=16;function xm(e,t){e(n=>vm(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function eR(e,t,n){const r=e.index.get(t),o=r===void 0?void 0:e.records[r];if(r===void 0||!o||o.kind!=="user"||!o.local||o.text===n)return e;const s=e.records.slice(),{skill:a,...c}=o,l=vi(n);return s[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:s}}function sc(e,t){let n=Xe.get(e);if(!n){if(Xe.size>=qI){const s=Xe.keys().next();s.done||Xe.delete(s.value)}n=new Map,Xe.set(e,n)}const r={identity:e,id:t.id,text:t.text,images:t.images,documents:t.documents??[],onPainted:t.onPainted,settled:t.settled,submittedAt:t.submittedAt};for(n.set(r.id,r);n.size>XI;){const s=n.keys().next();if(s.done)break;n.delete(s.value)}const o=tr.get(e);o&&xm(o,r)}function Xj(e){if(!e)return null;const t=Xe.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function ic(e,t){const n=Xe.get(e);n&&(n.delete(t),n.size===0&&Xe.delete(e))}function ac(e,t){const n=Xe.get(e)?.get(t);n&&(n.settled=!0)}function rf(e,t){return e?Xe.get(e)?.has(t)===!0:!1}function qj(e){return e?(Xe.get(e)?.size??0)>0:!1}function tR(e,t,n){const r=Xe.get(e)?.get(t);if(!r)return;r.text=n;const o=tr.get(e);o&&o(s=>eR(s,t,n))}function nR(e,t){if(e===t)return;const n=Xe.get(e);if(!n)return;Xe.delete(e);const r=Xe.get(t)??new Map;for(const[o,s]of n)s.identity=t,r.set(o,s);Xe.set(t,r)}function ys(e){Xe.delete(e)}function rR(e,t){const n=Xe.get(e);if(n)for(const r of[...n.keys()]){const o=t.index.get(r),s=o===void 0?void 0:t.records[o];s?.kind==="user"&&s.local!==!0&&ic(e,r)}}function oR(e,t){tr.set(e,t);const n=Xe.get(e);if(n)for(const r of n.values())xm(t,r);return()=>{tr.get(e)===t&&tr.delete(e)}}function sR(e,t){const n=Xe.get(e);if(!n)return t;let r=t;for(const o of n.values())r=vm(r,o.id,o.text,o.images,void 0,o.documents);return r}function iR(e,t,n){return e===t?!0:!n}function aR(e,t){const n=tr.get(e);if(!n)return ic(e,t),"queued";let r="queued";return n(o=>{const s=o.records[o.index.get(t)??-1];return!s||s.kind!=="user"?o:s.local?(r="retracted",ym(o,t)):(r="owner",o)}),ic(e,t),r}function Tm(e,t){const n=tr.get(e);if(!n)return"unseen";let r="unseen";return n(o=>{const s=o.records[o.index.get(t)??-1];return!s||s.kind!=="user"||(r=s.local?"local":"owner"),o}),r}function cR(e){const t=Am(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:Lt,stale:!1,owedLabels:zn,markLabels:fo}}function lR(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function pa(e,t){if(e.size!==0)for(const n of t)e.delete(Dt(n))}function ws(e,t){for(const n of t)e.add(Dt(n))}const of=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function e$(e,t,n=!0,r=e,o={}){const s=o.openFrame===!0,a=o.journalOrder===!0,c=R.useRef(a);c.current=a;const l=R.useRef(s);l.current=s;const d=o.peerJournalSource===!0,u=R.useRef(d);u.current=d;const f=R.useRef(null),h=R.useRef(0),m=R.useRef(0),y=R.useRef(0),b=R.useRef(null),v=R.useRef(null),p=R.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const N=St.getState();return px(N.sessions,N.placementFacts,e)},[e]),A=R.useCallback(()=>{const N=f.current;return p()&&N!==null&&N.sessionId===e&&N.peer},[p,e]),k=R.useCallback(()=>{const N=f.current;return N!==null&&N.sessionId===e&&N.peer},[e]),[C,L]=R.useState(()=>{const N=t&&e?cR(e):null;return{status:"connecting",frontend:null,heldFrontend:null,contextCarried:!1,pendingModel:null,history:null,cold:!1,subscriptionId:null,ownerEpoch:null,receipt:null,terminal:null,turnsCompleted:0,failure:null,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:r?sR(r,N?.transcript??Lt):Lt,stale:N?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:N?.owedLabels??zn,labelMarked:N?.markLabels??fo,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),O=R.useRef(C),I=R.useCallback(N=>{const ee=N(O.current);return ee===O.current||(O.current=ee,L(ee)),ee},[]);R.useEffect(()=>c_(()=>{I(N=>{const{failure:ee}=N;if(!ee?.kind)return N;const pe=bl(ee.kind);return pe.statement===ee.statement&&pe.action===ee.action?N:{...N,failure:pe}})}),[I]);const g=R.useRef(e),w=R.useRef([]),S=R.useRef(Lt.index),x=R.useRef(new Set),F=R.useRef(new Set),j=R.useRef(nf(e)),X=R.useRef(new Set),T=R.useRef(null),V=R.useRef({}),Z=R.useRef(null),ge=R.useRef(null),z=R.useRef(null),me=R.useRef(0),se=R.useRef(0),je=R.useRef(0);R.useEffect(()=>{if(!e||!t)return;const N=++se.current,ee=new WeakMap;let pe=null;const Fe=(ne,re)=>{const ke=ee.get(ne);if(ke===void 0||xt(re)===ke.revision)return!1;const ye=ne.payload.history.journal_generation;return!(typeof ye=="string"&&ye.length>0&&ye===re.journalGeneration)};let te=null,pt=!1,Ve=0,Se=0,et=0,G=0,Te=0,Pe=0,Oe=0,Ze=!1;const We=()=>{Pe&&(window.clearTimeout(Pe),Pe=0)},os=ne=>{for(const re of ne)j.current.attempts.set(re,(j.current.attempts.get(re)??0)+1)},ji=ne=>{I(re=>{const ke=new Set;for(const Ue of re.labelPending)re.labelPending.has(Ue)&&(fa(j.current,re.transcript.argsByCall,Ue,ua(re))||ke.add(Ue));let ye=null;for(const Ue of re.labelMarked)fa(j.current,re.transcript.argsByCall,Ue,ua(re))||(ye=ye??new Set(re.labelMarked),ye.delete(Ue));if(ke.size===0&&!ye)return re;const ie=new Set(re.labelPending);for(const Ue of ke)ie.delete(Ue);return{...re,labelPending:ie.size?ie:zn,labelMarked:ye&&ye.size===0?fo:ye??re.labelMarked}})},Xg=ne=>{I(re=>{let ke=null,ye=null;for(const ie of ne)re.labelPending.has(ie)&&(ke=ke??new Set(re.labelPending),ke.delete(ie),ye=ye??new Set(re.labelMarked),ye.add(ie));return!ke||!ye?re:{...re,labelPending:ke.size?ke:zn,labelMarked:ye}})},ss=async(ne,re,ke=ef,ye=1,ie,Ue=re,qe=null)=>{me.current+=1,se.current===ne&&I($e=>$e.historyReadPending?$e:{...$e,historyReadPending:!0});for(const $e of ke.targets)j.current.inFlight.add($e),X.current.add($e);let we=!1;try{we=await qg(ne,re,Ue,qe,ke,ye,ie)}finally{if(me.current=Math.max(0,me.current-1),me.current===0&&I($e=>$e.historyReadPending?{...$e,historyReadPending:!1}:$e),!we){for(const $e of ke.targets)j.current.inFlight.delete($e);j.current.refused&&Xg(ke.targets),ji()}}},qg=async(ne,re,ke,ye,ie,Ue,qe)=>{const we={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:ke.size===0},$e=O.current.transcript.viewEpoch,Ye=await e_(ne,re,ke,ye,ie,Ue,we,qe);if(Ye||se.current!==ne||we.reachedHeld||O.current.transcript.viewEpoch!==$e)return Ye;const bt=re!==ke&&[...re].some(yt=>ke.has(yt));if(bt&&we.joined)return Ye;let vt;if(we.oldest){if(!we.hasMore)return Ye;vt={id:we.oldest.id,ts:Math.round((we.oldest.ts??0)*1e3)}}else{if(bt||!ye)return Ye;vt=ye}if(!vt)return Ye;const yn=I(yt=>{const $t=wA(yt.transcript,vt,we.keys);return $t===yt.transcript?yt:{...yt,transcript:$t}});return S.current=yn.transcript.index,Ye},e_=async(ne,re,ke,ye,ie,Ue,qe,we)=>{const $e=O.current.transcript.viewEpoch,Ye=()=>O.current.transcript.viewEpoch!==$e,bt=new Set;let vt,yn=0,yt=0,$t=!1,wn=ke.size===0,fr=!1;const is=O.current.cold,kn=T.current,Un=kn?{epoch:kn.epoch,seq:kn.seq}:null,rn=new Set(ie.found),pr=()=>$A(ie.order,ie.targets,rn),M=()=>bm(ie.order,ie.targets,rn),P=()=>{const J=new Map;for(const wt of Ie){if(rn.has(wt))continue;const Nt=ht.get(wt);Nt!==void 0&&J.set(wt,Nt)}return J},Ee=new Set(ie.every);for(const J of rn)Ee.add(J);const Ie=new Set,ht=new Map;let Y=1;const Sn=ie.targets.size>0;let he=Math.max(Nu(pr()),Sn?j.current.depth:0),Je=0;for(;yn<qu&&yt<zI;){yt+=1;let J;const wt=za(O.current.transcript),Nt=wt.revision;try{J=await Qe({op:"sessions.history",sessionId:e,...vt?{beforeId:vt}:{},limit:Math.min(he,qu-yn),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(O.current.transcript).slice(0,512),...A()?{peerJournalSource:!0}:{}}:{}})}catch{if(Ye())return!1;if(O.current.transcript.records.length>0){if(Je++>0)return j.current.refused=!0,!1;continue}return Ue<BI?(Te=window.setTimeout(()=>{if(Te=0,se.current!==ne||Ye()){ji();return}ss(ne,re,ie,Ue+1,we,ke,ye)},Yu(Ue)),!0):(I(Re=>({...Re,status:"unavailable",failure:RI(),heldFrontend:null,...Re.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{ji()}if(se.current!==ne||Ye())return!1;if(xt(O.current.transcript)!==Nt){if(!O.current.hydrated)continue;return!1}j.current.refused=!1;const Bn=J.entries[0];yn+=J.entries.length,we?.(J.entries.length),pa(x.current,J.entries),ws(F.current,J.entries),I(Re=>{if(xt(Re.transcript)!==Nt)return Re;const Kt=vo(Re.transcript,J,{authoritative:!0,orderRead:wt,peerSource:k(),readWitness:Un}),hr=sa(J.entries,Ee),Ni=new Set(Re.labelPending);for(const o_ of hr)Ni.delete(o_);return{...Re,hydrated:Re.hydrated||J.entries.length>0||!is,labelPending:Ni.size?Ni:zn,labelMarked:jI(Re.labelMarked,hr),transcript:Kt}}),e&&vt===void 0&&St.getState().resolveHeldFromServer(e,J.entries,!J.cursor_missing);const r_=pr();for(const Re of sa(J.entries,Ee))rn.add(Re),Ee.add(Re);if(OA(J.entries)&&(fr=!0),Sn){const Re=PA(J.entries,Ee);for(const Kt of Re)Ie.add(Kt),Ee.add(Kt);for(const[Kt,hr]of xA(J.entries,Re))ht.set(Kt,hr);for(const Kt of[...Ie])rn.has(Kt)&&Ie.delete(Kt);Ie.size>0&&Y--<=0&&Ie.clear()}$t=$t||re.size===0||J.entries.some(Re=>re.has(Dt(Re))||bt.has(Re.id)),wn=wn||J.entries.some(Re=>ke.has(Dt(Re)));for(const Re of J.entries)bt.add(Re.id);for(const Re of J.entries)qe.keys.add(Dt(Re));Bn&&(qe.oldest=Bn),qe.hasMore=J.has_more,qe.joined=$t,qe.reachedHeld=wn;const $i=pr()+Ie.size;Sn&&pr()<r_&&(j.current.depth=Math.min(ml,Math.max(j.current.depth,yn)));let rd=!1;if(Sn){const Re=M();rd=TA(J.entries,Re,ie.starts,P(),new Set(Re.filter(hr=>ie.waiting.has(hr))))||fr}if(MA($t&&wn,rd?0:$i)||!Bn||!J.has_more)return!1;vt=Bn.id,he=$i>0?Nu($i):nc}return!1},ql=()=>{if(Ve&&cancelAnimationFrame(Ve),Se&&clearTimeout(Se),Ve=0,Se=0,se.current!==N)return;const ne=w.current;if(w.current=[],ne.length===0)return;const re=new Set,ke=new Map;for(const M of x.current)O.current.transcript.index.has(M)||x.current.delete(M);for(const M of F.current)O.current.transcript.index.has(M)||F.current.delete(M);for(const M of O.current.transcript.records)fl(M)&&!x.current.has(M.id)&&(re.add(M.id),ke.set(M.id,F.current.has(M.id)?M.ts:null));let ye=null;for(const M of ne){if(M.type!=="snapshot")continue;const P=M.payload.history,Ee=P.entries[0];if(!Ee||!P.has_more)continue;const Ie=Math.round((Ee.ts??0)*1e3);Ie>0&&(!ye||Ie<ye.ts)&&(ye={id:Ee.id,ts:Ie})}PI(ne);const ie=M=>{const P=M.payload.history.entries,Ee=P.at(-1);if(!Ee)return!1;if(lR(M.payload)){if(re.size===0)return!0;const Ie=new Set;for(const ht of P)Ie.add(Dt(ht));return P.some(ht=>re.has(Dt(ht)))?!0:t0(M.payload.history,ke,Ie)}return Ee.id===M.payload.frontend.snapshot.history_cursor?!1:re.has(Dt(Ee))},Ue=M=>M!=null&&S.current.has(M);let qe=!1;const we=ne.some(M=>M.type==="attention"?!Ue(M.payload.anchor_id):M.type==="snapshot"&&!ie(M)),$e=O.current.cold&&!O.current.hydrated&&ne.some(M=>M.type==="snapshot"||M.type==="frontend.replace"||M.type==="frontend.update"?M.payload.cold===!1:!1),Ye=new Set(O.current.transcript.argsByCall.keys()),bt=[],vt=new Set;for(const M of ne){if(M.type!=="snapshot")continue;const P=Fe(M,O.current.transcript);P||ws(F.current,M.payload.history.entries);for(const Ee of M.payload.history.entries){P||vt.add(Dt(Ee));const Ie=Ee.payload?.tool_calls;if(Array.isArray(Ie))for(const ht of Ie)ht&&typeof ht.id=="string"&&Ye.add(ht.id)}for(const Ee of M.payload.frontend.snapshot.live_events??[]){const Ie=Ee.message;!P&&typeof Ie?.id=="string"&&vt.add(Ie.id)}bt.push(...M.payload.frontend.snapshot.live_events??[])}const yn=ne.some(M=>M.type==="event"&&Qu.has(String(M.payload.type??""))),yt=$u(j.current.attempts,ju(bt,Ye),Ye,Xu),$t=yn?$u(j.current.attempts,[...j.current.attempts.keys(),...j.current.settled],Ye,Xu):[],wn=[];for(const M of ne){if(M.type!=="event")continue;const P=M.payload;String(P.type??"")==="tool_execution_end"&&String(P.tool_call_id??"")&&wn.push(P)}const fr=[];for(const M of wn){const P=String(M.tool_call_id??"");Ye.has(P)||j.current.settled.has(P)||fr.push(P)}for(const M of fr)j.current.settled.add(M);for(;j.current.settled.size>Ju;){const M=j.current.settled.values().next().value;if(M===void 0)break;j.current.settled.delete(M)}for(const[M,P]of Mu(wn))j.current.starts.set(M,P);for(;j.current.starts.size>tf;){const M=j.current.starts.keys().next().value;if(M===void 0)break;j.current.starts.delete(M)}const is=j.current.settleRows<GI?fr:[],kn=[...new Set([...yt,...$t,...is])],Un=kn.filter(M=>!j.current.painted.has(M));if(bt.length>0){j.current.order=ju(bt,new Set);for(const[M,P]of Mu(bt))j.current.starts.set(M,P);for(;j.current.starts.size>tf;){const M=j.current.starts.keys().next().value;if(M===void 0)break;j.current.starts.delete(M)}for(const M of IA(bt))j.current.waiting.add(M);for(const M of jA(bt))j.current.waiting.delete(M);for(;j.current.waiting.size>YI;){const M=j.current.waiting.values().next().value;if(M===void 0)break;j.current.waiting.delete(M)}}for(const M of[...j.current.attempts.keys()])Ye.has(M)&&j.current.attempts.delete(M);for(os([...yt,...$t]);j.current.attempts.size>Ju;){const M=j.current.attempts.keys().next().value;if(M===void 0)break;j.current.attempts.delete(M)}if(performance.mark("lop:transcript:flush:start"),I(M=>{let P={...M},Ee=P.frontend!==null;qe=!1;let Ie=null;const ht=Date.now();for(const Y of ne){if(Y.type==="heartbeat")continue;if(Y.type==="gap"){pe=null,P={...P,frontend:null,heldFrontend:P.frontend??P.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:Du(P.transcript)},Ee=!1;continue}if(Y.type==="open")pe=null;else if("seq"in Y){const he={epoch:Y.epoch,seq:Y.seq},Je=of(Y);if(!Je&&!sw(pe,he,{allowEqual:Y.type==="snapshot"}))continue;Je||(pe=he)}const Sn=T.current;if((Y.type==="open"||"seq"in Y)&&!of(Y)&&(T.current={epoch:Y.epoch,seq:Y.seq},P={...P,receipt:T.current}),Y.type==="open"){if(P={...P,subscriptionId:Y.payload.subscription_id},Y.payload.gap){const he=P.frontend??P.heldFrontend;P={...P,frontend:null,heldFrontend:he,history:null,transcript:Du(P.transcript)},he&&P.status==="live"&&(P={...P,status:"reconnecting"}),Ee=!1}continue}if(!Ee){if(Y.type==="event"&&(Ie=tc(Ie??P.transcript,Y.payload,ht,{frame:{epoch:Y.epoch,seq:Y.seq}})),Y.type==="snapshot"){const he=ee.get(Y),Je=Fe(Y,P.transcript);Je&&(qe=!0);const J=Y.payload,wt=!J.history.cursor_missing&&!Je;let Nt=Ie??P.transcript;wt&&(performance.mark("lop:open:history:start"),Nt=vo(Nt,J.history,{authoritative:!0,orderRead:he,peerSource:k(),readWitness:{epoch:Y.epoch,seq:Y.seq}}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),pa(x.current,J.history.entries),ws(F.current,J.history.entries)),e&&St.getState().resolveHeldFromServer(e,J.history.entries,wt),performance.mark("lop:open:seed:start"),Nt=AA(Nt,J.frontend.snapshot,ht,{epoch:Y.epoch,seq:Y.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const Bn=Zu(P.frontend??P.heldFrontend,J.frontend.snapshot,J.cold===!0||J.attaching===!0);P={...P,contextCarried:Object.keys(Bn).length>0,subagentPulses:CI(J.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...J.frontend.snapshot,...Bn,attention:Ar(P.frontend?.attention,J.frontend.snapshot.attention,e)},history:Je?P.history:J.history,cold:J.cold,ownerEpoch:J.frontend.epoch,failure:null,hydrated:P.hydrated||wt&&J.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:Nt},Ee=!0,Ie=null}continue}if(Y.type==="attention"){P.frontend&&(P={...P,frontend:{...P.frontend,attention:Ar(P.frontend.attention,Y.payload,e)}});continue}if(Y.type==="frontend.update"){const he=Y.payload,Je=he.changes??{};if((he.degraded===!0||he.paused===!0)&&(P={...P,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!P.frontend)continue;const J=he.epoch!==P.ownerEpoch&&Je.epoch===he.epoch,wt=he.changes!==void 0&&Je.epoch===he.epoch;(J||he.epoch===P.ownerEpoch&&(P.frontend.sequence<he.sequence||P.frontend.sequence===he.sequence&&wt))&&(P={...P,contextCarried:!1,ownerEpoch:J?he.epoch:P.ownerEpoch,frontend:{...P.frontend,...Je,...Je.jobs==null&&he.job_deltas?{jobs:Zw(P.frontend.jobs??[],he.job_deltas)}:{},attention:Ar(P.frontend.attention,Je.attention,e),sequence:he.sequence},...typeof he.cold=="boolean"?{cold:he.cold}:{}},wt&&P.liveUpdatesNotice==="update"&&P.liveUpdatesPaused&&(P={...P,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(Y.type==="frontend.replace"){if(P.frontend&&iw(Sn,e,Y)){const he=Y.payload.frontend,Je=Zu(P.frontend,he.snapshot,Y.payload.cold===!0);P={...P,contextCarried:Object.keys(Je).length>0,frontend:{...he.snapshot,...Je,attention:Ar(P.frontend.attention,he.snapshot.attention,e)},ownerEpoch:he.epoch,cold:Y.payload.cold,...P.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(Y.type==="event"){const he=String(Y.payload.type??"");if(Y.payload.action==="reload"){P={...P,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}$I.has(he)&&(P={...P,terminal:he}),Qu.has(he)&&(P={...P,turnsCompleted:P.turnsCompleted+1});const Je=tc(P.transcript,Y.payload,ht,{frame:{epoch:Y.epoch,seq:Y.seq},userStoppedAt:e?St.getState().stoppedTurns[e]??null:null,queuedAskEngine:fm(P.frontend)});Je!==P.transcript&&(P={...P,transcript:Je});const J=OI(P.subagentPulses,Y.payload);J!==P.subagentPulses&&(P={...P,subagentPulses:J})}}if(!Ee&&Ie){for(const Y of Ie.index.keys())P.transcript.index.has(Y)||x.current.add(Y);P={...P,transcript:Ie}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),S.current=P.transcript.index,!MI(ne))return M;if(Un.length>0){const Y=new Set(P.labelPending);for(const Sn of Un)Y.add(Sn);P={...P,labelPending:Y}}return P.frontend!==null&&P.frontend!==P.heldFrontend&&(P={...P,heldFrontend:P.frontend}),P}),Un.length>0){for(const M of Un)j.current.painted.add(M);for(;j.current.painted.size>ZI;){const M=j.current.painted.values().next().value;if(M===void 0)break;j.current.painted.delete(M)}}const rn=we||qe,pr=is.length>0&&yt.length===0&&$t.length===0&&!rn&&!$e;if(rn||kn.length>0||$e){const M=new Set(kn),P=j.current.order;ss(N,vt,kn.length>0?{targets:M,order:P,starts:j.current.starts,waiting:j.current.waiting,every:new Set([...P,...M]),found:new Set(sa(ne.flatMap(Ee=>Ee.type==="snapshot"?Ee.payload.history.entries:[]),new Set(P))),pending:Un}:ef,1,pr?Ee=>{j.current.settleRows+=Ee}:void 0,re,ye)}if(Kw())for(const M of ne)"epoch"in M&&"seq"in M&&Vw({carrier:"canonical-sse",sessionId:e,epoch:M.epoch,seq:M.seq,disposition:"processed"})},zr=()=>{const ne=te;if(te=null,f.current=null,h.current+=1,m.current&&(window.clearTimeout(m.current),m.current=0),y.current+=1,!!ne){pt=!0;try{ne()}finally{pt=!1}}},Kr=()=>{const ne=za(O.current.transcript),re=ia.currentToken(),ke=++je.current;We(),Pe=window.setTimeout(()=>{Pe=0,se.current===N&&(zr(),I(ie=>({...ie,subscriptionId:null,status:"unavailable",failure:Vu(go.ended),...ie.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ze&&(Ze=!0,Oe=window.setTimeout(()=>{Oe=0,se.current===N&&td()},FI)))},LI);const ye=p();te=xw({sessionId:e,epoch:V.current.epoch,afterSeq:V.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:Zt(O.current.transcript).slice(0,512),...ye?{peerJournalSource:!0}:{}}:{}},ie=>{if(se.current===N&&je.current===ke){if(ie.kind==="error"||ie.kind==="end"){if(pt)return;if(We(),zr(),ie.kind==="error"&&ie.status===404){if(!n){e&&St.getState().retireDraftWarm(e),I(we=>({...we,subscriptionId:null}));return}e&&(hI(e),vI(e),SI(e),St.getState().retireDraftsForSession(e)),I(we=>({...we,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...we.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const Ue=ie.kind==="error"?ie.detail??_("ui.common.errors.event_stream_failed"):_("ui.common.errors.event_stream_closed");if(I(we=>({...we,subscriptionId:null})),et>=DI){I(we=>({...we,status:"unavailable",failure:Vu(Ue),...we.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}et+=1;const qe=T.current;qe&&(V.current={epoch:qe.epoch,afterSeq:qe.seq}),I(we=>we.status==="unavailable"&&et>1?we:{...we,status:"reconnecting",failure:null}),G=window.setTimeout(()=>{G=0,se.current===N&&Kr()},Yu(et));return}if(ie.data!==void 0)try{const Ue=ie.data,qe=ie.receipt?performance.now():0,we=Ue.length>=WI;we&&performance.mark("lop:open:parse:start");const $e=JSON.parse(Ue),Ye=ie.receipt?performance.now():0;$e.type==="snapshot"&&ee.set($e,ne),we&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),$e.type==="snapshot"&&(ie.receipt&&console.warn(fw(ie.receipt,re,qe,Ye)),ia.note(e,"snapshot",re),et=0,We(),Ze=!1),w.current.push($e),Ve||(Ve=requestAnimationFrame(ql)),Se||(Se=window.setTimeout(ql,HI))}catch{}}},ie=>{ie==="requested"&&ia.note(e,"request",re)}),f.current={sessionId:e,peer:ye},h.current+=1},ed=()=>{G!==0&&(window.clearTimeout(G),G=0),V.current={},T.current=null,zr(),Kr()},td=()=>{et=0,Oe&&(window.clearTimeout(Oe),Oe=0),G&&(window.clearTimeout(G),G=0),Te&&(window.clearTimeout(Te),Te=0),I(ne=>({...ne,failure:null,status:ne.status==="unavailable"?"connecting":ne.status,transcript:bs(ne.transcript,!1)})),O.current.hydrated||ss(N,new Set(O.current.transcript.index.keys())),!te&&Kr()};Kr(),Z.current=td,ge.current=()=>{O.current.liveUpdatesReloading||(I(ne=>({...ne,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),et=0,G&&(window.clearTimeout(G),G=0),Oe&&(window.clearTimeout(Oe),Oe=0),ed())},z.current=()=>{!O.current.hydrated&&me.current===0&&ss(N,new Set(O.current.transcript.index.keys()))};const t_=QI(e,ed),nd=()=>{if(!t||!e||b.current===e)return;const ne=f.current;ne===null||ne.sessionId!==e||ne.peer||p()&&(b.current=e,zr(),Kr())};v.current=nd;const n_=St.subscribe(()=>{nd()});return()=>{se.current+=1,Z.current=null,z.current=null,ge.current=null,v.current=null,n_(),m.current&&(window.clearTimeout(m.current),m.current=0),t_(),zr(),Ve&&cancelAnimationFrame(Ve),Se&&clearTimeout(Se),G&&clearTimeout(G),Te&&clearTimeout(Te),De.current&&(window.clearTimeout(De.current),De.current=0),Ke.current&&(window.clearTimeout(Ke.current),Ke.current=0),Oe&&window.clearTimeout(Oe),We(),w.current=[]}},[I,e,t,n,a,p,A,k]),R.useEffect(()=>{!e||!t||v.current?.()},[e,t,d]),R.useEffect(()=>{V.current={},T.current=null,S.current=Lt.index;const N=iR(g.current,e,n);g.current=e;const ee=e?Am(e):null;S.current=N?O.current.transcript.index:(ee?.transcript??Lt).index;const pe=new Set(N?x.current:[]);for(const te of ee?.replayBorn??[])pe.add(te);const Fe=N?O.current.transcript.index:(ee?.transcript??Lt).index;for(const te of pe)Fe.has(te)||pe.delete(te);x.current=pe,N||(F.current=new Set),I(te=>({...te,frontend:null,heldFrontend:N?te.heldFrontend:null,contextCarried:N?te.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:N?te.turnsCompleted:0,transcript:N?te.transcript:ee?.transcript??Lt,stale:N?te.stale:ee!==null,missing:N?te.missing:!1,status:"connecting",subagentPulses:{},labelPending:ee?.owedLabels??zn,labelMarked:ee?.markLabels??fo,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),j.current=nf(e)},[e,n]),R.useEffect(()=>{if(e)return()=>{const N=O.current.transcript;N.records.length>0&&pI(e,{transcript:N,owedLabels:new Set([...O.current.labelPending].filter(ee=>fa(j.current,O.current.transcript.argsByCall,ee,ua(O.current)))),markLabels:new Set(O.current.labelMarked),replayBorn:new Set(x.current)});for(const ee of X.current)j.current.inFlight.delete(ee);X.current.clear()}},[e]);const De=R.useRef(0);R.useEffect(()=>{if(C.labelPending.size===0&&C.labelMarked.size===0){De.current&&(window.clearTimeout(De.current),De.current=0);return}if(De.current)return;const N=()=>{De.current=0;const ee=O.current.labelPending,pe=O.current.labelMarked;if(ee.size===0&&pe.size===0)return;const Fe=j.current;for(const te of ee)if(Fe.inFlight.has(te)){De.current=window.setTimeout(N,da);return}for(const te of pe)if(Fe.inFlight.has(te)){De.current=window.setTimeout(N,da);return}I(te=>te.labelPending.size===0&&te.labelMarked.size===0?te:{...te,labelPending:zn,labelMarked:fo})};De.current=window.setTimeout(N,da)},[I,C.labelPending,C.labelMarked]);const Ke=R.useRef(0);R.useEffect(()=>{if(C.labelPending.size===0){Ke.current&&(window.clearTimeout(Ke.current),Ke.current=0),I(N=>N.labelHoldLate?{...N,labelHoldLate:!1}:N);return}C.labelHoldLate||Ke.current||(Ke.current=window.setTimeout(()=>{Ke.current=0,I(N=>N.labelPending.size===0||N.labelHoldLate?N:{...N,labelHoldLate:!0})},KI))},[I,C.labelPending,C.labelHoldLate]);const tt=R.useRef(e);tt.current=e;const _e=R.useRef({id:e,epoch:0});_e.current.id!==e&&(_e.current={id:e,epoch:_e.current.epoch+1});const Ce=R.useRef(null);Ce.current===null&&(Ce.current=EI());const Rt=R.useRef(!1),Le=R.useRef(null),[Mt,ve]=R.useState(0);R.useEffect(()=>{const N=C.transcript,ee=Zt(N);if(!e||!a||!N.orderNeedsReconcile&&(!N.journalGeneration||ee.length===0)||Rt.current)return;const pe=G=>({fields:JSON.stringify([Mt,e,G.viewEpoch,xt(G),G.orderNeedsReconcile,G.orderWantedGeneration,Zt(G)]),demand:G.orderDemand}),Fe=pe(N);if(Le.current?.fields===Fe.fields&&Le.current.demand===Fe.demand)return;Le.current=Fe;const te=e,pt=N.viewEpoch;Rt.current=!0;let Ve=null,Se=N;const et=G=>{if(!G.peer||tt.current!==te||O.current.transcript.viewEpoch!==pt||h.current!==G.streamEpoch)return;const Te=G.kind==="authority"?G.frame.payload.history:G.page,Pe=Te.journal_order_state;if(Pe==="ready"){m.current&&(window.clearTimeout(m.current),m.current=0),I(Ze=>{const We=bs(Ze.transcript,!1);return We===Ze.transcript?Ze:{...Ze,transcript:We}});return}if(Pe==="unavailable"){if(m.current&&(window.clearTimeout(m.current),m.current=0),Te.reconcile===!0)return;I(Ze=>{const We=bs(Ze.transcript,!0);return We===Ze.transcript?Ze:{...Ze,transcript:We}});return}if(Pe!=="building")return;m.current&&(window.clearTimeout(m.current),m.current=0);const Oe=++y.current;m.current=window.setTimeout(()=>{m.current=0,y.current===Oe&&tt.current===te&&O.current.transcript.viewEpoch===pt&&h.current===G.streamEpoch&&I(Ze=>{const We=bs(Ze.transcript,!0);return We===Ze.transcript?Ze:{...Ze,transcript:We}})},UI)};qw({getTranscript:()=>O.current.transcript,isCurrent:()=>tt.current===te&&O.current.transcript.viewEpoch===pt,sweep:(G,Te)=>{if(!A())return;if(G.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${te}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const Pe=G.journalGeneration;if(typeof Pe!="string"||Pe.length===0)return{kind:"none",path:`/v1/desktop/sessions/${te}/history`,query:new URLSearchParams};if(qp(G,Te?.("lookup")).length>0){const We=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:Pe});return{kind:"lookup",path:`/v1/desktop/sessions/${te}/history`,query:We}}if(Zc(G).length>0){const We=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:Pe});return{kind:"payload",path:`/v1/desktop/sessions/${te}/history`,query:We}}return{kind:"none",path:`/v1/desktop/sessions/${te}/history`,query:new URLSearchParams}},read:async(G,Te)=>{Se=O.current.transcript,Le.current=pe(Se);const Pe=A(),Oe=h.current;if(Te==="lookup"||Te==="payload"){const We=O.current.transcript.journalGeneration,os=await Qe({op:"sessions.history",sessionId:te,limit:100,journalOrder:!0,orderIds:G,peerJournalSource:!0,sourceRead:Te==="payload"?"payload":"metadata",...typeof We=="string"&&We.length>0?{expectedJournalGeneration:We}:{}});return Te==="payload"?{kind:"payload",page:os,peer:Pe,streamEpoch:Oe}:{kind:"lookup",page:os,peer:Pe,streamEpoch:Oe}}return{kind:"authority",frame:await Qe({op:"sessions.get",sessionId:te,journalOrder:!0,orderIds:G,...Pe?{peerJournalSource:!0}:{}}),peer:Pe,streamEpoch:Oe}},page:G=>G.kind==="authority"?G.frame.payload.history:G.page,lookupPath:`/v1/desktop/sessions/${te}`,commit:(G,Te,Pe)=>{G.peer&&h.current!==G.streamEpoch||(I(Oe=>tt.current!==te||xt(Oe.transcript)!==Te||Oe.transcript.viewEpoch!==pt?Oe:{...Oe,transcript:G.kind==="authority"?G.peer?Pu(Oe.transcript,G.frame.payload.history,{authoritative:!0,orderRead:Pe}):bA(Oe.transcript,G.frame.payload.history,Pe):G.kind==="payload"?vA(Oe.transcript,G.page,Pe,Te):Pu(Oe.transcript,G.page,{authoritative:!1})}),et(G))}}).then(G=>{Ve=G.kind==="complete"?G.transcript:null}).catch(G=>{console.warn("[canonical] source-order reconcile refused",G)}).finally(()=>{Rt.current=!1;const G=O.current.transcript,Te=Ve??Se;Ve&&tt.current===te&&G.viewEpoch===pt&&!G.orderNeedsReconcile&&(Le.current=pe(Te)),(tt.current!==te||G.viewEpoch!==pt||xt(G)!==xt(Te)||G.orderWantedGeneration!==Te.orderWantedGeneration||G.orderNeedsReconcile!==Te.orderNeedsReconcile||G.orderDemand!==Te.orderDemand||JSON.stringify(Zt(G))!==JSON.stringify(Zt(Te)))&&ve(Pe=>Pe+1)})},[I,e,a,A,C.transcript,Mt]);const Ae=R.useCallback(async()=>{const N=Ce.current;if(!e||!N)return{kind:"nothing-to-load"};const ee=e,pe=_e.current.epoch,Fe=()=>_e.current.epoch===pe,te=O.current.transcript.viewEpoch,pt=()=>O.current.transcript.viewEpoch===te,Ve=await N.load(`${ee}#${pe}`,{getTranscript:()=>O.current.transcript,readPage:Se=>Qe({op:"sessions.history",sessionId:ee,beforeId:Se,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(O.current.transcript).slice(0,512),...A()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>Fe()&&pt(),commit:Se=>I(et=>{const G=Se(et.transcript);return G===et.transcript?et:{...et,transcript:G}}).transcript,setLoading:Se=>{Fe()&&I(et=>et.loadingOlder===Se?et:{...et,loadingOlder:Se})},peerSource:k});return Fe()&&(Ve.kind==="failed"?I(Se=>Se.olderFailed?Se:{...Se,olderFailed:!0}):Ve.kind==="applied"&&I(Se=>Se.olderFailed?{...Se,olderFailed:!1}:Se)),Ve},[I,e,A,k]),ft=R.useCallback(async()=>(await Ae()).kind==="applied",[Ae]),_t=R.useRef(!1),jt=R.useCallback(async(N,ee)=>{if(!e||_t.current)return!1;const pe=e;_t.current=!0;const Fe=xt(O.current.transcript),te=T.current,pt=te?{epoch:te.epoch,seq:te.seq}:null;try{const Ve=await Qe({op:"sessions.history",sessionId:pe,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(O.current.transcript).slice(0,512),...A()?{peerJournalSource:!0}:{}}:{}});return tt.current!==pe||xt(O.current.transcript)!==Fe||O.current.transcript.viewEpoch!==ee?!1:(I(Se=>xt(Se.transcript)!==Fe?Se:{...Se,transcript:vo(Se.transcript,Ve,{keepPaging:!0,peerSource:k(),readWitness:pt})}),pa(x.current,Ve.entries),ws(F.current,Ve.entries),HA(Ve.entries,N))}catch{return!1}finally{_t.current=!1}},[I,e,A,k]);R.useEffect(()=>r?oR(r,ee=>{I(pe=>{const Fe=ee(pe.transcript);return Fe===pe.transcript?pe:{...pe,transcript:Fe}})}):void 0,[I,r]),R.useEffect(()=>{r&&rR(r,C.transcript)},[r,C.transcript]);const Gr=R.useCallback(()=>{I(N=>({...N,transcript:NA(N.transcript),olderFailed:!1,heldFrontend:null}))},[I]),ur=R.useCallback(()=>{Z.current?.()},[]),Zl=R.useCallback(()=>{ge.current?.()},[]),Yl=R.useCallback(()=>{z.current?.()},[]),Jl=R.useCallback((N,ee="info")=>{I(pe=>({...pe,transcript:FA(pe.transcript,N,ee)}))},[I]),Ql=R.useCallback(N=>{I(ee=>({...ee,pendingModel:N}))},[I]),Xl=R.useCallback(()=>{I(N=>N.pendingModel===null?N:{...N,pendingModel:null})},[I]);return R.useEffect(()=>{const N=C.pendingModel;if(!N)return;const ee=rc(N);if(!ee)return;const pe=C.frontend;nI(pe,ee)&&I(Fe=>({...Fe,pendingModel:null}))},[I,C.frontend,C.pendingModel]),R.useEffect(()=>{if(!C.pendingModel)return;const N=window.setTimeout(()=>I(ee=>({...ee,pendingModel:null})),NI);return()=>window.clearTimeout(N)},[I,C.pendingModel]),R.useMemo(()=>({...C,awaitingHydration:t&&!!e&&n&&!C.hydrated,loadOlder:ft,loadOlderDetailed:Ae,refreshTail:jt,clearView:Gr,addNote:Jl,paintPendingModel:Ql,clearPendingModel:Xl,retry:ur,rehydrate:Yl,reloadFromHistory:Zl}),[C,t,e,n,ft,Ae,jt,Gr,Jl,Ql,Xl,ur,Yl,Zl])}function Si(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
34
+ `),s=(r?`${n} ${r}`:n).trim();if(s.length<=bo)return{headline:s,detail:o||null};const a=r===null?null:oA(r);if(a!==null){const c=(f,h)=>`${ti} ${[f,h].filter(Boolean).join(" ")}`,l=f=>[f,o].filter(Boolean).join(`
35
+ `)||null,d=`${n} ${c(a.leading,a.clause)}`;if(d.length<=bo)return{headline:d,detail:l(a.rest)};const u=`${n} ${c("",a.clause)}`;if(u.length<=bo)return{headline:u,detail:l([a.leading,a.rest].filter(Boolean).join(" "))}}return{headline:um(s),detail:[r,o].filter(Boolean).join(`
36
+ `)||null}}function oA(e){const t=e.startsWith(ti)?e.slice(ti.length):e,n=t.indexOf("/mcp");if(n<0)return null;const r=t.slice(n),o=r.search(qE),s=(o<0?r:r.slice(0,o)).trim();return s?{leading:t.slice(0,n).trim(),clause:s,rest:(o<0?"":r.slice(o)).trim()}:null}function sA(e){const t=e.trim(),n=iA(t);if(n<0)return{headline:t,detail:null};const r=t.slice(n).trim();return{headline:t.slice(0,n).trim(),detail:r||null}}function iA(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
+ `),r=n[0].match(QE),s=(typeof t.raw=="string"?t.raw.trim():"")||(r?n[0].slice(r[0].length):n[0]).trim()||e.trim(),a=n.slice(1).join(`
38
+ `).trim();return{provider:(r?.[1]??"").trim()||null,category:(r?.[2]??"").trim()||null,headline:s,detail:a||null}}function dm(e){if(typeof e!="object"||e===null)return null;const t=e.hub_receipt;if(typeof t!="object"||t===null)return null;const n=t,r=n.direction;if(r!=="to_child"&&r!=="to_parent")return null;const o=n.body;if(typeof o!="string"||!o.trim())return null;const s={...n};for(const a of["expects_reply","steer"])typeof s[a]!="boolean"&&(s[a]=null);for(const a of["label","job_id"])a in s&&typeof s[a]!="string"&&delete s[a];return s}function cA(e){const t=lA(e),n=e.split(`
39
+ `).map(r=>r.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=>!Cu.test(c)&&!dA(c),r=t.find(n),o=t.find(c=>Cu.test(c)&&!c.startsWith("</"));let s=r??o??e.trim();const a=t.indexOf(s);if(a>=0&&s.endsWith(":")){const c=t.slice(a+1).find(n);c&&(s=`${s} ${c}`)}return um(s)}function dA(e){return XE.has(e.replace(/\s+/g," ").trim().toLowerCase())}function um(e){const t=e.trim();if(t.length<=bo)return t;const n=t.slice(0,bo),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const uA="harness_injected",fm=e=>!e||typeof e!="object"?!1:e[uA]===!0;function pm(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function hm(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 Ou(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 mm(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:sm,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:r,text:a,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const a=n.details??{},c=om(String(a.detail??""));return{kind:"notice",id:e.id,ts:r,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:r,complete:!0,text:am,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:cm,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:r,complete:!0,text:wi(c),copy:c,level:a.kind==="error"?"error":"warning"}}}}if(e.type==="custom"&&n.custom_type===qa){const a=n.details??{};return Iu(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(BE.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=Za(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&ea(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...Ps(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(h=>f[h]===u[h])?f:u,images:Jn(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===zE){const{body:u,sender:f}=mh(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&ea(t.sender,f)?t.sender:f}}if(a===ZE){if(ik(c)||ak(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===KE){const u=c.answers,f={};if(u&&typeof u=="object")for(const[y,b]of Object.entries(u))f[String(y)]=Array.isArray(b)?b.map(v=>String(v)):[];const h=c.questions,m=Array.isArray(h)?h.flatMap(y=>{if(!y||typeof y!="object")return[];const b=y;return[{id:String(b.id??""),question:String(b.question??""),secret:b.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:r,askId:String(c.ask_id??""),status:String(c.status??"answered"),by:c.by&&typeof c.by=="object"?c.by:null,reason:typeof c.reason=="string"?c.reason:null,questions:m,answers:f,secretLost:c.secret_lost===!0}}if(a===VE){const u=Number(c.waited_s);return{kind:"ask_timeout",id:e.id,ts:r,askId:String(c.ask_id??""),waitedS:Number.isFinite(u)&&u>0?u:0,urgent:c.urgent===!0}}if(a===qa)return Iu(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?KS(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:a,text:d,...a==="team_bridge_message"?{bridgeReceipt:ck(c)}:{},attribution:n.attribution??"system",...Ps(a,d,c)}:null}const s=String(n.role??"");if(s==="user"){const a=dm(n.provider_payload);if(a){const u=Za({...a,text:Yt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&ea(f.sender,u.sender)&&(u.sender=f.sender);const h=t?.kind==="custom"||t?.kind==="user"?t.images:void 0;return{kind:"custom",id:e.id,ts:r,customType:"hub_message",text:u.envelope,attribution:"user",...Ps("hub_message",u.envelope||u.body,{...a,text:Yt(n)}),receipt:f&&Object.keys(u).every(m=>f[m]===u[m])?f:u,images:Jn(n,e.id,h)}}}if(fm(n.provider_payload))return null;const c=Yt(n);if(Uh(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=vi(c),d=tm(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Jn(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(s==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=Yt(n);return!c&&a.length>0?{kind:"assistant",id:e.id,ts:r,text:"",streaming:!1,stopReason:String(n.stop_reason??"toolUse"),callsTools:!0,error:!1}:{kind:"assistant",id:e.id,ts:r,text:c,complete:!0,streaming:!1,callsTools:a.length>0,stopReason:n.stop_reason??null,error:!!n.is_error}}if(s==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(hm(l))return null;const d=Xh(l.__fault);return{kind:"tool",id:`tool:${a}`,ts:r,toolCallId:a,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:Yt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Jn(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...Dh(c.details,t?.kind==="tool"?t:null),diff:Nh($h(c.details),t?.kind==="tool"?t.diff:null),diffTruncatedRows:Lh(c.details,t?.kind==="tool"?t.diffTruncatedRows??0:0),stopped:d,delivery:xh(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:Sh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:Eh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:Fh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.details??null:null)}}return null}function hA(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 mA=/^(?:tool|compaction|local):/;function gA(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)&&!mA.test(t.id))return t.id}return null}function _A(e,t){const n=nE(t);if(n)return e.records[e.index.get(n)??-1]}function ul(e){const t=qp(e,e.records);if(t===e.records)return e;const n=t.map(Bh);return{...e,records:n,index:It(n)}}const Bo=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function gm(e,t,n,r){const o={...e,sourceEntryId:t,journalSeq:r,journalGeneration:n};if(e.kind==="user"&&(e.provisional===!0||e.local===!0)){const{provisional:s,local:a,...c}=o;return c}return o}function bA(e){const t=new Set,n=new Set;for(const r of e.records){const o=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof o!="string"||o.length<1||o.length>128||(t.add(o),r.journalGeneration===e.journalGeneration&&Bo(r.journalSeq)&&n.add(o))}return{carried:t,admitted:n}}function fl(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function Pu(e,t){const n=new Set;for(const a of t)typeof a=="string"&&a.length>0&&a.length<=128&&n.add(a);if(n.size===0)return e;let r=!1;const o=e.records.map(a=>{const c=a.sourceEntryId??(a.kind==="tool"||a.kind==="supplement"?null:a.id);if(c===null||!n.has(c))return a;const l=fl(a);return l!==a&&(r=!0),l});let s=r?{...e,records:o}:e;return s=_m(s,n),s}function _m(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=bA(e),o=e.orderRevision??0,s=e.journalBodyOwed;let a=null;const c=e.journalSourceVoid;let l=null;for(const d of t)typeof d!="string"||d.length<1||d.length>128||!n.has(d)||r.has(d)||(a||(a=new Map(s??[])),a.set(d,o),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return a?{...e,journalBodyOwed:a,...l?{journalSourceVoid:l}:{}}:e}function ni(e,t,n){const r=n&&e.journalSourceUnavailable===!0?{...e,journalSourceUnavailable:void 0}:e;if(t.length===0)return r;const o=r.journalBodyOwed;let s=null;const a=r.journalSourceVoid;let c=null;for(const l of t)o?.has(l)&&(s||(s=new Map(o)),s.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!s&&!c?r:{...r,...s?{journalBodyOwed:s}:{},...c?{journalSourceVoid:c}:{}}}function qo(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function bm(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function vA(e,t,n){let r=Lr(e,t,t.entries.map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),!0,n);for(const s of t.entries)r=Zc(r,{...s.payload,id:s.id});const o=qo(r,!1);return ul(o.journalPeerSource===void 0&&!o.journalBodyOwed&&!o.journalSourceVoid&&o.journalSourceUnavailable===void 0?o:{...o,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function Mu(e,t,n){let r=Lr(e,t,(t.entries??[]).map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=qo(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const s=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];s.length>0&&(r=_m(r,s));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=ni(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=bm(r,t),ul(r)}function yA(e,t,n,r){let o=Lr(e,t,[],!1,n,{peer:!0});o=qo(o,!0);const s=o.journalBodyOwed,a=m=>r!==void 0&&(s?.get(m)??Number.NEGATIVE_INFINITY)>r,c=t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===o.journalGeneration,l=c?[...t.entries??[],...t.dependency_entries??[]]:[],d=[];let u=o.records,f=o.index;if(l.length>0){const m=new Map;for(const y of l){if(typeof y.id!="string"||y.id===""||a(y.id))continue;const b=`tool:${String(y.payload?.tool_call_id??"")}`,v=f.get(y.id)??f.get(b),p=v===void 0?void 0:u[v];if(!p)continue;let A=mm(y,p);A&&(A={...A,sourceEntryId:y.id,...p.sourcePrecedes?{sourcePrecedes:p.sourcePrecedes}:{}},Bo(y.journal_seq)?(A=gm(A,y.id,t.journal_generation,y.journal_seq),d.push(y.id)):A=fl(A),m.set(p.id,A))}m.size>0&&(u=u.map(y=>m.get(y.id)??y),f=It(u))}let h=u===o.records?o:{...o,records:u,index:f};if(c){h=ni(h,d,!1);const m=(t.source_missing_ids??[]).filter(y=>typeof y=="string"&&y.length>0&&y.length<=128&&!a(y));if(m.length>0){h=ni(h,m,!1);const y=new Set(h.journalSourceVoid??[]);for(const b of m)y.add(b);h={...h,journalSourceVoid:y}}}return h=bm(h,t),ul(h)}function bs(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function vo(e,t,n={}){let r=e;const o=r,s=[];let a=e.profileHistoryPending;const c=P=>qo(ni(P.profileHistoryPending===a?P:{...P,profileHistoryPending:a},s,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Lr(r,t,t.entries.map(P=>({id:P.id,journal_seq:P.journal_seq,role:P.payload?.role,tool_call_id:P.payload?.tool_call_id})),n.authoritative===!0,n.orderRead,{peer:n.peerSource===!0}),t.journal_generation&&t.journal_generation!==r.journalGeneration)return c(r);const l=n.peerSource===!0&&typeof t.journal_generation=="string"&&t.journal_generation.length>0&&t.journal_generation===r.journalGeneration;for(const P of t.entries)r=Zc(r,{...P.payload,id:P.id});const d=n.keepPaging===!0&&r.viewEpoch>0,u=n.pagedBefore!==void 0&&r.index.has(n.pagedBefore)?n.pagedBefore:r.records[0]?.id,f=JS(t.entries,r.records,d||o.journalGeneration!==r.journalGeneration?[]:r.profileHistoryPending);a=!d&&f.pending.length?f.pending:void 0;const h=[];for(const P of f.entries){if(d&&!LA(P,r.clearedAt))continue;const z=r.records[r.index.get(P.id)??-1]??r.records[r.index.get(`tool:${String(P.payload?.tool_call_id??"")}`)??-1]??_A(r,P);let Z=mm(P,z);if(QS(P,z)&&z&&(Z=z),Z&&(r.journalMode||Z.kind==="tool"&&ol(Z.toolName,Z.details))&&(Z={...Z,sourceEntryId:P.id}),Z&&r.journalMode){const ge=z?.sourcePrecedes??(n.pagedBefore!==void 0&&!z?u:void 0);ge!==void 0&&Z.sourcePrecedes!==ge&&(Z={...Z,sourcePrecedes:ge})}Z&&l&&Bo(P.journal_seq)?(Z=gm(Z,P.id,t.journal_generation,P.journal_seq),s.push(P.id)):Z&&n.peerSource===!0&&(Z=fl(Z)),!(Z&&z&&pA(z,n.readWitness))&&Z&&h.push(Z)}let m=r.argsByCall,y=!1;for(const P of t.entries){const z=P.payload?.tool_calls;if(!Array.isArray(z))continue;const Z=Math.round((P.ts??0)*1e3);for(const ge of z)!ge||typeof ge.id!="string"||m.has(ge.id)||(y||(m=new Map(m),y=!0),m.set(ge.id,{...ge,anchoredAt:Z,anchorId:P.id}))}for(let P=0;P<h.length;P++){const z=h[P];if(z.kind!=="tool")continue;const Z=m.get(z.toolCallId);if(!Z)continue;const ge=Z.arguments??null;h[P]={...z,args:ge,intent:typeof ge?.i=="string"?ge.i:null}}const b=y?r.records.map(P=>{if(P.kind!=="tool"||P.args)return P;const Z=m.get(P.toolCallId)?.arguments??null;return Z?{...P,args:Z,intent:P.intent??(typeof Z.i=="string"?Z.i:null)}:P}):r.records,v=new Set(t.entries.map(P=>P.id)),p=n.peerSource===!0&&n.replace===!0?r.records.filter(P=>P.kind==="user"&&(P.provisional===!0||P.local===!0)&&!v.has(P.id)):[],A=n.replace?p.length>0?{...Lt,records:p,index:It(p)}:Lt:{...r,records:b},k=new Map(A.records.map(P=>[P.id,P]));let T=r!==o||n.replace||!n.replace&&b!==r.records;for(const P of h){const z=k.get(P.id);if(!z){T=!0,k.set(P.id,P);continue}if(z.kind==="tool"&&P.kind==="tool"){const Z={...P,args:P.args??z.args,intent:P.intent??z.intent,images:nm(P.images,z.images,"current")};tc(z,Z)||(T=!0,k.set(P.id,Z));continue}tc(z,P)||(T=!0,k.set(P.id,P))}const F=r.compacting&&t.entries.some(P=>r.index.has(P.id)||Math.round((P.ts??0)*1e3)<r.compactingSince?!1:P.type==="compaction"||P.type==="message"&&P.payload?.custom_type==="compaction_refused"),C=t.entries[0],I=C?Math.round((C.ts??0)*1e3):0,g=r.journalMode?_n:DE(A.records,I,n.statedByOwner!==!1);let w=A.oldestId,S=A.oldestTs,x=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(C&&(w=C.id,S=I),x=t.has_more):n.pagedBefore!==void 0?C?(w=C.id,S=I,x=t.has_more):x=!1:C&&(r.journalMode?(r.journalPositions?.get(C.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):I>0&&I<r.oldestTs)&&(w=C.id,S=I,x=t.has_more));const N=w!==r.oldestId||S!==r.oldestTs;if(!T&&!N&&r.hasMore===x&&!F&&g.size===0)return c(r);const J=g.size===0?[...k.values()]:[...k.values()].map(P=>g.has(P.id)?LE(P):P),M=im(Uo(J,n.statedByOwner===!1?_n:new Set(h.map(P=>P.id)),r));return n.keepPaging?c({...r,records:M,index:It(M),argsByCall:m}):c({...r,records:M,index:It(M),oldestId:w,oldestTs:S,hasMore:x,argsByCall:m,compacting:F?!1:r.compacting,compactingSince:F?0:r.compactingSince})}const wA=/^(?:local|notice|retry|subagent|compaction):/;function pl(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!wA.test(e.id)}}function kA(e,t,n=_n){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(o=>!(o.ts<t.ts&&pl(o)&&!n.has(o.id)));return r.length===e.records.length?e:{...e,records:r,index:It(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const on={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function sa(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function nc(e,t,n=Date.now(),r={}){let o=e;const s=t.message;if(t.type==="journal_order_ready"){const l=typeof t.journal_generation=="string"?t.journal_generation:void 0;if(o={...o,orderNeedsReconcile:!0,orderWantedGeneration:t.reconcile===!0?void 0:l,orderDemand:t.reconcile===!0?{}:{generation:l}},t.reconcile===!0)return o;const d=Lr(o,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=Uo(d.records,_n,d);return d===o&&u===o.records?o:{...d,records:u,index:It(u)}}s&&(o=Zc(o,s));const a=r.frame,c=r.queuedAskEngine;switch(t.type){case"agent_start":{const l=Number(t.generation??o.generation+1);return l===o.generation?o:{...o,generation:l,compacting:!1,compactingSince:0}}case"compaction_start":return o.compacting?o:{...o,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??o.generation)<o.generation)return o;let d=o;for(const u of o.records)if(u.kind==="assistant"&&u.streaming&&(d=Ne(d,{...u,streaming:!1,settledAt:n,callsTools:!1,stopReason:t.aborted?"aborted":u.stopReason})),u.kind==="tool"&&u.phase!=="done"){const f=u.phase==="composing"||u.phase==="queued";d=Ne(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=sa(s);if(s===void 0||l===null)return on.idlessFrameRefused+=1,o;const d=o.records[o.index.get(l)??-1];if(s.role==="user"){const u=dm(s.provider_payload);if(u){const b=Yt(s),v=Za({...u,text:b});if(v.body.trim()){const p=d?.kind==="user"&&d.provisional===!0;return Ne(o,{kind:"custom",id:l,ts:p?ri(o,n):n,customType:"hub_message",text:v.envelope,attribution:"user",...Ps("hub_message",v.envelope||v.body,{...u}),receipt:v,images:Jn(s,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(fm(s.provider_payload))return o;const f=Yt(s);if(Uh(f))return o;const h=d?.kind==="user"&&d.provisional===!0,m=tm(s,l,d?.kind==="user"?d.documents:void 0),y=vi(f);return Ne(o,{kind:"user",id:l,ts:h?ri(o,n):n,text:f,images:Jn(s,l,d?.kind==="user"?d.images:void 0),...m.length?{documents:m}:{},...h?{provisional:!0}:{},...y?{skill:y}:{}})}return s.role!=="assistant"||d?o:Ne(o,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=sa(s);if(s===void 0||l===null)return on.idlessFrameRefused+=1,o;const d=o.index.get(l),u=String(t.delta??""),f=Yt(s);if(d===void 0)return!f&&!u?o:Ne(o,{kind:"assistant",id:l,ts:n,text:f?f+u:u,streaming:!0,truncated:f===""?"prefix":void 0,...a?{frame:a}:{},stopReason:null,error:!1});const h=o.records[d];if(h.kind!=="assistant")return o;if(!h.streaming)return on.settledAssistantUpdate+=1,o;if(r.seed!==!0&&a&&h.frame&&a.epoch===h.frame.epoch&&a.seq<=h.frame.seq)return on.staleUpdateFrameDropped+=1,o;const m=NE(h.frame,a);if(r.seed===!0&&!f)return!h.text&&!u?o:(on.seededDeltaWithheld+=h.text?1:0,Ne(o,{...h,text:h.text||u,...m?{frame:m}:{},truncated:h.text?"interrupted":"prefix"}));let y;if(f){if(y=f+u,y.length<=h.text.length)return o}else{if(!u)return o;y=h.text+u}return Ne(o,{...h,text:y,...m?{frame:m}:{},truncated:f?void 0:h.truncated})}case"message_end":{const l=sa(s);if(s===void 0)return on.idlessFrameRefused+=1,o;if(l===null){if(s.role!=="assistant")return on.idlessFrameRefused+=1,o;let y;for(const p of o.records)if(!(p.kind!=="assistant"||!p.streaming)){if(y!==void 0)return on.idlessFrameRefused+=1,o;y=p}if(y===void 0)return on.idlessFrameRefused+=1,o;const b=Array.isArray(s.tool_calls)?s.tool_calls:[],v={...y,streaming:!1,settledAt:y.settledAt??n,callsTools:b.length>0,...y.text||b.length===0?{complete:!0}:{}};return Ne(o,v)}if(s.role!=="assistant")return o;const d=o.index.get(l),u=Yt(s),f=d===void 0?void 0:o.records[d],h=Array.isArray(s.tool_calls)?s.tool_calls:[],m={kind:"assistant",id:l,ts:d===void 0?n:o.records[d].ts,text:u,...u||h.length===0?{complete:!0}:{},streaming:!1,callsTools:h.length>0,settledAt:f?.kind==="assistant"&&f.settledAt!==void 0?f.settledAt:n,stopReason:s.stop_reason??null,error:!!s.is_error,...a?{frame:a}:{}};return Ne(o,m)}case"history_delta":{const d=(Array.isArray(t.messages)?t.messages:[]).filter(k=>String(k.id??"")!==""),u=typeof t.journal_generation=="string"&&t.journal_generation.length>0?t.journal_generation:void 0,f=t.journal_ordinals&&typeof t.journal_ordinals=="object"&&!Array.isArray(t.journal_ordinals)?t.journal_ordinals:void 0,h=t.entry_times&&typeof t.entry_times=="object"&&!Array.isArray(t.entry_times)?t.entry_times:void 0,m="journal_generation"in t||"journal_ordinals"in t||"entry_times"in t,y=o.journalPeerSource===!0||m,b=y&&u!==void 0&&u===o.journalGeneration,v=d.map(k=>String(k.id??"")).filter(k=>k.length>0&&k.length<=128),p={entries:d.map(k=>{const T=String(k.id??""),F=f?.[T],C=h?.[T];return{id:T,ts:b&&typeof C=="number"&&Number.isFinite(C)?C:n/1e3,type:"message",payload:{kind:k.custom_type?"custom":"message",...k},...b&&Bo(F)?{journal_seq:F}:{}}}),has_more:o.hasMore,...b?{journal_generation:u}:{}};let A=vo(o,p,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:y});if(y&&v.length>0)if(b){const k=v.filter(T=>!Bo(f?.[T]));k.length>0&&(A=Pu(A,k))}else A=Pu(A,v),u!==void 0&&(A=Lr(A,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),A=qo(A,!0));return A}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return o;const d=String(t.supersedes_tool_call_id??""),u=`tool:${l}`,f=o.records[o.index.get(u)??-1],h=d?o.records[o.index.get(`tool:${d}`)??-1]:void 0,m=f?.kind==="tool"?f:h?.kind==="tool"?h:void 0;if(m&&m.phase!=="composing"&&m.phase!=="queued")return d&&f?.kind==="tool"?oa(o,d):o;const b=String(t.not_run_reason??"").trim()||null,v=String(t.not_run_kind??"").trim()||null;if(Ou(t.tool_name,c)&&!b&&!m)return d?oa(o,d):o;const p=Number(t.argument_bytes??0),A={kind:"tool",id:u,ts:m?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:b?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:p>0?p:m?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:_o,added:0,removed:0,diff:null,diffTruncatedRows:0,stopped:!1,notRunReason:b,notRunKind:b?v:null,neverSent:b!==null};return d&&h?.kind==="tool"&&f?.kind!=="tool"?UE(o,d,A):Ne(d&&f?.kind==="tool"?oa(o,d):o,A)}case"tool_execution_start":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1];if(u&&u.kind==="tool"&&u.phase==="done"&&!u.notRunReason)return o;const f=xu(o,l,t,u),h=f&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:f,anchoredAt:Mr(t)??n}):o.argsByCall,m=h===o.argsByCall?o:{...o,argsByCall:h};return Ou(t.tool_name,c)&&!u?m:Ne(m,{kind:"tool",id:d,ts:u?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??(typeof f?.i=="string"?f.i:null),args:f,phase:"running",notRunReason:null,notRunKind:null,neverSent:!1,argumentBytes:0,output:null,isError:!1,durationS:null,startedAt:Mr(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:_o,added:0,removed:0,diff:u?.kind==="tool"?u.diff:null,diffTruncatedRows:u?.kind==="tool"?u.diffTruncatedRows??0:0,details:u?.kind==="tool"?u.details??null:null,stopped:!1})}case"tool_execution_update":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1];if(!u||u.kind!=="tool")return o;const f=t.partial_result??{},h=Th(f.details,u.details);return h===(u.details??null)?o:Ne(o,{...u,details:h})}case"tool_execution_end":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1],f=t.result??{};if(hm(f.details))return wm(o,d);const h=xu(o,l,t,u),m=u&&u.kind==="tool"?u:{kind:"tool",id:d,ts:n,toolCallId:l,toolName:String(t.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:_o,added:0,removed:0,diff:null,diffTruncatedRows:0,stopped:!1},y=h&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:h,anchoredAt:Mr(t)??n}):o.argsByCall,b=y===o.argsByCall?o:{...o,argsByCall:y},v=r.userStoppedAt??null,p=!!(t.is_error??f.is_error),A=Xh(f.details?.__fault),k=v!==null&&(typeof m.startedAt=="number"?m.startedAt<=v:p);return Ne(b,{...m,args:h,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:Yt(f)||null,isError:k||A?!1:p,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof m.startedAt=="number"?m.startedAt+t.duration_s*1e3:null,startedAt:null,images:$E(Jn(f,d,m.images),m.images),...Dh(f.details,m),diff:Nh($h(f.details),m.diff),diffTruncatedRows:Lh(f.details,m.diffTruncatedRows??0),stopped:m.stopped||k||A,delivery:xh(f.details,m.delivery,m.toolName),bridge:Sh(m.toolName,f.details,m.bridge),bridgeLabel:Eh(m.toolName,f.details,m.bridgeLabel),details:Fh(m.toolName,f.details,m.details)})}case"supplement_progress":{const l=RE(t);if(!l)return o;const d=il(l.anchor),u=o.records[o.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,h=Qh(f,l,n);return h?Ne(o,h):o}case"notice":{const l=String(t.text??"");if(!l)return o;const d=`notice:${o.generation}:${l}`;return o.index.has(d)?o:Ne(o,{kind:"notice",id:d,ts:n,text:l,level:t.kind??"info"})}case"compaction_end":{const l=Number(t.tokens_before??0),d=Number(t.tokens_after??0),f=!!t.success?null:om(String(t.detail??"")),h=f?f.text:l&&d?HE(l,d):sm,m=`compaction:${o.generation}:${l}:${d}`,y=o.compacting?{...o,compacting:!1,compactingSince:0}:o;return y.index.has(m)?y:f?Ne(y,{kind:"notice",id:m,ts:n,text:h,copy:f.copy,level:f.level}):GE(Ne(y,{kind:"compaction",id:m,ts:n,text:h,before:l}))}case"retry_start":{const l=`Retrying after an error (attempt ${String(t.attempt??"?")})${t.fallback_model?`, falling back to ${String(t.fallback_model)}`:""}`,d=`retry:${o.generation}:${String(t.attempt??"")}`;return o.index.has(d)?o:Ne(o,{kind:"notice",id:d,ts:n,text:l,level:"warning"})}case"subagent_end":{const l=`subagent:${String(t.job_id??"")}`,d=String(t.status??""),u=`${String(t.label??"Subagent")} ${d||"finished"}`,f=o.records[o.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?o:Ne(o,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return o}}function Mr(e){return sw(e.started_at_epoch)}function hl(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function SA(e){const t=hl(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function EA(e,t){const n=Mr(e);if(n!==null)return n;const r=hl(e);if(!r)return null;const o=t.argsByCall.get(r)?.anchoredAt;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}function AA(e,t){if(Mr(e)!==null)return!1;const n=hl(e);if(!n)return!1;const r=t.argsByCall.get(n)?.anchorId;if(typeof r!="string")return!1;const o=t.index.get(r);return o!==void 0&&o<=rm(t.records)}function ml(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 ki(e){return e.type==="tool_execution_end"}function IA(e,t,n=Date.now(),r=null){let o=e;t.streaming&&t.generation>o.generation&&(o={...o,generation:t.generation}),o.compacting&&(o={...o,compacting:!1,compactingSince:0});const s=t.streaming===!0,a=pm(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let h=n;const m=SA(f);if(m!==null&&!o.index.has(m)){const y=EA(f,o);if(y!==null)h=y,c=!0,AA(f,o)&&l.add(m);else if(ki(f)||ml(f)||!s)continue}o=nc(o,f,h,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return o;const d=Uo(o.records,l,o);return{...o,records:d,index:It(d)}}function ju(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!ki(r)&&!ml(r))continue;const o=String(r.tool_call_id??"");if(!o)continue;const s=Mr(r);s!==null&&t.set(o,s)}return t}function RA(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n;if(r.type!=="tool_call_compose")continue;const o=r.not_run_reason;if(typeof o=="string"&&o.trim().length>0)continue;const s=String(r.tool_call_id??"");s&&t.add(s)}return t}const xA=5e3;function TA(e,t){const n=new Set(t),r=new Map;if(n.size===0)return r;for(const o of e){if(o.payload?.role!=="tool")continue;const s=o.payload.tool_call_id;if(typeof s!="string"||!n.has(s))continue;const a=o.ts;typeof a!="number"||!Number.isFinite(a)||r.set(s,Math.round(a*1e3))}return r}function CA(e,t,n,r=new Map,o=new Set){const s=e[0]?.ts;if(typeof s!="number"||!Number.isFinite(s))return!1;let a=null;for(const l of t){const d=n.get(l);if(d===void 0){if(o.has(l))continue;return!1}(a===null||d<a)&&(a=d)}for(const l of r.values())(a===null||l<a)&&(a=l);return a===null?!1:Math.round(s*1e3)<=a-xA}function $u(e,t){const n=[];for(const r of e??[]){if(!r)continue;const o=r;if(!ki(o)&&!ml(o))continue;const s=String(o.tool_call_id??"");!s||n.includes(s)||t.has(s)||n.push(s)}return n}function Nu(e,t,n,r){const o=[],s=new Set;for(const a of t)s.has(a)||(s.add(a),!n.has(a)&&((e.get(a)??0)>=r||o.push(a)));return o}const OA=3.25,rc=100,gl=500;function Du(e){return e<=0?rc:Math.min(gl,rc+Math.ceil(OA*e))}function ia(e,t){const n=[];if(t.size===0)return n;for(const r of e){const o=r.payload?.tool_calls;if(Array.isArray(o))for(const s of o)s&&typeof s.id=="string"&&t.has(s.id)&&n.push(s.id)}return n}function PA(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function MA(e,t){const n=new Set(t);for(const s of e){const a=s.payload?.tool_calls;if(Array.isArray(a))for(const c of a)c&&typeof c.id=="string"&&n.add(c.id)}const r=[],o=new Set;for(const s of e){if(s.payload?.role!=="tool")continue;const a=s.payload.tool_call_id;typeof a!="string"||n.has(a)||o.has(a)||(o.add(a),r.push(a))}return r}function jA(e,t){return e&&t===0}function $A(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,o=r.not_run_reason,s=r.type==="tool_call_compose"&&typeof o=="string"&&o.trim().length>0;if(r.type!=="tool_execution_start"&&!ki(r)&&!s)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function vm(e,t,n){const r=new Set(e),o=[];for(const s of t)!r.has(s)&&!n.has(s)&&o.push(s);for(const s of e){if(n.has(s))return o;t.has(s)&&o.push(s)}return o}function NA(e,t,n){return vm(e,t,n).length}function Lu(e){let t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;for(const n of e.records)n.kind!=="assistant"||!n.streaming||n.truncated||(t=Ne(t,{...n,truncated:"interrupted"}));return t}function DA(e,t=Date.now()){return e.records.length===0&&!e.profileHistoryPending?.length?e:{...Lt,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function LA(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 Fu(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function FA(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return dl(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function ri(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function ym(e,t,n,r,o=Date.now(),s=ec){if(e.index.has(t))return e;const a=vi(n);return Ne(e,{kind:"user",id:t,ts:ri(e,o),text:n,images:r,...s.length?{documents:s}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function wm(e,t){return dl(e,n=>n.id===t)}let Uu=0;function UA(e,t,n,r=Date.now()){return Uu+=1,Ne(e,{kind:"notice",id:`local:${r}:${Uu}`,ts:ri(e,r),text:t,level:n})}function kj(e,t,n,r){const o=t?.anchor_id,s=t?.kind;if(!o||s!=="error"&&s!=="interrupted"&&s!=="closed"&&s!=="retired"||n||e.index.has(o)||!t?.unseen&&!r?.has(o))return e;r?.add(o);const a=s==="error"?{id:"stopped_with_error"}:s==="interrupted"?{id:"interrupted"}:void 0;return Ne(e,{kind:"notice",id:o,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:s==="closed"?am:s==="retired"?cm:wi(a),...a?{copy:a}:{},level:s==="closed"?"info":s==="retired"?"warning":s==="error"?"error":"warning"})}const BA="compacting context…";function Sj(e){return typeof e=="string"&&e.trim()===BA}const HA=[1500,5e3];async function Ej(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of HA){await t(n);try{if(await e())return}catch{}}}function WA(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 GA=["store","routed","request","snapshot","content","painted","sendable"],zA=6e4,KA="[open-trace]",VA=/^[A-Za-z0-9_-]{1,80}$/,ZA=["sidebar","open","native"];function YA(e,t,n){const r=VA.test(e.sessionId)?e.sessionId:"?",o=ZA.includes(e.entrance)?e.entrance:"open",s=u=>u===void 0?"-":String(Math.max(0,Math.round(u-e.start))),{painted:a,sendable:c}=e.stages,l=a!==void 0&&c!==void 0?Math.max(a,c):void 0,d=[KA,`t=${e.token}`,`clickEpochMs=${e.clickEpochMs??"-"}`,`session=${r}`,`via=${o}`,`outcome=${t}`,...GA.map(u=>`${u}=${s(e.stages[u])}`),`settled=${s(l)}`];return n!==void 0&&d.push(`by=t${n}`),d.join(" ")}function JA(e){let t=0,n=null;const r=(s,a)=>{const c=n;if(c){n=null,e.clearTimer(c.timer);for(const l of Object.keys(c.fallbacks))c.stages[l]===void 0&&(c.stages[l]=c.fallbacks[l]);e.log(YA(c,s,a));for(const l of c.endListeners.splice(0))l()}},o=(s,a)=>{s.stages[a]===void 0&&(s.stages[a]=e.now(),s.stages.painted!==void 0&&s.stages.sendable!==void 0&&r("settled"))};return{begin(s,a){t+=1;const c=t;n&&r("superseded",c);const l={token:c,sessionId:s,entrance:a,start:e.now(),clickEpochMs:performance.timeOrigin+performance.now(),stages:{},fallbacks:{},timer:void 0,frameRequested:!1,endListeners:[]};return l.timer=e.setTimer(()=>{n===l&&r("timeout")},zA),n=l,c},note(s,a,c,l){const d=n;if(!(!d||!s||d.sessionId!==s)&&!(c!==void 0&&c!==d.token)){if(l?.fallback===!0){d.stages[a]===void 0&&d.fallbacks[a]===void 0&&(d.fallbacks[a]=e.now());return}if(a==="content"&&!d.frameRequested){d.frameRequested=!0,o(d,"content"),e.nextFrame(()=>{n===d&&o(d,"painted")});return}a==="painted"||a==="content"||o(d,a)}},fail(s,a){!n||!s||n.sessionId!==s||r(a)},activeSessionId(){return n?.sessionId??null},currentToken(){return n?.token??null},onEnd(s,a){n?.token===s?n.endListeners.push(a):a()}}}const QA=typeof window<"u";function XA(e,t,n){t(()=>n(e))}const qA=e=>{const t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)},aa=JA({now:()=>performance.now(),nextFrame:e=>{QA&&typeof requestAnimationFrame=="function"&&typeof MessageChannel=="function"?XA(e,t=>requestAnimationFrame(()=>t()),qA):setTimeout(e,0)},log:e=>console.warn(e),setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e)});function Aj(e,t,n,r){let o=!1;const s=()=>{const c=e.activeSessionId();if(c===null||e.currentToken()!==t)return;const l=n();if(l.activeSessionId!==c||l.activeDraftKey){o&&e.fail(c,"left");return}o=!0,e.note(c,"store"),l.validatingSessionId!==c&&e.note(c,"sendable")},a=r(s);e.onEnd(t,a),s()}const Bu=new Set(["openrouter","radient","radient-key"]),eI=new Set(["auto","openrouter/auto"]),tI=()=>_("ui.chat.session_readout.model.router_auto");function km(e){return e.slice(e.lastIndexOf("/")+1)||e}function nI(e,t){return e===t||e===km(t)}function oc(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 rI(e,t){return t?oc(e?.selected_model)===t||oc(e?.effective_model)===t:!1}function Ij(e){if(!e||typeof e.model_id!="string"||!e.model_id)return null;const t=typeof e.provider=="string"?e.provider:"",n=t?`${t}/${e.model_id}`:e.model_id,r=typeof e.display_name=="string"?e.display_name.trim():"",o=Bu.has(t)||!r||nI(r,e.model_id)||r.toLowerCase()==="unknown";return{name:Bu.has(t)&&eI.has(e.model_id)?tI():o?km(n):r,selector:n}}function Rj(e,t,n=null){const r=e?.effective_model??e?.selected_model??null,o=n&&r?{...r,reasoning_effort:n}:r;return{identity:t??r,effort:o}}function xj(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function Tj(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function Cj(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 Oj(e){const t=e?.effort_displacement,n=t?.note;if(typeof n!="string"||!n.trim())return null;const r=new Map;for(const a of[e?.effective_model,e?.selected_model]){const c=typeof a?.display_name=="string"?a.display_name.trim():"";if(!a||!c||!a.provider||!a.model_id)continue;const l=`${a.provider}/${a.model_id}`;l!==t?.serving&&l!==t?.selected||r.set(l,c)}if(!r.size)return n.trim();const o=[...r.keys()].sort((a,c)=>c.length-a.length).map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),s=new RegExp(`(^|[\\s(])(${o.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(s,(a,c,l)=>`${c}${r.get(l)}`)}function Pj(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function oI(e){const t=e.trim();return t&&(Sm(t)??t)}const Hu=new Map;function Sm(e){const t=nn();let n=Hu.get(t);return n===void 0&&(n={auto:_("ui.chat.session_readout.effort.level.auto"),none:_("ui.chat.session_readout.effort.level.none"),minimal:_("ui.chat.session_readout.effort.level.minimal"),low:_("ui.chat.session_status.effort_level.low"),medium:_("ui.chat.session_status.effort_level.medium"),high:_("ui.chat.session_status.effort_level.high"),xhigh:_("ui.chat.session_readout.effort.level.xhigh"),max:_("ui.chat.session_readout.effort.level.max"),unknown:_("ui.chat.session_readout.effort.level.unknown"),reasoning:_("ui.chat.session_readout.effort.level.reasoning")},Hu.set(t,n)),n[e.toLowerCase()]}const uo=e=>oI(e).toLowerCase(),vs=e=>{const t=Sm(e.trim());return t===void 0?e:t.toLowerCase()};function Em(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 Mj(e,t){const n=(e??t)?.effective_model;return Em(n)?null:n?.model_id??null}function jj(e){if(!e)return null;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim().toLowerCase():"",n=Array.isArray(e.reasoning_efforts)?e.reasoning_efforts.filter(s=>typeof s=="string"):null,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",o=Em(e);return t?{label:t,adjustable:n===null||n.length>0,knownLadder:!!(n&&n.length>0),levelKnown:!0,detail:n&&n.length>0?_("ui.chat.session_readout.effort.detail.offers",{levels:Ts(n.map(uo))}):_("ui.chat.session_readout.effort.detail.session")}:n&&n.length>0?{label:"auto",adjustable:!0,knownLadder:!0,levelKnown:!0,detail:r?_("ui.chat.session_readout.effort.detail.auto_with_default",{default:uo(r),levels:Ts(n.map(uo))}):_("ui.chat.session_readout.effort.detail.auto",{levels:Ts(n.map(uo))})}:o?{label:"unknown",adjustable:!0,knownLadder:!1,levelKnown:!1,detail:_("ui.chat.session_readout.effort.detail.not_reported",{command:"/effort <level>"})}:n&&e.reasoning?{label:"reasoning",adjustable:!1,knownLadder:!0,levelKnown:!0,detail:_("ui.chat.session_readout.effort.detail.no_levels")}:n===null&&r?{label:r,adjustable:!1,knownLadder:!1,levelKnown:!0,detail:_("ui.chat.session_readout.effort.detail.default_only")}:null}function $j(e,t){if(!e)return null;if(!t||t.length===0||e.knownLadder)return e;const n=t.map(r=>typeof r=="object"&&r!==null&&"value"in r?String(r.value):"").filter(Boolean);return n.length===0?e:{...e,adjustable:!0,detail:_("ui.chat.session_readout.effort.detail.offers",{levels:Ts(n.map(uo))})}}function sI(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=eo(n.provider);if(!a)return null;const c=eo(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:eo(n.label)||a,effectiveState:d,owner:eo(n.owner_label)||eo(n.owner_device)||_("ui.chat.session_readout.access.owner_fallback"),observedAt:ca(n.observed_at),lastGrantAt:ca(n.last_grant_at),lastGrantExpiresAt:ca(n.last_grant_expires_at)}}if(!n||n.state!=="signed_out"&&n.state!=="temporarily_unavailable")return null;const r=typeof n.provider=="string"?n.provider:"";if(!r)return null;const o=e?.effective_model?.provider;if(o&&o!==r)return null;const s=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:s,state:n.state}:{provider:r,label:s}}function Nj(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function Dj(e){return e&&e.draft!==!0?sI(e.frontend,e.servingLocality):null}function eo(e){return typeof e=="string"?e.trim():""}function ca(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function la(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function Lj(e){const{label:t,effectiveState:n}=e,r=e.owner||_("ui.chat.session_readout.access.owner_fallback"),o={local:[_("ui.chat.session_readout.access.local.title",{label:t}),_("ui.chat.session_readout.access.local.description")],pending:[_("ui.chat.session_readout.access.pending.title",{label:t}),_("ui.chat.session_readout.access.pending.description")],eligible_borrow_unverified:[_("ui.chat.session_readout.access.eligible_borrow_unverified.title",{owner:r}),_("ui.chat.session_readout.access.eligible_borrow_unverified.description",{label:t,owner:r})],effective_borrow:[_("ui.chat.session_readout.access.effective_borrow.title",{label:t,owner:r}),_("ui.chat.session_readout.access.effective_borrow.description")],expired:[_("ui.chat.session_readout.access.expired.title",{label:t}),_("ui.chat.session_readout.access.expired.description",{owner:r})],withdrawn:[_("ui.chat.session_readout.access.withdrawn.title",{label:t}),_("ui.chat.session_readout.access.withdrawn.description")],owner_unavailable:[_("ui.chat.session_readout.access.owner_unavailable.title",{owner:r}),_("ui.chat.session_readout.access.owner_unavailable.description",{label:t,owner:r})],device_bound:[_("ui.chat.session_readout.access.device_bound.title",{label:t}),_("ui.chat.session_readout.access.device_bound.description")],absent:[_("ui.chat.session_readout.access.absent.title",{label:t}),e.connectHere===!0?_("ui.chat.session_readout.access.absent.description_connect"):_("ui.chat.session_readout.access.absent.description_remote")]},s=e.state==="temporarily_unavailable",[a,c]=n?o[n]:[s?_("ui.chat.session_status.temporarily_unavailable",{label:t}):_("ui.chat.session_status.not_signed_in",{label:t}),s?_("ui.chat.session_status.temporarily_unavailable_description"):_("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];n&&e.observedAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.last_checked",{time:la(e.observedAt)})),n&&e.lastGrantAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.last_resolved",{time:la(e.lastGrantAt)})),n&&e.lastGrantExpiresAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.grant_expiry",{time:la(e.lastGrantExpiresAt)}));const d=[...l];return n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push(_("ui.chat.session_readout.access.history.only")),{title:a,description:c,history:l.join(" "),historyLines:d,tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!s,canSwitchModel:n!=="effective_borrow"}}function Fj(e){switch(e?.effectiveState){case"effective_borrow":case"pending":case"eligible_borrow_unverified":return!0;default:return!1}}function Uj(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="not-cleared"||e.kind==="settled"&&e.canRetry}function Bj(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function Hj(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function iI(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function aI(e,t){return!!e.streams[t]}function Am(e,t){return e.attached[t]?.turns.at(-1)}function Wj(e,t){const n=Am(e,t);return n?e.streams[n.asideId]:void 0}function Gj(e,t){const n=e.attached[t]?.turns??[];for(let r=n.length-1;r>=0;r-=1){const o=n[r];if(o&&e.streams[o.asideId]?.settled)return o.asideId}}function cI(){return{text:"",streaming:!0,settled:!1,error:null}}function lI(e){return{text:e,streaming:!1,settled:!0,error:null}}function dI(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const uI=Qo(e=>({streams:{},attached:{},attachAside:t=>e(n=>{const r=n.attached[t];return r&&r.notice===null?n:{attached:{...n.attached,[t]:r?{...r,notice:null}:{turns:[],notice:null}}}}),beginAsk:(t,n,r)=>e(o=>({streams:{...o.streams,[n]:cI()},attached:{...o.attached,[t]:{turns:[...o.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const o=iI(r.streams[t],n);return o?{streams:{...r.streams,[t]:o}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:lI(n)}}:r),failAside:(t,n)=>e(r=>aI(r,t)?{streams:{...r.streams,[t]:dI(r.streams[t],n)}}:r),setAsideNotice:(t,n)=>e(r=>{const o=r.attached[t];return o?{attached:{...r.attached,[t]:{...o,notice:n}}}:r}),queueAdoption:(t,n,r)=>e(o=>{const s=o.attached[t];return s?{attached:{...o.attached,[t]:{...s,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:o}),unqueueAdoption:(t,n,r)=>e(o=>{const s=o.attached[t];if(s?.queued?.asideId!==n)return o;const{queued:a,...c}=s;return{attached:{...o.attached,[t]:{...c,notice:r}}}}),detachAside:t=>e(n=>{const r=n.attached[t],o={...n.attached};if(delete o[t],!r)return{attached:o};const s={...n.streams};for(const a of r.turns)delete s[a.asideId];return{streams:s,attached:o}})}));function zj(e,t){return Am(e,t)?.asideId}const fI=4*1024*1024,Wu=1024*1024,Jt=new Map;function Gu(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function pI(e){const t=e.slice(-200),n=Gu(t);if(n<=Wu)return{records:t,bytes:n};let r=0,o=t.length,s=0;for(;o-r>1;){const a=Math.floor((r+o)/2),c=Gu(t.slice(a));c>Wu?r=a:(o=a,s=c)}return{records:t.slice(o),bytes:s}}function hI(e,t){const{records:n,bytes:r}=pI(FA(t.transcript).records);if(n.length===0){Jt.delete(e);return}const o={...t.transcript,records:n,index:new Map(n.map((a,c)=>[a.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},s={transcript:o,savedAt:Date.now(),bytes:r,owedLabels:zu(n,t.owedLabels),markLabels:zu(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>o.index.has(a)))};Jt.delete(e),Jt.set(e,s),gI()}function zu(e,t){if(!t||t.size===0)return Ku;const n=new Set;for(const r of e)r.kind!=="tool"||r.args||r.toolCallId&&t.has(r.toolCallId)&&n.add(r.toolCallId);return n.size>0?n:Ku}const Ku=new Set;function Im(e){const t=Jt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function mI(e){Jt.delete(e)}function gI(){let e=0;for(const t of Jt.values())e+=t.bytes;for(;e>fI&&Jt.size>0;){const t=Jt.keys().next().value;if(t===void 0)break;const n=Jt.get(t);Jt.delete(t),e-=n?.bytes??0}}const _I=8,bI=128,Rm=new Set,vI="",an=new Map,_l=e=>e??vI;function Kj(e){return an.get(_l(e))??Rm}function Vj(e,t,n){const r=_l(e),o=an.get(r)??new Set,s=new Set(o);if(n)for(s.delete(t),s.add(t);s.size>bI;){const a=s.values().next().value;if(a===void 0)break;s.delete(a)}else s.delete(t);for(an.delete(r),s.size>0&&an.set(r,s);an.size>_I;){const a=an.keys().next().value;if(a===void 0)break;an.delete(a)}return an.get(r)??Rm}function yI(e){an.delete(_l(e))}const wI=128,oi=4096,da=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),Vu=e=>e.startsWith("qg:")&&e.length>3;function Zj(e,t,n=null,r=[]){const o=new Map,s=new Map;for(let c=0;c<e.length;c+=1){const l=e[c];for(let d=0;d<l.segmentIds.length;d+=1){const u=l.segmentIds[d];if(o.has(u))return da("duplicate-prior-id");if(o.size===oi)return da("prior-id-limit");o.set(u,{ordinal:c,order:d})}l.eligible!==!1&&Vu(l.key)&&t.has(l.key)&&s.size<wI&&s.set(c,l.key)}for(const c of r)if(!o.has(c)){if(o.size===oi)return da("prior-id-limit");o.set(c,{ordinal:-1,order:-1})}const a=n===null?void 0:o.get(n);if(a!==void 0&&a.ordinal>=0){const c=e[a.ordinal];c.eligible!==!1&&Vu(c.key)&&s.set(a.ordinal,c.key)}return{complete:!0,owners:o,keys:s,reason:null}}function Yj(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>oi)return r("prior-id-limit");const o=new Set,s=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,h,m)=>{const y=a.get(f);y===void 0?a.set(f,{current:h,many:!1,lastOrder:m,reordered:!1,outside:!1}):(y.current!==h&&(y.many=!0),m<=y.lastOrder&&(y.reordered=!0),y.lastOrder=m)};for(let f=0;f<t.length;f+=1){const h=t[f];let m=null,y=!1;for(const v of h.segmentIds){if(s!==null){if(s.has(v))return r("duplicate-current-id");if(s.size===oi)return r("current-uniqueness-unproved");s.add(v)}const p=e.owners.get(v);if(p!==void 0){if(o.has(v))return r("duplicate-current-id");o.add(v),l(p.ordinal,f,p.order),m===null?m=p.ordinal:m!==p.ordinal&&(y=!0)}}if(h.eligible===!1||y||m===null||m<0)continue;const b=e.keys.get(m);b!==void 0&&c.set(f,{owner:m,key:b})}for(const f of n.outsideCurrentIds??[]){const h=e.owners.get(f);if(h===void 0||o.has(f))continue;const m=a.get(h.ordinal);m!==void 0&&(m.outside=!0)}for(const[f,h]of c){const m=a.get(h.owner),y=h.key.slice(3);(m===void 0||m.many||m.reordered||m.outside||!o.has(y))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const h=c.get(f)?.key??t[f].key;if(d.has(h)){if(u.has(h))return r("key-collision");u.add(h)}}return{episodes:t.map((f,h)=>{const m=c.get(h);return m===void 0?f:{...f,key:m.key}}),reason:null}}const kI=8,SI="",Yn=new Map,bl=e=>e??SI;function Jj(e){return Yn.get(bl(e))??null}function Qj(e,t){const n=bl(e);for(Yn.delete(n),Yn.set(n,t);Yn.size>kI;){const r=Yn.keys().next().value;if(r===void 0)break;Yn.delete(r)}}function EI(e){Yn.delete(bl(e))}function AI(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const o=n.getTranscript().orderRevision??0,s=()=>(n.getTranscript().orderRevision??0)===o;try{let a=r,c=await n.readPage(a);if(!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing){const u=gA(n.getTranscript()),f=u!==null&&u!==a?u:hA(c,a);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(a=f,c=await n.readPage(a),!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing)return{kind:"failed",reason:"cursor-missing"}}let l=n.getTranscript();const d=n.commit(u=>(l=u,(u.orderRevision??0)!==o?u:vo(u,c,{...u.oldestId===r?{pagedBefore:a}:{},...n.peerSource?.()===!0?{peerSource:!0}:{}})));return(d.orderRevision??0)!==o||c.journal_generation!==void 0&&c.journal_generation!==d.journalGeneration?{kind:"stale"}:{kind:"applied",newRecords:Math.max(0,d.records.length-l.records.length),exhausted:!d.hasMore}}catch{return{kind:"failed",reason:"request"}}finally{n.setLoading?.(!1)}};return{busy:n=>e!==null&&e.key===n,load(n,r){if(e!==null&&e.key===n)return e.promise;const o=r.getTranscript();if(!o.hasMore||!o.oldestId)return Promise.resolve({kind:"nothing-to-load"});const s={key:n,promise:t(r,o.oldestId)};e=s;const a=()=>{e===s&&(e=null)};return s.promise.then(a,a),s.promise}}}const II={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"},RI={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function vl(e){return{kind:e,statement:_(II[e]),action:RI[e]}}function Zu(e){return vl(cw(e))}const xI=()=>vl("historyUnreadable"),TI=new Set(["subagent_start","subagent_progress","subagent_end"]),CI=(e,t)=>({...e,[t]:(e[t]??0)+1}),OI=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=xm(n);r&&(t[r]=(t[r]??0)+1)}return t},xm=e=>{if(!e||typeof e!="object")return null;const t=e;return TI.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},PI=(e,t)=>{const n=xm(t);return n?CI(e,n):e};function Yu(e,t,n){if(!n||!e)return{};const r=e.context_tokens;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return{};const o=t.context_tokens;return typeof o=="number"&&Number.isFinite(o)&&o>=r?{}:{context_tokens:r,context_is_estimate:e.context_is_estimate??t.context_is_estimate,context_window:e.context_window??t.context_window,last_usage:e.last_usage??null}}function MI(e){for(const t of e)t.type==="aside_delta"&&uI.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function jI(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const zn=new Set,fo=new Set;function $I(e,t){let n=null;for(const r of t)e.has(r)&&(n=n??new Set(e),n.delete(r));return n??e}const NI=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),DI=15e3,sc=[500,1e3,2e3,4e3,8e3,8e3],LI=sc.length,FI=2e4,UI=1e4,BI=1e4;function Ju(e){const t=Math.max(1,Math.min(e,sc.length));return sc[t-1]??8e3}const HI=3,WI=250,GI=32*1024,Qu=512,Xu=new Set(["turn_end","agent_end"]),qu=2,zI=500,ef=gl,KI=6,ua=Np("sessions.history"),VI=2e3,tf={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},tr=new Map,Ms=new Map,ZI=8,YI=2048,nf=1024,JI=1024,QI="",Hn=new Map;function rf(e){const t=e??QI,n=Hn.get(t);if(n)return Hn.delete(t),Hn.set(t,n),n;const r={attempts:new Map,painted:new Set,inFlight:new Set,refused:!1,depth:0,order:[],starts:new Map,waiting:new Set,settled:new Set,settleRows:0};for(Hn.set(t,r);Hn.size>ZI;){const o=Hn.keys().next().value;if(o===void 0||o===t)break;Hn.delete(o)}return r}function fa(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function pa(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function XI(e,t){return Ms.set(e,t),()=>{Ms.get(e)===t&&Ms.delete(e)}}function Xj(e){const t=Ms.get(e);return t?(t(),!0):!1}const Qe=new Map,qI=4,eR=16;function Tm(e,t){e(n=>ym(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function tR(e,t,n){const r=e.index.get(t),o=r===void 0?void 0:e.records[r];if(r===void 0||!o||o.kind!=="user"||!o.local||o.text===n)return e;const s=e.records.slice(),{skill:a,...c}=o,l=vi(n);return s[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:s}}function ic(e,t){let n=Qe.get(e);if(!n){if(Qe.size>=eR){const s=Qe.keys().next();s.done||Qe.delete(s.value)}n=new Map,Qe.set(e,n)}const r={identity:e,id:t.id,text:t.text,images:t.images,documents:t.documents??[],onPainted:t.onPainted,settled:t.settled,submittedAt:t.submittedAt};for(n.set(r.id,r);n.size>qI;){const s=n.keys().next();if(s.done)break;n.delete(s.value)}const o=tr.get(e);o&&Tm(o,r)}function qj(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 ac(e,t){const n=Qe.get(e);n&&(n.delete(t),n.size===0&&Qe.delete(e))}function cc(e,t){const n=Qe.get(e)?.get(t);n&&(n.settled=!0)}function of(e,t){return e?Qe.get(e)?.has(t)===!0:!1}function e$(e){return e?(Qe.get(e)?.size??0)>0:!1}function nR(e,t,n){const r=Qe.get(e)?.get(t);if(!r)return;r.text=n;const o=tr.get(e);o&&o(s=>tR(s,t,n))}function rR(e,t){if(e===t)return;const n=Qe.get(e);if(!n)return;Qe.delete(e);const r=Qe.get(t)??new Map;for(const[o,s]of n)s.identity=t,r.set(o,s);Qe.set(t,r)}function ys(e){Qe.delete(e)}function oR(e,t){const n=Qe.get(e);if(n)for(const r of[...n.keys()]){const o=t.index.get(r),s=o===void 0?void 0:t.records[o];s?.kind==="user"&&s.local!==!0&&ac(e,r)}}function sR(e,t){tr.set(e,t);const n=Qe.get(e);if(n)for(const r of n.values())Tm(t,r);return()=>{tr.get(e)===t&&tr.delete(e)}}function iR(e,t){const n=Qe.get(e);if(!n)return t;let r=t;for(const o of n.values())r=ym(r,o.id,o.text,o.images,void 0,o.documents);return r}function aR(e,t,n,r=!0){return e===t||!r?!0:!n}function cR(e,t){const n=tr.get(e);if(!n)return ac(e,t),"queued";let r="queued";return n(o=>{const s=o.records[o.index.get(t)??-1];return!s||s.kind!=="user"?o:s.local?(r="retracted",wm(o,t)):(r="owner",o)}),ac(e,t),r}function Cm(e,t){const n=tr.get(e);if(!n)return"unseen";let r="unseen";return n(o=>{const s=o.records[o.index.get(t)??-1];return!s||s.kind!=="user"||(r=s.local?"local":"owner"),o}),r}function lR(e){const t=Im(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:Lt,stale:!1,owedLabels:zn,markLabels:fo}}function dR(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function ha(e,t){if(e.size!==0)for(const n of t)e.delete(Dt(n))}function ws(e,t){for(const n of t)e.add(Dt(n))}const sf=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function t$(e,t,n=!0,r=e,o={}){const s=o.openFrame===!0,a=o.journalOrder===!0,c=R.useRef(a);c.current=a;const l=R.useRef(s);l.current=s;const d=o.peerJournalSource===!0,u=R.useRef(d);u.current=d;const f=R.useRef(null),h=R.useRef(0),m=R.useRef(0),y=R.useRef(0),b=R.useRef(null),v=R.useRef(null),p=R.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const D=St.getState();return hx(D.sessions,D.placementFacts,e)},[e]),A=R.useCallback(()=>{const D=f.current;return p()&&D!==null&&D.sessionId===e&&D.peer},[p,e]),k=R.useCallback(()=>{const D=f.current;return D!==null&&D.sessionId===e&&D.peer},[e]),[T,F]=R.useState(()=>{const D=t&&e?lR(e):null;return{status:"connecting",frontend:null,heldFrontend:null,contextCarried:!1,pendingModel:null,history:null,cold:!1,subscriptionId:null,ownerEpoch:null,receipt:null,terminal:null,turnsCompleted:0,failure:null,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:r?iR(r,D?.transcript??Lt):Lt,stale:D?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:D?.owedLabels??zn,labelMarked:D?.markLabels??fo,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),C=R.useRef(T),I=R.useCallback(D=>{const ee=D(C.current);return ee===C.current||(C.current=ee,F(ee)),ee},[]);R.useEffect(()=>l_(()=>{I(D=>{const{failure:ee}=D;if(!ee?.kind)return D;const he=vl(ee.kind);return he.statement===ee.statement&&he.action===ee.action?D:{...D,failure:he}})}),[I]);const g=R.useRef(e),w=R.useRef(n),S=R.useRef([]),x=R.useRef(Lt.index),N=R.useRef(new Set),J=R.useRef(new Set),M=R.useRef(rf(e)),P=R.useRef(new Set),z=R.useRef(null),Z=R.useRef({}),ge=R.useRef(null),K=R.useRef(null),ve=R.useRef(null),pe=R.useRef(0),ye=R.useRef(0),ft=R.useRef(0);R.useEffect(()=>{if(!e||!t)return;const D=++ye.current,ee=new WeakMap;let he=null;const De=(ne,re)=>{const Se=ee.get(ne);if(Se===void 0||Ct(re)===Se.revision)return!1;const we=ne.payload.history.journal_generation;return!(typeof we=="string"&&we.length>0&&we===re.journalGeneration)};let te=null,ht=!1,Ke=0,Ee=0,et=0,G=0,Ce=0,Me=0,Oe=0,Ve=!1;const We=()=>{Me&&(window.clearTimeout(Me),Me=0)},os=ne=>{for(const re of ne)M.current.attempts.set(re,(M.current.attempts.get(re)??0)+1)},$i=ne=>{I(re=>{const Se=new Set;for(const Le of re.labelPending)re.labelPending.has(Le)&&(pa(M.current,re.transcript.argsByCall,Le,fa(re))||Se.add(Le));let we=null;for(const Le of re.labelMarked)pa(M.current,re.transcript.argsByCall,Le,fa(re))||(we=we??new Set(re.labelMarked),we.delete(Le));if(Se.size===0&&!we)return re;const se=new Set(re.labelPending);for(const Le of Se)se.delete(Le);return{...re,labelPending:se.size?se:zn,labelMarked:we&&we.size===0?fo:we??re.labelMarked}})},qg=ne=>{I(re=>{let Se=null,we=null;for(const se of ne)re.labelPending.has(se)&&(Se=Se??new Set(re.labelPending),Se.delete(se),we=we??new Set(re.labelMarked),we.add(se));return!Se||!we?re:{...re,labelPending:Se.size?Se:zn,labelMarked:we}})},ss=async(ne,re,Se=tf,we=1,se,Le=re,Xe=null)=>{pe.current+=1,ye.current===ne&&I($e=>$e.historyReadPending?$e:{...$e,historyReadPending:!0});for(const $e of Se.targets)M.current.inFlight.add($e),P.current.add($e);let ke=!1;try{ke=await e_(ne,re,Le,Xe,Se,we,se)}finally{if(pe.current=Math.max(0,pe.current-1),pe.current===0&&I($e=>$e.historyReadPending?{...$e,historyReadPending:!1}:$e),!ke){for(const $e of Se.targets)M.current.inFlight.delete($e);M.current.refused&&qg(Se.targets),$i()}}},e_=async(ne,re,Se,we,se,Le,Xe)=>{const ke={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:Se.size===0},$e=C.current.transcript.viewEpoch,Ze=await t_(ne,re,Se,we,se,Le,ke,Xe);if(Ze||ye.current!==ne||ke.reachedHeld||C.current.transcript.viewEpoch!==$e)return Ze;const bt=re!==Se&&[...re].some(yt=>Se.has(yt));if(bt&&ke.joined)return Ze;let vt;if(ke.oldest){if(!ke.hasMore)return Ze;vt={id:ke.oldest.id,ts:Math.round((ke.oldest.ts??0)*1e3)}}else{if(bt||!we)return Ze;vt=we}if(!vt)return Ze;const yn=I(yt=>{const $t=kA(yt.transcript,vt,ke.keys);return $t===yt.transcript?yt:{...yt,transcript:$t}});return x.current=yn.transcript.index,Ze},t_=async(ne,re,Se,we,se,Le,Xe,ke)=>{const $e=C.current.transcript.viewEpoch,Ze=()=>C.current.transcript.viewEpoch!==$e,bt=new Set;let vt,yn=0,yt=0,$t=!1,wn=Se.size===0,fr=!1;const is=C.current.cold,kn=z.current,Un=kn?{epoch:kn.epoch,seq:kn.seq}:null,rn=new Set(se.found),pr=()=>NA(se.order,se.targets,rn),j=()=>vm(se.order,se.targets,rn),O=()=>{const Q=new Map;for(const wt of Re){if(rn.has(wt))continue;const Nt=mt.get(wt);Nt!==void 0&&Q.set(wt,Nt)}return Q},Ae=new Set(se.every);for(const Q of rn)Ae.add(Q);const Re=new Set,mt=new Map;let Y=1;const Sn=se.targets.size>0;let me=Math.max(Du(pr()),Sn?M.current.depth:0),Ye=0;for(;yn<ef&&yt<KI;){yt+=1;let Q;const wt=Ka(C.current.transcript),Nt=wt.revision;try{Q=await Je({op:"sessions.history",sessionId:e,...vt?{beforeId:vt}:{},limit:Math.min(me,ef-yn),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(C.current.transcript).slice(0,512),...A()?{peerJournalSource:!0}:{}}:{}})}catch{if(Ze())return!1;if(C.current.transcript.records.length>0){if(Ye++>0)return M.current.refused=!0,!1;continue}return Le<HI?(Ce=window.setTimeout(()=>{if(Ce=0,ye.current!==ne||Ze()){$i();return}ss(ne,re,se,Le+1,ke,Se,we)},Ju(Le)),!0):(I(xe=>({...xe,status:"unavailable",failure:xI(),heldFrontend:null,...xe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{$i()}if(ye.current!==ne||Ze())return!1;if(Ct(C.current.transcript)!==Nt){if(!C.current.hydrated)continue;return!1}M.current.refused=!1;const Bn=Q.entries[0];yn+=Q.entries.length,ke?.(Q.entries.length),ha(N.current,Q.entries),ws(J.current,Q.entries),I(xe=>{if(Ct(xe.transcript)!==Nt)return xe;const Kt=vo(xe.transcript,Q,{authoritative:!0,orderRead:wt,peerSource:k(),readWitness:Un}),hr=ia(Q.entries,Ae),Di=new Set(xe.labelPending);for(const s_ of hr)Di.delete(s_);return{...xe,hydrated:xe.hydrated||Q.entries.length>0||!is,labelPending:Di.size?Di:zn,labelMarked:$I(xe.labelMarked,hr),transcript:Kt}}),e&&vt===void 0&&St.getState().resolveHeldFromServer(e,Q.entries,!Q.cursor_missing);const o_=pr();for(const xe of ia(Q.entries,Ae))rn.add(xe),Ae.add(xe);if(PA(Q.entries)&&(fr=!0),Sn){const xe=MA(Q.entries,Ae);for(const Kt of xe)Re.add(Kt),Ae.add(Kt);for(const[Kt,hr]of TA(Q.entries,xe))mt.set(Kt,hr);for(const Kt of[...Re])rn.has(Kt)&&Re.delete(Kt);Re.size>0&&Y--<=0&&Re.clear()}$t=$t||re.size===0||Q.entries.some(xe=>re.has(Dt(xe))||bt.has(xe.id)),wn=wn||Q.entries.some(xe=>Se.has(Dt(xe)));for(const xe of Q.entries)bt.add(xe.id);for(const xe of Q.entries)Xe.keys.add(Dt(xe));Bn&&(Xe.oldest=Bn),Xe.hasMore=Q.has_more,Xe.joined=$t,Xe.reachedHeld=wn;const Ni=pr()+Re.size;Sn&&pr()<o_&&(M.current.depth=Math.min(gl,Math.max(M.current.depth,yn)));let od=!1;if(Sn){const xe=j();od=CA(Q.entries,xe,se.starts,O(),new Set(xe.filter(hr=>se.waiting.has(hr))))||fr}if(jA($t&&wn,od?0:Ni)||!Bn||!Q.has_more)return!1;vt=Bn.id,me=Ni>0?Du(Ni):rc}return!1},ed=()=>{if(Ke&&cancelAnimationFrame(Ke),Ee&&clearTimeout(Ee),Ke=0,Ee=0,ye.current!==D)return;const ne=S.current;if(S.current=[],ne.length===0)return;const re=new Set,Se=new Map;for(const j of N.current)C.current.transcript.index.has(j)||N.current.delete(j);for(const j of J.current)C.current.transcript.index.has(j)||J.current.delete(j);for(const j of C.current.transcript.records)pl(j)&&!N.current.has(j.id)&&(re.add(j.id),Se.set(j.id,J.current.has(j.id)?j.ts:null));let we=null;for(const j of ne){if(j.type!=="snapshot")continue;const O=j.payload.history,Ae=O.entries[0];if(!Ae||!O.has_more)continue;const Re=Math.round((Ae.ts??0)*1e3);Re>0&&(!we||Re<we.ts)&&(we={id:Ae.id,ts:Re})}MI(ne);const se=j=>{const O=j.payload.history.entries,Ae=O.at(-1);if(!Ae)return!1;if(dR(j.payload)){if(re.size===0)return!0;const Re=new Set;for(const mt of O)Re.add(Dt(mt));return O.some(mt=>re.has(Dt(mt)))?!0:n0(j.payload.history,Se,Re)}return Ae.id===j.payload.frontend.snapshot.history_cursor?!1:re.has(Dt(Ae))},Le=j=>j!=null&&x.current.has(j);let Xe=!1;const ke=ne.some(j=>j.type==="attention"?!Le(j.payload.anchor_id):j.type==="snapshot"&&!se(j)),$e=C.current.cold&&!C.current.hydrated&&ne.some(j=>j.type==="snapshot"||j.type==="frontend.replace"||j.type==="frontend.update"?j.payload.cold===!1:!1),Ze=new Set(C.current.transcript.argsByCall.keys()),bt=[],vt=new Set;for(const j of ne){if(j.type!=="snapshot")continue;const O=De(j,C.current.transcript);O||ws(J.current,j.payload.history.entries);for(const Ae of j.payload.history.entries){O||vt.add(Dt(Ae));const Re=Ae.payload?.tool_calls;if(Array.isArray(Re))for(const mt of Re)mt&&typeof mt.id=="string"&&Ze.add(mt.id)}for(const Ae of j.payload.frontend.snapshot.live_events??[]){const Re=Ae.message;!O&&typeof Re?.id=="string"&&vt.add(Re.id)}bt.push(...j.payload.frontend.snapshot.live_events??[])}const yn=ne.some(j=>j.type==="event"&&Xu.has(String(j.payload.type??""))),yt=Nu(M.current.attempts,$u(bt,Ze),Ze,qu),$t=yn?Nu(M.current.attempts,[...M.current.attempts.keys(),...M.current.settled],Ze,qu):[],wn=[];for(const j of ne){if(j.type!=="event")continue;const O=j.payload;String(O.type??"")==="tool_execution_end"&&String(O.tool_call_id??"")&&wn.push(O)}const fr=[];for(const j of wn){const O=String(j.tool_call_id??"");Ze.has(O)||M.current.settled.has(O)||fr.push(O)}for(const j of fr)M.current.settled.add(j);for(;M.current.settled.size>Qu;){const j=M.current.settled.values().next().value;if(j===void 0)break;M.current.settled.delete(j)}for(const[j,O]of ju(wn))M.current.starts.set(j,O);for(;M.current.starts.size>nf;){const j=M.current.starts.keys().next().value;if(j===void 0)break;M.current.starts.delete(j)}const is=M.current.settleRows<zI?fr:[],kn=[...new Set([...yt,...$t,...is])],Un=kn.filter(j=>!M.current.painted.has(j));if(bt.length>0){M.current.order=$u(bt,new Set);for(const[j,O]of ju(bt))M.current.starts.set(j,O);for(;M.current.starts.size>nf;){const j=M.current.starts.keys().next().value;if(j===void 0)break;M.current.starts.delete(j)}for(const j of RA(bt))M.current.waiting.add(j);for(const j of $A(bt))M.current.waiting.delete(j);for(;M.current.waiting.size>JI;){const j=M.current.waiting.values().next().value;if(j===void 0)break;M.current.waiting.delete(j)}}for(const j of[...M.current.attempts.keys()])Ze.has(j)&&M.current.attempts.delete(j);for(os([...yt,...$t]);M.current.attempts.size>Qu;){const j=M.current.attempts.keys().next().value;if(j===void 0)break;M.current.attempts.delete(j)}if(performance.mark("lop:transcript:flush:start"),I(j=>{let O={...j},Ae=O.frontend!==null;Xe=!1;let Re=null;const mt=Date.now();for(const Y of ne){if(Y.type==="heartbeat")continue;if(Y.type==="gap"){he=null,O={...O,frontend:null,heldFrontend:O.frontend??O.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:Lu(O.transcript)},Ae=!1;continue}if(Y.type==="open")he=null;else if("seq"in Y){const me={epoch:Y.epoch,seq:Y.seq},Ye=sf(Y);if(!Ye&&!iw(he,me,{allowEqual:Y.type==="snapshot"}))continue;Ye||(he=me)}const Sn=z.current;if((Y.type==="open"||"seq"in Y)&&!sf(Y)&&(z.current={epoch:Y.epoch,seq:Y.seq},O={...O,receipt:z.current}),Y.type==="open"){if(O={...O,subscriptionId:Y.payload.subscription_id},Y.payload.gap){const me=O.frontend??O.heldFrontend;O={...O,frontend:null,heldFrontend:me,history:null,transcript:Lu(O.transcript)},me&&O.status==="live"&&(O={...O,status:"reconnecting"}),Ae=!1}continue}if(!Ae){if(Y.type==="event"&&(Re=nc(Re??O.transcript,Y.payload,mt,{frame:{epoch:Y.epoch,seq:Y.seq}})),Y.type==="snapshot"){const me=ee.get(Y),Ye=De(Y,O.transcript);Ye&&(Xe=!0);const Q=Y.payload,wt=!Q.history.cursor_missing&&!Ye;let Nt=Re??O.transcript;wt&&(performance.mark("lop:open:history:start"),Nt=vo(Nt,Q.history,{authoritative:!0,orderRead:me,peerSource:k(),readWitness:{epoch:Y.epoch,seq:Y.seq}}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),ha(N.current,Q.history.entries),ws(J.current,Q.history.entries)),e&&St.getState().resolveHeldFromServer(e,Q.history.entries,wt),performance.mark("lop:open:seed:start"),Nt=IA(Nt,Q.frontend.snapshot,mt,{epoch:Y.epoch,seq:Y.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const Bn=Yu(O.frontend??O.heldFrontend,Q.frontend.snapshot,Q.cold===!0||Q.attaching===!0);O={...O,contextCarried:Object.keys(Bn).length>0,subagentPulses:OI(Q.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...Q.frontend.snapshot,...Bn,attention:Ar(O.frontend?.attention,Q.frontend.snapshot.attention,e)},history:Ye?O.history:Q.history,cold:Q.cold,ownerEpoch:Q.frontend.epoch,failure:null,hydrated:O.hydrated||wt&&Q.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:Nt},Ae=!0,Re=null}continue}if(Y.type==="attention"){O.frontend&&(O={...O,frontend:{...O.frontend,attention:Ar(O.frontend.attention,Y.payload,e)}});continue}if(Y.type==="frontend.update"){const me=Y.payload,Ye=me.changes??{};if((me.degraded===!0||me.paused===!0)&&(O={...O,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!O.frontend)continue;const Q=me.epoch!==O.ownerEpoch&&Ye.epoch===me.epoch,wt=me.changes!==void 0&&Ye.epoch===me.epoch;(Q||me.epoch===O.ownerEpoch&&(O.frontend.sequence<me.sequence||O.frontend.sequence===me.sequence&&wt))&&(O={...O,contextCarried:!1,ownerEpoch:Q?me.epoch:O.ownerEpoch,frontend:{...O.frontend,...Ye,...Ye.jobs==null&&me.job_deltas?{jobs:Yw(O.frontend.jobs??[],me.job_deltas)}:{},attention:Ar(O.frontend.attention,Ye.attention,e),sequence:me.sequence},...typeof me.cold=="boolean"?{cold:me.cold}:{}},wt&&O.liveUpdatesNotice==="update"&&O.liveUpdatesPaused&&(O={...O,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(Y.type==="frontend.replace"){if(O.frontend&&aw(Sn,e,Y)){const me=Y.payload.frontend,Ye=Yu(O.frontend,me.snapshot,Y.payload.cold===!0);O={...O,contextCarried:Object.keys(Ye).length>0,frontend:{...me.snapshot,...Ye,attention:Ar(O.frontend.attention,me.snapshot.attention,e)},ownerEpoch:me.epoch,cold:Y.payload.cold,...O.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(Y.type==="event"){const me=String(Y.payload.type??"");if(Y.payload.action==="reload"){O={...O,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}NI.has(me)&&(O={...O,terminal:me}),Xu.has(me)&&(O={...O,turnsCompleted:O.turnsCompleted+1});const Ye=nc(O.transcript,Y.payload,mt,{frame:{epoch:Y.epoch,seq:Y.seq},userStoppedAt:e?St.getState().stoppedTurns[e]??null:null,queuedAskEngine:pm(O.frontend)});Ye!==O.transcript&&(O={...O,transcript:Ye});const Q=PI(O.subagentPulses,Y.payload);Q!==O.subagentPulses&&(O={...O,subagentPulses:Q})}}if(!Ae&&Re){for(const Y of Re.index.keys())O.transcript.index.has(Y)||N.current.add(Y);O={...O,transcript:Re}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),x.current=O.transcript.index,!jI(ne))return j;if(Un.length>0){const Y=new Set(O.labelPending);for(const Sn of Un)Y.add(Sn);O={...O,labelPending:Y}}return O.frontend!==null&&O.frontend!==O.heldFrontend&&(O={...O,heldFrontend:O.frontend}),O}),Un.length>0){for(const j of Un)M.current.painted.add(j);for(;M.current.painted.size>YI;){const j=M.current.painted.values().next().value;if(j===void 0)break;M.current.painted.delete(j)}}const rn=ke||Xe,pr=is.length>0&&yt.length===0&&$t.length===0&&!rn&&!$e;if(rn||kn.length>0||$e){const j=new Set(kn),O=M.current.order;ss(D,vt,kn.length>0?{targets:j,order:O,starts:M.current.starts,waiting:M.current.waiting,every:new Set([...O,...j]),found:new Set(ia(ne.flatMap(Ae=>Ae.type==="snapshot"?Ae.payload.history.entries:[]),new Set(O))),pending:Un}:tf,1,pr?Ae=>{M.current.settleRows+=Ae}:void 0,re,we)}if(Vw())for(const j of ne)"epoch"in j&&"seq"in j&&Zw({carrier:"canonical-sse",sessionId:e,epoch:j.epoch,seq:j.seq,disposition:"processed"})},zr=()=>{const ne=te;if(te=null,f.current=null,h.current+=1,m.current&&(window.clearTimeout(m.current),m.current=0),y.current+=1,!!ne){ht=!0;try{ne()}finally{ht=!1}}},Kr=()=>{const ne=Ka(C.current.transcript),re=aa.currentToken(),Se=++ft.current;We(),Me=window.setTimeout(()=>{Me=0,ye.current===D&&(zr(),I(se=>({...se,subscriptionId:null,status:"unavailable",failure:Zu(go.ended),...se.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ve&&(Ve=!0,Oe=window.setTimeout(()=>{Oe=0,ye.current===D&&nd()},UI)))},FI);const we=p();te=Tw({sessionId:e,epoch:Z.current.epoch,afterSeq:Z.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:Zt(C.current.transcript).slice(0,512),...we?{peerJournalSource:!0}:{}}:{}},se=>{if(ye.current===D&&ft.current===Se){if(se.kind==="error"||se.kind==="end"){if(ht)return;if(We(),zr(),se.kind==="error"&&se.status===404){if(!n){e&&St.getState().retireDraftWarm(e),I(ke=>({...ke,subscriptionId:null}));return}e&&(mI(e),yI(e),EI(e),St.getState().retireDraftsForSession(e)),I(ke=>({...ke,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...ke.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const Le=se.kind==="error"?se.detail??_("ui.common.errors.event_stream_failed"):_("ui.common.errors.event_stream_closed");if(I(ke=>({...ke,subscriptionId:null})),et>=LI){I(ke=>({...ke,status:"unavailable",failure:Zu(Le),...ke.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}et+=1;const Xe=z.current;Xe&&(Z.current={epoch:Xe.epoch,afterSeq:Xe.seq}),I(ke=>ke.status==="unavailable"&&et>1?ke:{...ke,status:"reconnecting",failure:null}),G=window.setTimeout(()=>{G=0,ye.current===D&&Kr()},Ju(et));return}if(se.data!==void 0)try{const Le=se.data,Xe=se.receipt?performance.now():0,ke=Le.length>=GI;ke&&performance.mark("lop:open:parse:start");const $e=JSON.parse(Le),Ze=se.receipt?performance.now():0;$e.type==="snapshot"&&ee.set($e,ne),ke&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),$e.type==="snapshot"&&(se.receipt&&console.warn(pw(se.receipt,re,Xe,Ze)),aa.note(e,"snapshot",re),et=0,We(),Ve=!1),S.current.push($e),Ke||(Ke=requestAnimationFrame(ed)),Ee||(Ee=window.setTimeout(ed,WI))}catch{}}},se=>{se==="requested"&&aa.note(e,"request",re)}),f.current={sessionId:e,peer:we},h.current+=1},td=()=>{G!==0&&(window.clearTimeout(G),G=0),Z.current={},z.current=null,zr(),Kr()},nd=()=>{et=0,Oe&&(window.clearTimeout(Oe),Oe=0),G&&(window.clearTimeout(G),G=0),Ce&&(window.clearTimeout(Ce),Ce=0),I(ne=>({...ne,failure:null,status:ne.status==="unavailable"?"connecting":ne.status,transcript:bs(ne.transcript,!1)})),C.current.hydrated||ss(D,new Set(C.current.transcript.index.keys())),!te&&Kr()};Kr(),ge.current=nd,K.current=()=>{C.current.liveUpdatesReloading||(I(ne=>({...ne,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),et=0,G&&(window.clearTimeout(G),G=0),Oe&&(window.clearTimeout(Oe),Oe=0),td())},ve.current=()=>{!C.current.hydrated&&pe.current===0&&ss(D,new Set(C.current.transcript.index.keys()))};const n_=XI(e,td),rd=()=>{if(!t||!e||b.current===e)return;const ne=f.current;ne===null||ne.sessionId!==e||ne.peer||p()&&(b.current=e,zr(),Kr())};v.current=rd;const r_=St.subscribe(()=>{rd()});return()=>{ye.current+=1,ge.current=null,ve.current=null,K.current=null,v.current=null,r_(),m.current&&(window.clearTimeout(m.current),m.current=0),n_(),zr(),Ke&&cancelAnimationFrame(Ke),Ee&&clearTimeout(Ee),G&&clearTimeout(G),Ce&&clearTimeout(Ce),Be.current&&(window.clearTimeout(Be.current),Be.current=0),qe.current&&(window.clearTimeout(qe.current),qe.current=0),Oe&&window.clearTimeout(Oe),We(),S.current=[]}},[I,e,t,n,a,p,A,k]),R.useEffect(()=>{!e||!t||v.current?.()},[e,t,d]),R.useEffect(()=>{Z.current={},z.current=null,x.current=Lt.index;const D=aR(g.current,e,n,w.current);g.current=e,w.current=n;const ee=e?Im(e):null;x.current=D?C.current.transcript.index:(ee?.transcript??Lt).index;const he=new Set(D?N.current:[]);for(const te of ee?.replayBorn??[])he.add(te);const De=D?C.current.transcript.index:(ee?.transcript??Lt).index;for(const te of he)De.has(te)||he.delete(te);N.current=he,D||(J.current=new Set),I(te=>({...te,frontend:null,heldFrontend:D?te.heldFrontend:null,contextCarried:D?te.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:D?te.turnsCompleted:0,transcript:D?te.transcript:ee?.transcript??Lt,stale:D?te.stale:ee!==null,missing:D?te.missing:!1,status:"connecting",subagentPulses:{},labelPending:ee?.owedLabels??zn,labelMarked:ee?.markLabels??fo,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),M.current=rf(e)},[e,n]),R.useEffect(()=>{if(e)return()=>{const D=C.current.transcript;D.records.length>0&&hI(e,{transcript:D,owedLabels:new Set([...C.current.labelPending].filter(ee=>pa(M.current,C.current.transcript.argsByCall,ee,fa(C.current)))),markLabels:new Set(C.current.labelMarked),replayBorn:new Set(N.current)});for(const ee of P.current)M.current.inFlight.delete(ee);P.current.clear()}},[e]);const Be=R.useRef(0);R.useEffect(()=>{if(T.labelPending.size===0&&T.labelMarked.size===0){Be.current&&(window.clearTimeout(Be.current),Be.current=0);return}if(Be.current)return;const D=()=>{Be.current=0;const ee=C.current.labelPending,he=C.current.labelMarked;if(ee.size===0&&he.size===0)return;const De=M.current;for(const te of ee)if(De.inFlight.has(te)){Be.current=window.setTimeout(D,ua);return}for(const te of he)if(De.inFlight.has(te)){Be.current=window.setTimeout(D,ua);return}I(te=>te.labelPending.size===0&&te.labelMarked.size===0?te:{...te,labelPending:zn,labelMarked:fo})};Be.current=window.setTimeout(D,ua)},[I,T.labelPending,T.labelMarked]);const qe=R.useRef(0);R.useEffect(()=>{if(T.labelPending.size===0){qe.current&&(window.clearTimeout(qe.current),qe.current=0),I(D=>D.labelHoldLate?{...D,labelHoldLate:!1}:D);return}T.labelHoldLate||qe.current||(qe.current=window.setTimeout(()=>{qe.current=0,I(D=>D.labelPending.size===0||D.labelHoldLate?D:{...D,labelHoldLate:!0})},VI))},[I,T.labelPending,T.labelHoldLate]);const fe=R.useRef(e);fe.current=e;const Ie=R.useRef({id:e,epoch:0});Ie.current.id!==e&&(Ie.current={id:e,epoch:Ie.current.epoch+1});const Rt=R.useRef(null);Rt.current===null&&(Rt.current=AI());const He=R.useRef(!1),pt=R.useRef(null),[_e,Pe]=R.useState(0);R.useEffect(()=>{const D=T.transcript,ee=Zt(D);if(!e||!a||!D.orderNeedsReconcile&&(!D.journalGeneration||ee.length===0)||He.current)return;const he=G=>({fields:JSON.stringify([_e,e,G.viewEpoch,Ct(G),G.orderNeedsReconcile,G.orderWantedGeneration,Zt(G)]),demand:G.orderDemand}),De=he(D);if(pt.current?.fields===De.fields&&pt.current.demand===De.demand)return;pt.current=De;const te=e,ht=D.viewEpoch;He.current=!0;let Ke=null,Ee=D;const et=G=>{if(!G.peer||fe.current!==te||C.current.transcript.viewEpoch!==ht||h.current!==G.streamEpoch)return;const Ce=G.kind==="authority"?G.frame.payload.history:G.page,Me=Ce.journal_order_state;if(Me==="ready"){m.current&&(window.clearTimeout(m.current),m.current=0),I(Ve=>{const We=bs(Ve.transcript,!1);return We===Ve.transcript?Ve:{...Ve,transcript:We}});return}if(Me==="unavailable"){if(m.current&&(window.clearTimeout(m.current),m.current=0),Ce.reconcile===!0)return;I(Ve=>{const We=bs(Ve.transcript,!0);return We===Ve.transcript?Ve:{...Ve,transcript:We}});return}if(Me!=="building")return;m.current&&(window.clearTimeout(m.current),m.current=0);const Oe=++y.current;m.current=window.setTimeout(()=>{m.current=0,y.current===Oe&&fe.current===te&&C.current.transcript.viewEpoch===ht&&h.current===G.streamEpoch&&I(Ve=>{const We=bs(Ve.transcript,!0);return We===Ve.transcript?Ve:{...Ve,transcript:We}})},BI)};e0({getTranscript:()=>C.current.transcript,isCurrent:()=>fe.current===te&&C.current.transcript.viewEpoch===ht,sweep:(G,Ce)=>{if(!A())return;if(G.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${te}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const Me=G.journalGeneration;if(typeof Me!="string"||Me.length===0)return{kind:"none",path:`/v1/desktop/sessions/${te}/history`,query:new URLSearchParams};if(eh(G,Ce?.("lookup")).length>0){const We=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:Me});return{kind:"lookup",path:`/v1/desktop/sessions/${te}/history`,query:We}}if(Yc(G).length>0){const We=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:Me});return{kind:"payload",path:`/v1/desktop/sessions/${te}/history`,query:We}}return{kind:"none",path:`/v1/desktop/sessions/${te}/history`,query:new URLSearchParams}},read:async(G,Ce)=>{Ee=C.current.transcript,pt.current=he(Ee);const Me=A(),Oe=h.current;if(Ce==="lookup"||Ce==="payload"){const We=C.current.transcript.journalGeneration,os=await Je({op:"sessions.history",sessionId:te,limit:100,journalOrder:!0,orderIds:G,peerJournalSource:!0,sourceRead:Ce==="payload"?"payload":"metadata",...typeof We=="string"&&We.length>0?{expectedJournalGeneration:We}:{}});return Ce==="payload"?{kind:"payload",page:os,peer:Me,streamEpoch:Oe}:{kind:"lookup",page:os,peer:Me,streamEpoch:Oe}}return{kind:"authority",frame:await Je({op:"sessions.get",sessionId:te,journalOrder:!0,orderIds:G,...Me?{peerJournalSource:!0}:{}}),peer:Me,streamEpoch:Oe}},page:G=>G.kind==="authority"?G.frame.payload.history:G.page,lookupPath:`/v1/desktop/sessions/${te}`,commit:(G,Ce,Me)=>{G.peer&&h.current!==G.streamEpoch||(I(Oe=>fe.current!==te||Ct(Oe.transcript)!==Ce||Oe.transcript.viewEpoch!==ht?Oe:{...Oe,transcript:G.kind==="authority"?G.peer?Mu(Oe.transcript,G.frame.payload.history,{authoritative:!0,orderRead:Me}):vA(Oe.transcript,G.frame.payload.history,Me):G.kind==="payload"?yA(Oe.transcript,G.page,Me,Ce):Mu(Oe.transcript,G.page,{authoritative:!1})}),et(G))}}).then(G=>{Ke=G.kind==="complete"?G.transcript:null}).catch(G=>{console.warn("[canonical] source-order reconcile refused",G)}).finally(()=>{He.current=!1;const G=C.current.transcript,Ce=Ke??Ee;Ke&&fe.current===te&&G.viewEpoch===ht&&!G.orderNeedsReconcile&&(pt.current=he(Ce)),(fe.current!==te||G.viewEpoch!==ht||Ct(G)!==Ct(Ce)||G.orderWantedGeneration!==Ce.orderWantedGeneration||G.orderNeedsReconcile!==Ce.orderNeedsReconcile||G.orderDemand!==Ce.orderDemand||JSON.stringify(Zt(G))!==JSON.stringify(Zt(Ce)))&&Pe(Me=>Me+1)})},[I,e,a,A,T.transcript,_e]);const it=R.useCallback(async()=>{const D=Rt.current;if(!e||!D)return{kind:"nothing-to-load"};const ee=e,he=Ie.current.epoch,De=()=>Ie.current.epoch===he,te=C.current.transcript.viewEpoch,ht=()=>C.current.transcript.viewEpoch===te,Ke=await D.load(`${ee}#${he}`,{getTranscript:()=>C.current.transcript,readPage:Ee=>Je({op:"sessions.history",sessionId:ee,beforeId:Ee,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(C.current.transcript).slice(0,512),...A()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>De()&&ht(),commit:Ee=>I(et=>{const G=Ee(et.transcript);return G===et.transcript?et:{...et,transcript:G}}).transcript,setLoading:Ee=>{De()&&I(et=>et.loadingOlder===Ee?et:{...et,loadingOlder:Ee})},peerSource:k});return De()&&(Ke.kind==="failed"?I(Ee=>Ee.olderFailed?Ee:{...Ee,olderFailed:!0}):Ke.kind==="applied"&&I(Ee=>Ee.olderFailed?{...Ee,olderFailed:!1}:Ee)),Ke},[I,e,A,k]),xt=R.useCallback(async()=>(await it()).kind==="applied",[it]),Tt=R.useRef(!1),Gr=R.useCallback(async(D,ee)=>{if(!e||Tt.current)return!1;const he=e;Tt.current=!0;const De=Ct(C.current.transcript),te=z.current,ht=te?{epoch:te.epoch,seq:te.seq}:null;try{const Ke=await Je({op:"sessions.history",sessionId:he,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(C.current.transcript).slice(0,512),...A()?{peerJournalSource:!0}:{}}:{}});return fe.current!==he||Ct(C.current.transcript)!==De||C.current.transcript.viewEpoch!==ee?!1:(I(Ee=>Ct(Ee.transcript)!==De?Ee:{...Ee,transcript:vo(Ee.transcript,Ke,{keepPaging:!0,peerSource:k(),readWitness:ht})}),ha(N.current,Ke.entries),ws(J.current,Ke.entries),WA(Ke.entries,D))}catch{return!1}finally{Tt.current=!1}},[I,e,A,k]);R.useEffect(()=>r?sR(r,ee=>{I(he=>{const De=ee(he.transcript);return De===he.transcript?he:{...he,transcript:De}})}):void 0,[I,r]),R.useEffect(()=>{r&&oR(r,T.transcript)},[r,T.transcript]);const ur=R.useCallback(()=>{I(D=>({...D,transcript:DA(D.transcript),olderFailed:!1,heldFrontend:null}))},[I]),Zl=R.useCallback(()=>{ge.current?.()},[]),Yl=R.useCallback(()=>{K.current?.()},[]),Jl=R.useCallback(()=>{ve.current?.()},[]),Ql=R.useCallback((D,ee="info")=>{I(he=>({...he,transcript:UA(he.transcript,D,ee)}))},[I]),Xl=R.useCallback(D=>{I(ee=>({...ee,pendingModel:D}))},[I]),ql=R.useCallback(()=>{I(D=>D.pendingModel===null?D:{...D,pendingModel:null})},[I]);return R.useEffect(()=>{const D=T.pendingModel;if(!D)return;const ee=oc(D);if(!ee)return;const he=T.frontend;rI(he,ee)&&I(De=>({...De,pendingModel:null}))},[I,T.frontend,T.pendingModel]),R.useEffect(()=>{if(!T.pendingModel)return;const D=window.setTimeout(()=>I(ee=>({...ee,pendingModel:null})),DI);return()=>window.clearTimeout(D)},[I,T.pendingModel]),R.useMemo(()=>({...T,awaitingHydration:t&&!!e&&n&&!T.hydrated,loadOlder:xt,loadOlderDetailed:it,refreshTail:Gr,clearView:ur,addNote:Ql,paintPendingModel:Xl,clearPendingModel:ql,retry:Zl,rehydrate:Jl,reloadFromHistory:Yl}),[T,t,e,n,xt,it,Gr,ur,Ql,Xl,ql,Zl,Jl,Yl])}function Si(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
41
41
 
42
42
  `)?e:`${t}
43
43
 
44
- ${e}`}const ha={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function js(e,t,n){const r=[...e.attachments??[]],o=[],s=[],a=new Set;for(const h of t.attachments){const m=r.find(b=>b.path===h&&!a.has(b.id));if(m){a.add(m.id),s.push(m.id);continue}const y={id:n(),path:h};o.push(y),s.push(y.id)}const c=[...e.replies??[]],l=t.replies.filter(h=>!c.some(m=>m.id===h.id)),d=t.text,u=[...o,...r],f=[...l,...c];return{...e,attachments:u,replies:f,textRevision:(e.textRevision??0)+1,volatilePendingText:e.volatilePendingText===!0||t.volatileText===!0,pendingText:d===""?e.pendingText:Si(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:s,replyIds:t.replies.map(h=>f.find(m=>m.id===h.id)?.id).filter(h=>h!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function dR(e,t){const n=e.lateDeliveredText??e.returned?.text;if(!n||t.includes(n))return!0;const r=Math.max(8,Math.min(24,Math.floor(n.length/3)));for(let o=0;o+r<=n.length;o++)if(t.includes(n.slice(o,o+r)))return!0;return!1}function uR(e){return{text:Si(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function fR(e,t){if(!e||!t)return!1;const n=uR(e),r=e.attachments??[],o=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((s,a)=>s.id===t.chipIds[a])&&o.length===t.replyIds.length&&o.every((s,a)=>s.id===t.replyIds[a])}function pR(e,t=()=>crypto.randomUUID()){const n={};for(const[r,o]of Object.entries(e??{}))n[r]=o.inFlight?js(o,o.inFlight,t):o;return n}function hR(e,t){const n=t.text,r=Si(e.currentInput??"",e.pendingText??"");let o=r,s="overlap";n===""?s="draft-only":r.startsWith(n)&&(o=r.slice(n.length).replace(/^\n+/,""),s="draft-only");const a=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:o,pendingText:void 0,attachments:(e.attachments??[]).filter(l=>!a.has(l.id)),replies:(e.replies??[]).filter(l=>!c.has(l.id)),unredactedChars:n===""?e.unredactedChars??0:0},box:s}}const mR=300,Cm="conversation-input-store";let Ho=null,Om=Cm,kt=null,ma=!1;const cc=()=>{try{return globalThis.localStorage??null}catch{return null}},yo=()=>{kt!==null&&(clearTimeout(kt),kt=null);const e=Ho;if(!e)return;const t=Om,n=cc();if(n){try{n.setItem(t,JSON.stringify(e))}catch(r){ma||(ma=!0,console.warn("[composer] the draft could not be persisted; it stays in memory for this session",r));return}Ho=null,ma=!1}},t$=()=>{yo()},n$=()=>{Ho=null,kt!==null&&(clearTimeout(kt),kt=null)},gR={getItem:e=>{const t=cc();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)=>{Ho=t,Om=e,kt!==null&&clearTimeout(kt),kt=setTimeout(()=>{kt=null,yo()},mR)},removeItem:e=>{Ho=null,kt!==null&&(clearTimeout(kt),kt=null),cc()?.removeItem(e)}};typeof window<"u"&&typeof window.addEventListener=="function"&&(window.addEventListener("pagehide",yo),window.addEventListener("beforeunload",yo),window.document?.addEventListener("visibilitychange",()=>{window.document.visibilityState==="hidden"&&yo()}));const ct=Qo()(_i((e,t)=>({inputByConversation:{},addReply:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=Array.isArray(o.replies)?o.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...o,replies:[...s,r]}}})},removeReply:(n,r)=>{const o=t().inputByConversation[n];o&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,replies:o.replies.filter(s=>s.id!==r)}}})},clearReplies:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:[]}}})},addAttachment:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=Array.isArray(o.attachments)?o.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...o,attachments:[...s,r]}}})},removeAttachment:(n,r)=>{const o=t().inputByConversation[n];o&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,attachments:o.attachments.filter(s=>s.id!==r)}}})},clearAttachments:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[]}}})},setCurrentInput:(n,r,o=0)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...s,lateDelivered:s.lateDelivered==="overlap"&&!dR(s,r)?void 0:s.lateDelivered,currentInput:r,unredactedChars:r?o:0}}})},getUnredactedChars:n=>t().inputByConversation[n]?.unredactedChars||0,getCurrentInput:n=>t().inputByConversation[n]?.currentInput||"",addSubmittedMessage:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=o.submittedMessages[o.submittedMessages.length-1],a=r&&r!==s?[...o.submittedMessages.slice(-19),r]:o.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...o,submittedMessages:a}}})},getSubmittedMessages:n=>t().inputByConversation[n]?.submittedMessages||[],clearSubmittedMessages:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,submittedMessages:[]}}})},getCurrentHistoryIndex:n=>t().inputByConversation[n]?.currentHistoryIndex??null,setCurrentHistoryIndex:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=o.submittedMessages;let a=null;typeof r=="number"&&s.length>0&&(a=Math.max(0,Math.min(r,s.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...o,currentHistoryIndex:a}}})},resetCurrentHistoryIndex:n=>{const r=t().inputByConversation[n];r&&(r.currentHistoryIndex??null)!==null&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentHistoryIndex:null}}})},clearAll:n=>{const{[n]:r,...o}=t().inputByConversation;e({inputByConversation:o})},restoreRow:(n,r)=>{e({inputByConversation:{...t().inputByConversation,[n]:{...r,textRevision:(r.textRevision??0)+1}}})},beginInFlight:(n,r,o=!0)=>{const s=t().inputByConversation[n]??ha,a=new Set(r.attachments.map(d=>d.id)),c=new Set(r.replies.map(d=>d.id)),l=s.currentInput===r.text;e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:l?"":s.currentInput,unredactedChars:l?0:s.unredactedChars,textRevision:l?(s.textRevision??0)+1:s.textRevision,attachments:(s.attachments??[]).filter(d=>!a.has(d.id)),replies:(s.replies??[]).filter(d=>!c.has(d.id)),inFlight:o?{text:r.text,attachments:r.attachments.map(d=>d.path),replies:[...r.replies],unredactedChars:l?s.unredactedChars:0,volatileText:r.volatileText}:s.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const r={...t().inputByConversation};let o=!1;for(const s of n){const a=r[s];!a||!a.inFlight&&!a.returned||(r[s]={...a,inFlight:void 0,returned:void 0},o=!0)}o&&e({inputByConversation:r})},returnInFlight:(n,r)=>{const o={...t().inputByConversation},s=o[n],a=s?.inFlight??o[r]?.inFlight;let c=o[r]??ha;n!==r&&s&&(c=js(c,{text:s.currentInput??"",attachments:(s.attachments??[]).map(l=>l.path),replies:s.replies??[],unredactedChars:s.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:o[r]?.returned},delete o[n]),a&&(c=js(c,a,()=>crypto.randomUUID())),!(!a&&n===r)&&(o[r]=c,e({inputByConversation:o}))},adoptReturnedText:n=>{const r=t().inputByConversation[n];if(r?.pendingText===void 0)return null;const o=Si(r.currentInput??"",r.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:o,pendingText:void 0,textRevision:(r.textRevision??0)+1}}}),o},returnPayload:(n,r)=>{const o=t().inputByConversation[n]??ha;o.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:js(o,r,()=>crypto.randomUUID())}})},reconcileDelivered:n=>{const r=t().inputByConversation[n];if(!r)return;const o=f=>(f.currentInput??"")===""&&(f.attachments??[]).length===0&&(f.replies??[]).length===0,s=r.returned!==void 0||r.inFlight!==void 0,a=r.returned?fR(r,r.returned):o(r),c=r.returned?hR(r,r.returned):null,l={...r,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,volatilePendingText:void 0,textRevision:(r.textRevision??0)+1},d=(c?.row.currentInput??"")==="",u=c&&!o(c.row)?{...c.row,returned:void 0,inFlight:void 0,volatilePendingText:d?void 0:r.volatilePendingText,lateDelivered:c.box==="overlap"&&d?"draft-only":c.box,lateDeliveredText:c.box==="overlap"&&!d?r.returned?.text:void 0,textRevision:(r.textRevision??0)+1}:{...r,returned:void 0,inFlight:void 0,lateDelivered:s&&r.returned?.text?"overlap":s?"delivered":void 0,lateDeliveredText:s?r.returned?.text:void 0};e({inputByConversation:{...t().inputByConversation,[n]:a||c!==null&&o(c.row)?l:u}})},dismissLateDelivery:n=>{const r=t().inputByConversation[n];r?.lateDelivered&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,lateDelivered:void 0,lateDeliveredText:void 0}}})},clearComposer:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,volatilePendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,textRevision:(r.textRevision??0)+1}}})},setComposerText:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...o,currentInput:r,unredactedChars:o.unredactedChars??0,textRevision:(o.textRevision??0)+1}}})}}),{name:Cm,storage:gR,partialize:e=>({inputByConversation:Object.fromEntries(Object.entries(e.inputByConversation).map(([t,n])=>{let r=n;return r.inFlight?.volatileText&&(r={...r,inFlight:{...r.inFlight,text:""}}),r.returned?.volatileText&&(r={...r,returned:{...r.returned,text:""}}),r.volatilePendingText&&(r={...r,pendingText:void 0}),r.volatilePendingText&&(r={...r,lateDeliveredText:void 0}),[t,r]}))}),merge:(e,t)=>({...t,inputByConversation:pR(e?.inputByConversation)})}));function Pm(e){if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null}function r$(e,t){return t?e.filter(n=>n.session_id===t&&Mm(n)).length:0}function Mm(e){if(Pm(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function _R(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function o$(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 s$={cwd:""};function bR(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,_R(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function vR(e){return(await Qe({op:"sessions.preview",requestId:crypto.randomUUID(),cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}})).frontend}function i$(e,t){const n=e.trim();if(!n)return{checked:!0,rung:null,confirmation:o=>_("ui.chat.session_readout.draft.confirm_model",{selector:o})};if(!t.ladderKnown)return{checked:!1,rung:null,refusal:_("ui.chat.session_readout.draft.refusal_ladder_unread")};const r=t.ladder.find(o=>o.trim().toLowerCase()===n.toLowerCase());return r?{checked:!0,rung:r,confirmation:o=>_("ui.chat.session_readout.draft.confirm_model_effort",{selector:o,effort:vs(r)})}:{checked:!0,rung:null,confirmation:o=>t.level?_("ui.chat.session_readout.draft.confirm_effort_changed",{selector:o,level:vs(t.level),wanted:vs(n)}):_("ui.chat.session_readout.draft.confirm_effort_unset",{selector:o,wanted:vs(n)})}}function a$(e,t){return e!==!0?null:t==="on"?_("ui.chat.fast_mode.stays_on"):t==="off"?_("ui.chat.fast_mode.turned_off"):_("ui.chat.fast_mode.unsupported_stays_off")}const c$=()=>_("ui.chat.fast_mode.service_cannot_carry"),l$="fast_unavailable";function vl(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function d$(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function u$(e){const t=e instanceof xe?e:null;return t?.code==="fast_mode_unsupported"?_("ui.chat.fast_mode.pick_unsupported"):t?.status===422?_("ui.chat.fast_mode.service_unavailable"):_("ui.chat.fast_mode.not_changed")}function f$(e,t){const n={...e,model:vl(e.model,t)};return{queryKey:bR(n),queryFn:()=>vR(n),placeholderData:v_,staleTime:3e4,retry:!1}}function ce(e){return typeof e=="string"?e.trim():""}function yr(e){const t=ce(e);return t||null}function Ln(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function po(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function jm(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function nr(e,t){return typeof e=="boolean"?e:t}function lc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Br(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 Br(t)}return[]}function yR(e){if(!On(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:jm(e.attempts),last_frame_at:Ln(e.last_frame_at),next_retry_at:Ln(e.next_retry_at),last_error:ce(e.last_error)}}function On(e){return typeof e=="object"&&e!==null}const wR=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function kR(e,t){const n=ce(e);return wR.includes(n)?n:t?"reachable":"unreachable_legacy"}const SR=["running","not_listening","unknown"];function ER(e){const t=ce(e);return SR.includes(t)?t:void 0}function AR(e){if(Array.isArray(e))return e.filter(On).map(t=>({endpoint:ce(t.endpoint),connected:t.connected===!0,detail:ce(t.detail),latency_ms:Ln(t.latency_ms)})).filter(t=>t.endpoint!=="")}function p$(e){const t=new Set,n=[];for(const a of Br(e)){const c=ce(a.device_id);if(!c||t.has(c)||typeof a.reachable!="boolean")continue;t.add(c);const l=ER(a.remote_relay),d=AR(a.attempts),u=a.reachable?void 0:yR(a.redial);n.push({device_id:c,name:ce(a.name),reachable:a.reachable,link_state:kR(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:yr(a.unreachable_reason??a.reason),last_seen_at:Ln(a.last_seen_at),session_count:po(a.session_count),rtt_ms:Ln(a.rtt_ms)})}const r=On(e)?e:{},o=ce(r.self_device_id),s=lc(r.degraded);return{peers:n,...o?{self_device_id:o}:{},...s.length?{degraded:s}:{}}}function IR(e){const t=ce(e.device_id);return t?{device_id:t,name:ce(e.name),role:ce(e.role),capabilities:lc(e.capabilities),active:nr(e.active,!0),suspect:nr(e.suspect,!1),endpoints:lc(e.endpoints),last_seen_at:Ln(e.last_seen_at),reachable:nr(e.reachable,!0),reason:ce(e.reason??e.unreachable_reason),scope:ce(e.scope)}:null}function RR(e){const t=ce(e.network_id);return t?{network_id:t,name:ce(e.name),epoch:jm(e.epoch),trust:ce(e.trust),members:Br(e.members).map(IR).filter(n=>n!==null)}:null}function h$(e){const t=On(e)?e:{},n=ce(t.self_device_id);return{networks:Br(t.networks).map(RR).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function xR(e){return e.live_state.trim().toLowerCase()==="busy"}function m$(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const o of Br(r)){const s=ce(o.id);if(!s||n.has(s))continue;const a=o.locality==="remote"?"remote":ce(o.locality)==="local"?"local":null;if(!a)continue;n.add(s);const c=On(o.status)?{code:ce(o.status.code),label:ce(o.status.label)}:null,l=On(o.binding)?{agent:yr(o.binding.agent),team:yr(o.binding.team)}:null,d=On(o.opened_by)?{agent:yr(o.opened_by.agent),label:yr(o.opened_by.label),session:yr(o.opened_by.session)}:null;t.push({id:s,name:ce(o.name),mtime:Ln(o.mtime)??0,locality:a,owner_device:ce(o.owner_device),owner_device_name:ce(o.owner_device_name),reachable:nr(o.reachable,!0),unreachable_reason:ce(o.unreachable_reason),live_state:ce(o.live_state),archived:nr(o.archived,!1),created_at:Ln(o.created_at),pinned:nr(o.pinned,!1),...typeof o.active=="boolean"?{active:o.active}:{},waiting_on:po(o.waiting_on),jobs_running:po(o.jobs_running),subagents_running:po(o.subagents_running),subagents_queued:po(o.subagents_queued),...typeof o.background_work=="boolean"?{background_work:o.background_work}:{},...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function g$(e){const{id:t,name:n,mtime:r,...o}=e;return{...o,session_id:t,title:n,updated_at:r}}function _$(e){if(!On(e))return null;const t=ce(e.session_id);if(!t)return null;const n=e.mode==="keep"?"keep":"move",r=ce(e.new_session_id)||(n==="move"?t:"");return r?{locality:e.locality==="local"?"local":"remote",owner_device:ce(e.owner_device),source_retired:nr(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:Br(e.phases).map(o=>({phase:ce(o.phase),peer:ce(o.peer),progress:typeof o.progress=="number"?o.progress:0}))}:null}const TR=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function b$(e){const t=e,n=ce(t?.code)||"move_refused",r=typeof t?.status=="number"?t.status:null;return{code:n,sentence:ce(t?.message)||_("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||TR.has(n)}}function v$(e){const t=ce(e.name);return t||_("ui.mesh.mesh_types.device_suffix",{suffix:ce(e.device_id).slice(-6)})}function CR(e){const t=ce(e.name);return t?JSON.stringify(t):_("ui.mesh.mesh_types.unnamed_device")}function OR(e,t){const n=ce(e);if(!t)return n;const r=t.map(ce).filter(s=>s.length>0&&s!==n);let o=Math.min(10,n.length);for(;o<n.length&&r.some(s=>s.startsWith(n.slice(0,o)));)o+=1;return o<n.length?`${n.slice(0,o)}…`:n}function y$(e,t,n=!1){const r=n?OR(e.id,t):ce(e.id);return`${CR(e)} ${r}`}function w$(e){const t=ce(e.name);return t||_("ui.mesh.mesh_types.network_suffix",{suffix:ce(e.network_id).slice(-6)})}const PR=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function MR(e){const t=e.trim();return t!==""&&PR.includes(t)}function $m(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"||MR(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const k$=()=>_("ui.mesh.mesh_graph.identity_suspect");function Nm(e){switch(e){case"self":return _("ui.mesh.mesh_drop.this_device");case"reached":return _("ui.mesh.mesh_reach.reached");case"relay-down":return _("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return _("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return _("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return _("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return _("ui.mesh.mesh_reach.not_a_member");case"unanswered":return _("ui.mesh.mesh_reach.no_answer");case"not-attempted":return _("ui.mesh.mesh_reach.not_asked");default:return _("ui.mesh.mesh_reach.unknown")}}function S$(e){const t=$m(e),n=Nm(t);return e.reason?`${n} — ${e.reason}`:n}const E$={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"},A$={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function I$(e){const t=e.trim();switch(t){case"ok":return _("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return _("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return _("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return _("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return _("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?_("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function R$(e){return e.reachable?"":e.remoteRelay==="not_listening"?_("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?_("ui.mesh.mesh_reach.peer_closed_handshake"):""}function x$(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>xR(r))?"working":"idle",source:"derived"}}function jR(e,t){const n={...e};for(const[r,o]of Object.entries(t))(!n[r]||o.at>=n[r].at)&&(n[r]=o);return n}function $R(e,t){if(e.locality!=="remote"||typeof e.owner_device!="string")return e;const n=t[e.owner_device];if(!n)return e.peer_reach||e.link_down?{...e,peer_reach:"unknown",link_down:!1,link_reconnecting:!1,reachable:!1,link_down_reason:null,last_seen_at:null}:e;const r=$m({state:"unreachable",reachable:n.reachable,reason:n.reason??"",sessionCount:n.session_count??null}),o=r==="unanswered",s=o&&n.redial_state==="reconnecting";return e.peer_reach===r&&e.link_down===o&&(e.link_reconnecting??!1)===s&&e.reachable===n.reachable&&e.last_seen_at===n.last_seen_at&&e.link_down_reason===n.reason?e:{...e,reachable:n.reachable,link_down:o,link_reconnecting:s,peer_reach:r,last_seen_at:n.last_seen_at,link_down_reason:n.reason}}function T$(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${_("ui.chat.canonical.transcript.reconnecting")} · ${dc(n,t)}`:_("ui.presence.link_down_last_seen",{age:dc(n,t)})}function dc(e,t){if(e===null)return _("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?_("ui.presence.just_now"):n<3600?_("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?_("ui.presence.hours_ago",{count:Math.floor(n/3600)}):_("ui.presence.days_ago",{count:Math.floor(n/86400)})}function C$(e,t){if(e.link_reconnecting===!0)return _("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return _("ui.presence.link_down_compact",{age:dc(n,t)})}function NR(e,t,n,r){if(r<=n)return{facts:e,watermark:n,removed:[]};const o=Object.fromEntries(Object.entries(e).filter(([,s])=>s.at>r));for(const[s,a]of Object.entries(t))(!o[s]||a.at>=o[s].at)&&(o[s]=a);return{facts:o,watermark:r,removed:Object.keys(e).filter(s=>!o[s])}}function O$(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?Nm(e.peer_reach):null}const DR=Object.freeze({}),yl=["model","effort","fast","cwd"],LR=new Set(["pending","applying","queued_next_step","waiting_idle"]);function Dm(e){return!!(e&&LR.has(e.state))}function FR(e,t){return t?e.request_id===t.request_id?t.local?!0:e.generation>t.generation||e.generation===t.generation&&!sf(e,t):e.generation!==t.generation?e.generation>t.generation:t.local?!1:!sf(e,t):!0}function sf(e,t){return!e.updated_at||!t.updated_at?!1:Date.parse(e.updated_at)<Date.parse(t.updated_at)}let Lm=0;const Fm=new WeakMap;function UR(e){return Fm.set(e,++Lm),e}function P$(){return Lm}function BR(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Wo(e,t,n){const r={...e};return Object.keys(n).length===0?delete r[t]:r[t]=n,r}function uc(e,t,n,r){const o=e[t]??{},s=o[n];if(r===null){if(!s||s.local)return e;const{[n]:a,...c}=o;return Wo(e,t,c)}return r.kind!==n||!FR(r,s)||s&&!s.local&&BR(r,s)?e:Wo(e,t,{...o,[n]:UR(r)})}function Um(e,t,n,r){let o=e;for(const s of yl){const a=n[s];if(a){o=uc(o,t,s,a);continue}if(r===void 0)continue;const c=o[t]?.[s];c&&(Fm.get(c)??0)>r||(o=uc(o,t,s,null))}return o}function HR(e,t,n,r=Number.POSITIVE_INFINITY){const o=n?[n]:[...new Set([...Object.keys(e),...Object.keys(t)])];let s=e;for(const a of o)s=Um(s,a,t[a]??{},r);return s}function WR(e,t,n,r=Date.now()){const o=e[t]??{},s=o[n.kind],a=new Date(r).toISOString(),c={kind:n.kind,value:n.value,effort:n.effort??null,request_id:n.requestId,generation:(s?.generation??0)+1,base:s?.base??null,state:"pending",attempts:0,created_at:a,updated_at:a,error:null,local:!0};return Wo(e,t,{...o,[n.kind]:c})}function GR(e,t,n,r,o,s=Date.now()){const a=e[t],c=a?.[n];return!a||!c||c.request_id!==r?e:Wo(e,t,{...a,[n]:{...c,state:"failed",error:o,updated_at:new Date(s).toISOString()}})}function zR(e,t,n,r){const o=e[t],s=o?.[n];if(!o||!s||s.generation!==r)return e;const{[n]:a,...c}=o;return Wo(e,t,c)}function M$(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"),r=t("effort"),o=t("fast"),s=t("cwd");return{model:typeof n?.value=="string"?n.value:null,effort:typeof r?.value=="string"?r.value:typeof n?.effort=="string"&&n.effort?n.effort:null,fast:typeof o?.value=="boolean"?o.value:null,cwd:typeof s?.value=="string"?s.value:null}}function j$(e){if(!e)return null;let t=null;for(const n of yl){const r=e[n];if(r?.state==="failed")return r;!t&&r&&Dm(r)&&(t=r)}return t}function $$(e){if(!e)return[];const t=[];for(const n of yl){const r=e[n];r&&(Dm(r)||r.state==="failed")&&t.push(r)}return t}function N$(e){const t=e.status??null;return{code:e.code??(t===null?"runtime_unreachable":"refused"),message:e.message??"",retryable:t===null||t>=500}}function D$(e,t){if(e===t)return[];const n=[];for(const[r,o]of Object.entries(t)){const s=o.cwd;if(s?.state!=="applied"||typeof s.value!="string")continue;const a=e[r]?.cwd;a?.state==="applied"&&a.request_id===s.request_id||n.push(s.value)}return n}function L$(e){return e.local?e.state==="failed"&&e.error?.retryable===!0:!0}const af=new Set;function F$(e){return af.has(e)?!1:(af.add(e),!0)}function U$(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?_("ui.chat.canonical.untitled"):n==="this chat"?_("ui.chat.canonical.this_chat"):n:t==="this_chat"?_("ui.chat.canonical.this_chat"):_("ui.chat.canonical.untitled")}function fc(e,t){return e.map((n,r)=>({id:`${t}:doc:${r}`,attachment:n.digest,filename:n.name??"Attached file",mimeType:n.mime_type??"application/octet-stream",path:n.path??null,storedPath:null,bytes:n.bytes??0}))}const ks=(e,t)=>e instanceof xe?Kc(e,t):e instanceof Error?e.message:t,Ei="session_unvalidated",KR=()=>_("ui.common.errors.session_unvalidated"),si="leading_slash_message",Bm=()=>_("ui.common.errors.leading_slash_message");function VR(e,t){return e instanceof xe&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const Hm="attachment_read_failed",Wm="store_out_of_space",Gm="store_unavailable";function cf(e){return e===Wm||e===Gm}const ZR="answer_not_sent",zm="aside_not_answered",Km="aside_still_answering";function ho(e){return e===si||e===Hm||e===Wm||e===Gm||e===ZR||e===zm||e===Km||e===Ei||e===mi}function YR(e){return e instanceof xe&&e.status===409&&wl(e)===void 0}function Vm(e,t=!1){return XR(e)||YR(e)&&!t?"not_sent":e instanceof xe&&e.status===404?"gone":"unknown"}function wl(e){if(e instanceof xe||e instanceof mn)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 _("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return _("ui.chat.canonical.send_failure.unreachable")},get busy(){return _("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return _("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return _("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return _("ui.chat.canonical.send_failure.retiring")},get notReady(){return _("ui.chat.canonical.send_failure.not_ready")},get generic(){return _("ui.chat.canonical.send_failure.generic")},get gone(){return _("ui.chat.canonical.send_failure.gone")},get sendLock(){return _("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return _("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return _("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return _("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return _("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return _("ui.chat.canonical.send_failure.late_delivery_overlap")}};function B$(e){return e?mt.gateLock:mt.sendLock}const H$=()=>_("ui.common.actions.retry"),W$=()=>_("ui.common.actions.clear");function JR(e,t,n=!1){const r=Vm(e,n),o=t??wl(e),s=Kc(e,mt.generic);return r==="gone"?{message:mt.gone,retry:!1,code:o}:r==="not_sent"?o===mi?{message:mt.busy,retry:!0,code:o}:o===Op?{message:mt.retiring,retry:!0,code:o}:o===He.serverUpdating?{message:Xn(o),retry:!0,code:o}:o===Ei?{message:mt.notReady,retry:!ho(o),code:o}:o===zm?{message:mt.asideNotAnswered,retry:!1,code:o}:o===Km?{message:mt.asideStillAnswering,retry:!1,code:o}:o===si?{message:Bm(),retry:!1,code:o}:{message:s,retry:!1,code:o}:zc(e)?{message:Xn(He.serverUpdating),retry:o===He.transportFailed,code:o}:o===He.transportFailed?{message:mt.unreachable,retry:!0,code:o}:gi(o)?{message:Xn(o),retry:!1,code:o}:o===Wc?{message:mt.unconfirmed,retry:!ho(o),code:o}:o===by.runtimeUnreachable?{message:mt.unconfirmed,retry:!0,code:o}:o?{message:s,retry:!ho(o),code:o}:{message:mt.unconfirmed,retry:!ho(o),code:o}}function pc(e){return e.trim()}function G$(e,t){if(t.length===0)return pc(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
45
- `);return pc(`${n}
46
- ${e}`)}function hc(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function QR(e,t,n,r){if(t.peer!==void 0||n?.locality==="remote"||r?.locality==="remote")return!1;const o=t.submittedAt;if(o===void 0||o<=0)return!1;const s=e[0]?.ts;return s===void 0||s<=0?!1:s*1e3<=o}function z$(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,s])=>hc(s,t));return(r.find(([,s])=>s.submittedText!==void 0||s.undelivered!==void 0||s.error!==void 0||s.admissionAttempted===!0||s.pending===!0)??r[0])?.[0]??`send:${t}`}function kl(e,t){return t??e??void 0}function Zm(e,t,n){return e?t??void 0:n??void 0}function K$(e,t,n){return kl(e,Zm(e,t,n))}function XR(e){return e instanceof xe?e.status===413||e.status===422?!0:e.code===mi||e.code===Op||e.code===He.noCredential||e.code===He.serverUpdating||cf(e.code):e instanceof mn&&(e.code===Ei||e.code===Hm||cf(e.code))}function es(e,t){const n=e.startsWith("send:")?e.slice(5):null;return kl(e.startsWith("draft:")?e:null,t??n)??e}function qR(e,t){const n=ct.getState(),r=es(e,t),o=r===""||r===e?[e]:[e,r];n.settleInFlight(o),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function V$(e,t){if(!t||t.migratedHeld||t.pending||!(t.heldClaimCode!==void 0||t.errorRetry===void 0&&t.submittedRendered===void 0)||!t.admissionAttempted||t.submittedText===void 0)return!1;const r=es(e,t.sessionId);return ct.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),St.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:mt.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!ho(t.heldClaimCode),heldClaimCode:void 0}),!0}function Z$(e,t){if(!t)return!1;const n=t.undelivered,r=t.submittedText,o=r!==void 0&&t.error!==void 0&&t.errorRetry!==void 0;if(!n&&!o)return!1;const s=es(e,t.sessionId);if(n){if(rf(s,n.recordId))return!1;const c=Tm(s,n.recordId);return c!=="unseen"?(c==="owner"&&St.getState().retractUndelivered(e,n.recordId),!1):(sc(s,{id:n.recordId,text:n.text,images:[],documents:fc(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const a=t.admissionRequestId;return rf(s,a)?!1:(sc(s,{id:a,text:t.submittedRendered??r,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${a}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type})),documents:fc(t.submittedFiles??[],a)}),!0)}function lf(e,t,n){aR(es(e,t),n)}function ex(e,t,n){if(e.submittedText!==t)return!1;const r=e.submittedAttachments??[];return r.length!==n.length?!1:r.every((o,s)=>o===n[s])}function tx(e,t){return!!t&&e===t}const nx=3,rx=5e3,ox=2e3;async function sx(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=nx||!(n instanceof xe)||n.code!==mi)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??ox),rx);await new Promise(o=>setTimeout(o,r))}}async function ix(e){await sx(async()=>{await Qe(e)})}async function Y$(e,t,n,r,o){const s=St.getState();if(tx(s.validatingSessionId,n))throw new mn(KR(),Ei);const a=s.drafts[e];if(a?.pending)return null;const c=pc(t.text),l=a?.submittedText!==void 0&&ex(a,c,t.attachments),d=a??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?a?.submittedImages??t.images:t.images,f=l?a?.submittedFiles??t.files:t.files,h=l?a?.submittedMode??t.mode:t.mode,m=l&&a?a.submittedInputMode:t.inputMode,y=l&&a?a.submittedInputPath:t.inputPath,b=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),v=Date.now();s.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:b,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:h,submittedInputMode:m,submittedInputPath:y,error:void 0,errorCode:void 0,submittedAt:v});const p=kl(e.startsWith("draft:")?e:null,n??d.sessionId)??null;p&&sc(p,{id:b,submittedAt:v,text:c,images:u.map((L,O)=>({id:`${b}:${O}`,data:L.data_b64,attachment:null,mimeType:L.mime_type})),documents:fc(f??[],b),onPainted:r});let A=l,k=n??d.sessionId,C=null;try{if(!k){if(C="sessions.create",k=await s.createSession(t.cwd,d.target,d.createRequestId,vl(d.model??null,s.draftFastCarries),d.warmId,d.peer)??void 0,!k)throw new mn(St.getState().error??_("ui.common.errors.chat_start_simple"));s.updateDraft(e,{sessionId:k}),p&&nR(p,k),s.fetchSessions()}const L=l&&a?.submittedRendered!==void 0?a.submittedRendered:o?await o(k)??c:c;return A=!0,s.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:L}),k&&tR(k,b,L),C="sessions.message",await ix({op:"sessions.message",sessionId:k,requestId:b,text:L,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:h,inputMode:m,inputPath:y}),s.finishDraft(e,k),St.setState({error:null}),k}catch(L){St.setState({error:null});const O=l&&a?.admissionAttempted===!0,I=Vm(L,O),g=C==="sessions.message"&&VR(L,c),w=g?si:wl(L),S=JR(L,w,O);let x=!1;const F=k??p??void 0;if(F&&I==="unknown"&&(x=A&&Tm(F,b)==="owner"),s.updateDraft(e,{pending:!1,admissionAttempted:I==="unknown"&&A,errorCode:w,error:S.message,errorRetry:S.retry}),x)return k?(s.finishDraft(e,k),k):null;const j=es(e,k??d.sessionId),X=p&&p!==j?[p,j]:[j];throw ct.getState().settleInFlight(X),p&&p!==j&&ct.getState().returnInFlight(p,j),F&&ac(F,b),e!==F&&ac(e,b),g?new xe(422,Bm(),L,si):L}}const Ym=50,df="activity",ax=25,cx=500;function lx(e){return e?Ym:cx}function uf(e,t){return`${e}:${t}`}function dx(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function ux(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function fx(e,t){const n=new Set;for(const[r,o]of Object.entries(t))o.locality==="remote"&&n.add(r);for(const r of e)r.locality==="remote"&&n.add(r.session_id);return n}function px(e,t,n){if(t[n]?.locality==="remote")return!0;for(const r of e)if(r.session_id===n&&r.locality==="remote")return!0;return!1}function hx(e){const t=new Set(e.tailIds),n=new Set(e.keepIds??[]),r=new Set(e.page.map(c=>c.session_id)),o=e.sessions.filter(c=>r.has(c.session_id)?!1:e.scopeIds.has(c.session_id)||n.has(c.session_id)?!0:t.has(c.session_id)),s=e.merge(e.sessions,e.page),a=new Set(s.map(c=>c.session_id));for(const c of o)a.has(c.session_id)||(a.add(c.session_id),s.push(c));return{rows:s,tailIds:e.tailIds.filter(c=>a.has(c))}}function mx(e){const t=[...e.previousIds],n=new Set(t);for(const s of e.page)n.has(s.session_id)||(n.add(s.session_id),t.push(s.session_id));const r=[...e.sessions],o=new Map(r.map((s,a)=>[s.session_id,a]));for(const s of e.page){const a=o.get(s.session_id);if(a===void 0){o.set(s.session_id,r.length),r.push(s);continue}r[a]=e.merge(r[a],s)}return{rows:r,ids:t}}function Kn(e,t){return{...e,...t,...bx(e,t),...vx(t,e),attention:Ar(e?.attention,t.attention,t.session_id)}}const J$=Pm,gx=e=>e.filter(Mm),ff=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const o=e[r],s=Ar(o.attention,n,t);if(s===o.attention)return e;const a=e.slice();return a[r]={...o,attention:s},a},_x=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function bx(e,t){const n=r=>typeof r?.status_revision=="number"&&typeof r?.status_epoch=="string"?{status_revision:r.status_revision,status_epoch:r.status_epoch}:void 0;return n(t)??n(e)??{}}function vx(e,t){const n=typeof t?.status_epoch=="string"&&t.status_epoch===e.status_epoch,r=t?.status_revision,o=e.status_revision;return t?.status!==void 0&&n&&typeof r=="number"&&typeof o=="number"&&r>o?{status:t?.status,status_revision:t?.status_revision,status_epoch:t?.status_epoch,...typeof t?.background_work=="boolean"?{background_work:t.background_work,subagents_running:t.subagents_running,subagents_queued:t.subagents_queued,jobs_running:t.jobs_running,waiting_on:t.waiting_on}:{}}:{}}function yx(e,t){const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(s.at<t){r=!0;continue}n[o]=s}return r?n:e}function ga(e,t){const n={...e.archiveFacts};delete n[t];const r={...e.placementFacts};delete r[t];const o=e.answerSeq+1;return{sessions:e.sessions.filter(s=>s.session_id!==t),archiveFacts:n,placementFacts:r,answerSeq:o,forgotten:{...e.forgotten,[t]:{at:o,title:e.sessions.find(s=>s.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function Jm(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 Qm(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 Xm(e,t,n){const r=ct.getState();if(t&&t!==e){r.adoptReturnedText(t);const o=ct.getState().inputByConversation[t];o&&o.inFlight===void 0&&((o.currentInput??"")!==""||(o.attachments?.length??0)>0)&&r.returnInFlight(t,e)}n&&r.returnPayload(e,{text:n.text,attachments:n.attachments,replies:[]})}function wx(e,t,n){const r=ct.getState(),o=n??(e?r.getCurrentInput(e):"");o&&r.setComposerText(t,o),e&&e!==t&&r.setComposerText(e,"")}function kx(e,t){let n=null;const r=[];for(const[o,s]of Object.entries(e))!s.sessionId||t[s.sessionId]===void 0||(n??={...e},n[o]=Jm(s),r.push({key:o,sessionId:s.sessionId,payload:Qm(s)}));return{drafts:n??e,restored:r}}function qm(e){return e.map(({id:t,name:n,mtime:r,...o})=>({...o,session_id:t,title:n,updated_at:r}))}function pf(e,t){return qm(e).filter(n=>t[n.session_id]===void 0)}function _a(e){return typeof e=="string"&&e.length>0?e:null}function Sx(e){if(e===null||typeof e!="object")return null;const t=e,n=c=>typeof c=="number"&&Number.isFinite(c)&&c>=0?Math.floor(c):null,r=n(t.total),o=n(t.active),s=n(t.unbound);if(r===null||o===null||s===null||!Array.isArray(t.scopes))return null;const a=[];for(const c of t.scopes){if(c===null||typeof c!="object")return null;const l=c;if(l.kind!=="team"&&l.kind!=="agent"||typeof l.name!="string"||l.name.length===0)continue;const d=n(l.total),u=n(l.active);d===null||u===null||a.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:r,active:o,unbound:s,scopes:a}}function Ex(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Kn(n.get(r.session_id),r)])).values()]}let ba=0,gr=null;function Ax(e,t,n){const r=gr;if(r)return r.invalidated=!0,r.limit=e,r.withCounts=t,r.promise;const o={limit:e,withCounts:t,invalidated:!1,promise:null};return gr=o,o.promise=(async()=>{try{for(;;){o.invalidated=!1;let s;try{s=await n(o.limit,o.withCounts)}catch(a){if(o.invalidated)continue;throw a}if(!o.invalidated)return gr===o&&(gr=null),s}}finally{gr===o&&(gr=null)}})(),o.promise}function eg(){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 Ix(){const e=eg();return e.kind==="session"?e.sessionId:null}function Rx(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 xx(e,t){const n={...t,...e},{drafts:r,restored:o}=kx(n.drafts,n.forgotten),s=r===n.drafts?n:{...n,drafts:r};for(const l of o)Xm(l.key,l.sessionId,l.payload);const a=eg();if(a.kind==="session")return{...s,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...s,activeSessionId:null};const c=Rx(s);return c?{...s,...c}:s}const St=Qo()(_i((e,t)=>({sessions:[],settingsIntents:DR,hydrateSettingsIntents:(n,r,o)=>{e(s=>{const a=HR(s.settingsIntents,n,r,o);return a===s.settingsIntents?s:{settingsIntents:a}})},applySettingsIntentFrame:(n,r,o)=>{e(s=>{const a=uc(s.settingsIntents,n,r,o);return a===s.settingsIntents?s:{settingsIntents:a}})},applySettingsIntentSlots:(n,r)=>{e(o=>{const s=Um(o.settingsIntents,n,r);return s===o.settingsIntents?o:{settingsIntents:s}})},paintSettingsIntent:(n,r)=>{e(o=>({settingsIntents:WR(o.settingsIntents,n,r)}))},failSettingsIntent:(n,r,o,s)=>{e(a=>{const c=GR(a.settingsIntents,n,r,o,s);return c===a.settingsIntents?a:{settingsIntents:c}})},removeSettingsIntent:(n,r,o)=>{e(s=>{const a=zR(s.settingsIntents,n,r,o);return a===s.settingsIntents?s:{settingsIntents:a}})},cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:Ix(),activeDraftKey:null,drafts:{},validatingSessionId:null,pinFailure:null,pinFacts:{},answerSeq:0,readAckRearm:null,readAckNotice:null,loading:!1,truncated:!1,head:{pageIds:[],tailIds:[],nextCursor:null,tailCursor:null,tailStarted:!1,complete:!1,loading:!1,error:null,at:0},scopes:{},counts:null,statusUnavailable:[],archiveFacts:{},placementFacts:{},peerDeviceFacts:{},peerDeviceSnapshotAt:0,forgotten:{},stoppedTurns:{},archiveFailure:null,archiveUndo:null,draftsUndo:null,bulkReadDeferral:null,stagedByDiscard:null,deleteCandidate:null,archiveCandidate:null,error:null,cwd:"~",setCwd:n=>e(r=>{const o=Object.entries(r.drafts);return o.some(([,s])=>!s.sessionId)?{cwd:n,drafts:Object.fromEntries(o.map(([s,a])=>a.sessionId?[s,a]:[s,{...a,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=lx(t().cataloguePageable),r=!1)=>{const o=++ba,s=t().answerSeq+1;e({answerSeq:s}),e({loading:!0,error:null});try{const a=await Ax(n,r,(l,d)=>Qe({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:df}:{}}));if(o!==ba)return;const c=qm(a.sessions);e(l=>{const d={...l.pinFacts};for(const[g,w]of Object.entries(d))w.at>=s||delete d[g];const u=new Set(c.map(g=>g.session_id));let f=!1;const h={...l.forgotten};for(const[g,w]of Object.entries(h))w.at<s&&u.has(g)&&(delete h[g],f=!0);const m=f?h:l.forgotten,y=c.filter(g=>m[g.session_id]===void 0);let b=null;for(const g of y){const w=l.placementFacts[g.session_id];if(w===void 0||w.at>=s)continue;const S=g.locality==="remote"?"remote":g.locality==="local"?"local":null;S!==null&&(b??={...l.placementFacts},b[g.session_id]={locality:S,owner_device:typeof g.owner_device=="string"?g.owner_device:"",at:l.answerSeq+1})}const v=_a(a.next_cursor),p=v===null&&a.truncated!==!0,A=y.map(g=>g.session_id),k=l.sessions.filter(g=>m[g.session_id]===void 0&&(l.pinFacts[g.session_id]?.at??-1)>=s),C=hx({sessions:l.sessions,scopeIds:dx(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...ux(l.placementFacts)],tailIds:p?[]:l.head.tailIds,page:y,merge:Ex});let L=C.rows;for(const g of k){const w=l.pinFacts[g.session_id],S=L.findIndex(x=>x.session_id===g.session_id);S===-1?L=[...L,{...g,pinned:w.pinned}]:L[S]={...L[S],pinned:w.pinned}}const O=yx(l.archiveFacts,s),I=Sx(a.counts);return{sessions:L,pinFacts:d,archiveFacts:O,...b===null?{}:{placementFacts:b,answerSeq:l.answerSeq+1},forgotten:m,loading:!1,truncated:a.truncated===!0,head:{pageIds:A,tailIds:C.tailIds,nextCursor:v,tailCursor:p?null:l.head.tailStarted?l.head.tailCursor:v,tailStarted:l.head.tailStarted,complete:p,loading:!1,error:null,at:s},...I===null?{}:{counts:I},statusUnavailable:Array.isArray(a.degraded)?a.degraded.filter(g=>typeof g=="string"):[]}})}catch(a){o===ba&&e({loading:!1,error:ks(a,_("ui.common.errors.chats_refresh"))})}},fetchCatalogueTail:async()=>{const n=t().head,r=n.tailCursor;if(!(r===null||n.loading)){e(o=>({head:{...o.head,loading:!0,error:null,tailStarted:!0,tailCursor:r}}));try{const o=await Qe({op:"sessions.list",limit:Ym,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:df}:{}}),s=pf(o.sessions,t().forgotten);e(a=>{const c=new Map(a.sessions.map((f,h)=>[f.session_id,h])),l=[...a.sessions],d=[];for(const f of s){const h=c.get(f.session_id);if(h===void 0){c.set(f.session_id,l.length),l.push(f),d.push(f.session_id);continue}l[h]=Kn(l[h],f)}const u=_a(o.next_cursor);return{sessions:l,head:{...a.head,tailIds:[...a.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(o){e(s=>({head:{...s.head,loading:!1,error:ks(o,_("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,o=null,s=ax)=>{const a=uf(n,r);if(t().scopes[a]?.loading)return;const c=t().answerSeq+1;e({answerSeq:c}),e(l=>({scopes:{...l.scopes,[a]:{ids:l.scopes[a]?.ids??[],nextCursor:l.scopes[a]?.nextCursor??null,loading:!0,error:null,at:c}}}));try{const l=await Qe({op:"sessions.list",limit:s,include_archived:!1,scope_kind:n,scope_name:r,...o===null?{}:{cursor:o}}),d=pf(l.sessions,t().forgotten);e(u=>{const f=u.scopes[a];if(f===void 0||f.at!==c)return{};const h=o!==null&&l.cursor_missing!==!0,m=mx({sessions:u.sessions,previousIds:h?f.ids:[],page:d,merge:Kn}),y=_a(l.next_cursor);return{sessions:m.rows,scopes:{...u.scopes,[a]:{ids:m.ids,nextCursor:y,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[a];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[a]:{...u,loading:!1,error:ks(l,_("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const o=uf(n,r);e(s=>{const a=s.scopes[o];if(a===void 0)return{};const c={...s.scopes};delete c[o];const l=s.activeSessionId,d=new Set(a.ids),u=new Set(s.head.pageIds),f=s.sessions.filter(h=>!d.has(h.session_id)||u.has(h.session_id)||l!==null&&h.session_id===l);return{scopes:c,sessions:f}})},setCataloguePageable:n=>{t().cataloguePageable!==n&&e({cataloguePageable:n})},setCatalogueActivityHead:n=>{t().catalogueActivityHead!==n&&e({catalogueActivityHead:n})},setDraftFastCarries:n=>{t().draftFastCarries!==n&&e({draftFastCarries:n})},setDraftWarmable:n=>{if(t().draftWarmable===n||(e({draftWarmable:n}),!n))return;const r=t().activeDraftKey,o=r?t().drafts[r]:void 0;if(!r||!o||o.sessionId||o.warmId)return;ct.getState().inputByConversation[r]?.currentInput&&t().ensureDraftWarm(r)},setArchiveUndo:n=>{e({archiveUndo:n})},setDraftsUndo:n=>{e({draftsUndo:n})},raiseBulkReadDeferral:n=>{e(r=>({bulkReadDeferral:{count:n,at:r.answerSeq+1}}))},clearBulkReadDeferral:()=>{e({bulkReadDeferral:null})},setStagedByDiscard:n=>{e({stagedByDiscard:n})},restoreDraftsUndo:()=>e(n=>{const r=n.draftsUndo;if(!r)return{};const o={...n.drafts};for(const[a,c]of Object.entries(r.drafts))a in o||(o[a]=c);const s=ct.getState();for(const[a,c]of Object.entries(r.composer)){const l=s.inputByConversation[a];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||s.restoreRow(a,c)}return{drafts:o,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,r,o)=>{const s=t().answerSeq+1,a=t().archiveFacts[n]??null,c=o??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:s,archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:s,answered:!1}}}));try{return await Qe({op:"sessions.archive",sessionId:n,archived:r}),e(l=>{const u=l.archiveFacts[n]?.at!==s;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:s,answered:!0}},archiveUndo:u?l.archiveUndo:r?{sessionId:n,title:c??void 0,archived:!0,at:s}:null,archiveFailure:l.archiveFailure?.sessionId===n?null:l.archiveFailure}}),!0}catch(l){return e(d=>{const u=d.archiveFacts[n]?.at!==s,f={...d.archiveFacts};return u||(a?.answered===!0?f[n]=a:(delete f[n],a!==null&&t().fetchSessions())),{archiveFacts:u?d.archiveFacts:f,answerSeq:d.answerSeq+1,archiveFailure:{sessionId:n,at:d.answerSeq+1,archived:r,title:c||"",detail:l instanceof xe&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await Qe({op:"sessions.delete",sessionId:n,confirmed:!0}),e(r=>ga(r,n)),t().retireDraftsForSession(n),{ok:!0}}catch(r){const o=r instanceof xe?r.status:null,s=r instanceof xe?r.code??null:null;return o===404?(e(a=>ga(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:s==="session_delete_refused",detail:r instanceof xe&&r.message?r.message:_("ui.common.errors.conversation_delete")}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,o=crypto.randomUUID(),s,a,c)=>{try{const l=await Qe({op:"sessions.create",requestId:o,cwd:n,...r?{target:r}:{},...s?{model:s}:{},...a?{draftId:a}:{},...c?{peer:c}:{}});return t().upsertSession({session_id:l.session_id,cwd:n,binding:l.binding}),c&&t().settlePlacement(l.session_id,{locality:"remote",owner_device:c}),l.session_id}catch(l){throw e({error:ks(l,_("ui.common.errors.chat_start"))}),l}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,r=Date.now())=>e(o=>({stoppedTurns:{...o.stoppedTurns,[n]:r}})),clearTurnStopped:n=>e(r=>{if(!(n in r.stoppedTurns))return r;const{[n]:o,...s}=r.stoppedTurns;return{stoppedTurns:s}}),openDraft:n=>{t().drafts[n]&&e({activeDraftKey:n,activeSessionId:null,validatingSessionId:null,error:null})},confirmSessionLive:n=>{n&&t().validatingSessionId===n&&e({validatingSessionId:null})},confirmSessionMissing:n=>{!n||t().validatingSessionId!==n||(e({validatingSessionId:null,...ga(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:_x(r.readAckRearm,n)}))},publishReadAckNotice:(n,r,o)=>{e(s=>{const a=s.readAckNotice;return a?.sessionId===n&&a.kind===r?s:{readAckNotice:{sessionId:n,kind:r,revision:(a?.revision??0)+1,reason:o}}})},clearReadAckNotice:n=>{e(r=>r.readAckNotice?.sessionId===n?{readAckNotice:null}:r)},applyAttention:(n,r)=>{e(o=>{const s=ff(o.sessions,n,r);return s===o.sessions?o:{...o,sessions:s}})},applyAttentionMany:n=>{e(r=>{let o=r.sessions;for(const s of n){const a=s?.conversation_id;typeof a!="string"||!a.startsWith("session/")||(o=ff(o,a.slice(8),s))}return o===r.sessions?r:{...r,sessions:o}})},markAllRead:async()=>{const n=gx(t().sessions).map(a=>({sessionId:a.session_id,completionToken:a.attention?.completion_token}));if(n.length===0)return{attempted:0,cleared:0,superseded:0,unknown:0,deferred:0};const r=await Qe({op:"attention.seen",items:n});t().applyAttentionMany(r.read);const o=fx(t().sessions,t().placementFacts),s=r.unknown.filter(a=>o.has(a)).length;return{attempted:n.length,cleared:r.read.length,superseded:r.superseded.length,unknown:r.unknown.length,deferred:s}},applySessionStatus:(n,r,o,s,a)=>{e(c=>{const l=c.sessions.findIndex(y=>y.session_id===n);let d=!1;const u=c.sessions.map(y=>{if(y.status_epoch===void 0&&y.status_revision===void 0||y.status_epoch===s)return y;d=!0;const{status_revision:b,status_epoch:v,...p}=y;return p});if(l<0)return d?{...c,sessions:u}:c;const f=u[l],m=!(a!==void 0&&Object.keys(a).some(y=>f[y]!==a[y]))&&f.status?.code===r.code&&f.status?.label===r.label&&f.status_revision===o&&f.status_epoch===s;return m&&!d?c:(m||(u[l]={...f,...a,status:r,status_revision:o,status_epoch:s}),{...c,sessions:u})})},openSession:async n=>t().activeSessionId===n&&!t().activeDraftKey?(t().rearmReadAck(n),!0):(e({activeSessionId:n,activeDraftKey:null,validatingSessionId:n,error:null}),t().rearmReadAck(n),!0),stageDraft:(n,r=!1)=>{const s=(!r&&n?`draft:${n.kind}:${n.name}`:null)??`draft:${crypto.randomUUID()}`,a=t().drafts[s],c=Zm(t().activeDraftKey,t().activeDraftKey?t().drafts[t().activeDraftKey]?.sessionId:void 0,t().activeSessionId);if(a?.sessionId&&!a.pending&&a.sessionId!==c){const d=t().drafts[`send:${a.sessionId}`]?`draft:${crypto.randomUUID()}`:`send:${a.sessionId}`;e(u=>{const f={...u.drafts};return delete f[s],f[d]={...a,key:d},{drafts:f}})}const l=t().drafts[s];return e(d=>({activeDraftKey:s,validatingSessionId:null,error:null,drafts:{...d.drafts,[s]:l??{key:s,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),s},restageDraft:(n,r)=>{const o=t().activeDraftKey,s=t().stageDraft(n);return wx(o,s,r),s},startNewChat:n=>{const r=t().stageDraft();return e({activeSessionId:null,validatingSessionId:null}),n&&(ct.getState().adoptReturnedText(n),ct.getState().inputByConversation[n]?.pendingText===void 0&&ct.getState().returnInFlight(n,r)),r},updateDraft:(n,r)=>e(o=>{const s=o.drafts[n],a=r.key!==void 0&&r.createRequestId!==void 0&&r.admissionRequestId!==void 0;return!s&&!a?{}:{drafts:{...o.drafts,[n]:{...o.drafts[n],...r}}}}),setDraftPeer:(n,r)=>e(o=>{const s=o.drafts[n];if(!s)return{};const a=r??void 0;return(s.peer??void 0)===a?{}:{drafts:{...o.drafts,[n]:{...s,peer:a,...s.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}}),setDraftModel:(n,r)=>e(o=>{const s=o.drafts[n];return s?{drafts:{...o.drafts,[n]:{...s,model:r,...s.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}:{}}),ensureDraftWarm:n=>{const r=t();if(!r.draftWarmable)return;const o=r.drafts[n];if(!o||o.sessionId||o.warmId||!r.cwd||o.peer)return;const s=o.draftRequestId??crypto.randomUUID();o.draftRequestId||t().updateDraft(n,{draftRequestId:s});const a=vl(o.model??null,r.draftFastCarries);Qe({op:"sessions.draft",requestId:s,cwd:r.cwd,...o.target?{target:o.target}:{},...a?{model:a}:{}}).then(c=>{const l=t().drafts[n];l&&!l.warmId&&!l.sessionId&&l.draftRequestId===s&&t().updateDraft(n,{warmId:c.draft_id})}).catch(()=>{})},finishDraft:(n,r)=>e(o=>{qR(n,r);const s={...o.drafts};return delete s[n],{drafts:s,...o.activeDraftKey===n?{activeDraftKey:null,activeSessionId:r}:{}}}),retireDraftSession:n=>{const r=t().drafts[n];if(!r?.sessionId||r.pending)return;const o=r.sessionId,s=Qm(r);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:Jm(c)}}}),Xm(n,o,s)},retireDraftsForSession:n=>{for(const[r,o]of Object.entries(t().drafts))r.startsWith("draft:")&&o.sessionId===n&&t().retireDraftSession(r)},retireDraftWarm:n=>{const r=Object.entries(t().drafts).filter(([o,s])=>o.startsWith("draft:")&&s.warmId===n&&!s.sessionId);r.length!==0&&e(o=>{const s={...o.drafts};for(const[a]of r){const c=s[a];!c||c.warmId!==n||c.sessionId||(s[a]={...c,warmId:void 0,draftRequestId:crypto.randomUUID()})}return{drafts:s}})},discardDraft:n=>e(r=>{const o={...r.drafts},s=o[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),a=o[n],c=ct.getState().inputByConversation[n];ys(n),s&&s!==n&&ys(s),delete o[n],ct.getState().clearAll(n);const l=a?{at:r.answerSeq+1,keys:[n],drafts:{[n]:a},composer:c?{[n]:c}:{}}:null;return{drafts:o,...l?{answerSeq:l.at,draftsUndo:l}:{},...r.activeDraftKey===n?{activeDraftKey:null}:{}}}),discardDrafts:n=>e(r=>{const o={...r.drafts};let s=!1;const a=[],c={},l={};for(const u of n){if(!(u in o))continue;const f=o[u];if(!f)continue;const h=f.sessionId??(u.startsWith("send:")?u.slice(5):void 0);ys(u),h&&h!==u&&ys(h),a.push(u),c[u]=f;const m=ct.getState().inputByConversation[u];m&&(l[u]=m),delete o[u],ct.getState().clearAll(u),r.activeDraftKey===u&&(s=!0)}if(a.length===0)return{};const d=r.answerSeq+1;return{drafts:o,answerSeq:d,draftsUndo:{at:d,keys:a,drafts:c,composer:l},...s?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,r,o)=>e(s=>{const a=r.map(S=>S.id),c=Object.entries(s.drafts).filter(([,S])=>hc(S,n)&&S.undelivered!==void 0&&a.includes(S.undelivered.recordId));let l=s.drafts;if(c.length>0){l={...l};for(const[S,x]of c){const F=x.undelivered?.recordId,{undelivered:j,...X}=x;l[S]=X,F!==void 0&&lf(S,x.sessionId,F)}}const d=Object.entries(l).find(([,S])=>hc(S,n)&&S.admissionAttempted===!0&&S.pending!==!0&&S.submittedText!==void 0);if(!d)return c.length>0?{drafts:l}:{};const[u,f]=d,h=f.admissionRequestId,m=a.includes(h);if(!m&&!o)return c.length>0?{drafts:l}:{};if(!m&&!QR(r,f,s.placementFacts[n],s.sessions.find(S=>S.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:y,submittedText:b,submittedAttachments:v,submittedImages:p,submittedMode:A,submittedInputMode:k,submittedInputPath:C,heldClaimCode:L,error:O,errorCode:I,errorRetry:g,...w}=f;return m||ac(n,h),{drafts:{...l,[u]:{...w,...m?{}:{undelivered:{recordId:h,text:b??"",attachments:v??[]}},admissionRequestId:crypto.randomUUID()}}}}),retractUndelivered:(n,r)=>{const o=t().drafts[n];!o||o.undelivered?.recordId!==r||(e(s=>{const{undelivered:a,...c}=s.drafts[n];return{drafts:{...s.drafts,[n]:c}}}),lf(n,o.sessionId,r))},bindSession:(n,r)=>t().setActiveSession(r),beginAnswer:()=>{const n=t().answerSeq+1;return e({answerSeq:n}),n},applySearchAnswer:(n,r)=>e(o=>{let s=null,a=null,c=null;for(const l of r){const d=o.archiveFacts[l.id];if(d!==void 0&&d.at<n&&(c=c??{...o.archiveFacts},delete c[l.id]),!(d!==void 0&&d.at>=n)&&typeof l.archived=="boolean"&&o.sessions.some(f=>f.session_id===l.id&&f.archived!==l.archived)){a=a??o.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.archived=l.archived===!0)}if(typeof l.pinned!="boolean")continue;const u=o.pinFacts[l.id];if(!(u!==void 0&&u.at>=n)&&(u!==void 0&&(s=s??{...o.pinFacts},delete s[l.id]),o.sessions.some(f=>f.session_id===l.id&&f.pinned!==l.pinned))){a=a??o.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return s===null&&a===null&&c===null?{}:{...s===null?{}:{pinFacts:s},...a===null?{}:{sessions:a},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,r,o)=>{const s=t().sessions.find(h=>h.session_id===n),a=t().pinFacts[n]??null,c=s===void 0?a?.pinned??!1:s.pinned===!0,l=s===void 0&&o!==void 0?{session_id:n,title:o.title||"",updated_at:o.updated_at,pinned:r}:null,d=t().beginAnswer(),u=s?.title??o?.title,f=s?.updated_at??o?.updated_at;e(h=>({sessions:l===null?h.sessions.map(m=>m.session_id===n?{...m,pinned:r}:m):[...h.sessions,l],pinFacts:{...h.pinFacts,[n]:{pinned:r,at:d,title:u,updated_at:f}},pinFailure:null}));try{const h=await Qe({op:"sessions.pin",sessionId:n,pinned:r});let m=!1;return e(y=>{const b=y.pinFacts[n];return b===void 0||b.at!==d?{}:(m=!0,{sessions:y.sessions.map(v=>v.session_id===n?{...v,pinned:h.pinned===!0}:v),pinFacts:{...y.pinFacts,[n]:{...b,pinned:h.pinned===!0}}})}),m}catch(h){return e(m=>{const y=m.pinFacts[n];if(y!==void 0&&y.at!==d)return{};const b={...m.pinFacts};return a===null&&s===void 0?delete b[n]:b[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:m.sessions.map(v=>v.session_id===n?{...v,pinned:c}:v),pinFacts:b,pinFailure:{sessionId:n,pinned:r,title:s?.title||"",detail:Kc(h,"")}}}),!1}},upsertSession:n=>e(r=>({sessions:r.sessions.some(s=>s.session_id===n.session_id)?r.sessions.map(s=>s.session_id===n.session_id?Kn(s,n):s):[...r.sessions,n]})),settlePlacement:(n,r)=>{const o=t().beginAnswer();e(s=>({sessions:s.sessions.map(a=>a.session_id===n?Kn(a,{session_id:n,locality:r.locality,owner_device:r.owner_device}):a),placementFacts:{...s.placementFacts,[n]:{locality:r.locality,owner_device:r.owner_device,at:o}}}))},settlePeerCatalogue:(n,r,o={},s=void 0)=>{e(a=>{const c={...a.forgotten};for(const g of n)c[g.session_id]?.at<r&&delete c[g.session_id];const l=n.filter(g=>{if(c[g.session_id]||g.locality==="remote"&&a.peerDeviceSnapshotAt>r&&typeof g.owner_device=="string"&&!a.peerDeviceFacts[g.owner_device])return!1;const w=a.placementFacts[g.session_id];return!w||w.at<r}),d={...a.placementFacts},u=new Set;let f=!1,h=0;for(const g of l){const w=g.locality==="remote"?"remote":g.locality==="local"?"local":null;if(w===null)continue;const S=a.placementFacts[g.session_id];if(S!==void 0){if(S.at>=r)continue}else if(w!=="remote")continue;h=h===0?a.answerSeq+1:h,u.add(g.session_id),d[g.session_id]={locality:w,owner_device:w==="remote"&&typeof g.owner_device=="string"?g.owner_device:"",at:h},f=!0}const m=s===void 0?null:NR(a.peerDeviceFacts,o,a.peerDeviceSnapshotAt,s),y=m?.facts??jR(a.peerDeviceFacts,Object.fromEntries(Object.entries(o).filter(([,g])=>g.at>a.peerDeviceSnapshotAt))),b=l.filter(g=>g.locality==="remote");let v=a.sessions,p=!1;const A=[],k=new Map;for(let g=0;g<v.length;g+=1)k.set(v[g].session_id,g);for(const g of b){const w=k.get(g.session_id);if(w===void 0){A.push(g);continue}v[w]!==g&&(p||(v=v.slice(),p=!0),v[w]=Kn(v[w],g))}A.length>0&&(v=[...v,...A]);for(const g of l){if(g.locality==="remote"||!u.has(g.session_id))continue;const w=k.get(g.session_id);w===void 0||v[w]===g||(p||(v=v.slice(),p=!0),v[w]=Kn(v[w],g))}const C=new Set(l.map(g=>g.session_id)),L=new Set;for(const g of l)g.locality==="remote"&&typeof g.owner_device=="string"&&g.owner_device!==""&&g.reachable!==!1&&L.add(g.owner_device);const O=new Set;for(const g of v){if(g.locality!=="remote"||typeof g.owner_device!="string"||!m?.removed.includes(g.owner_device))continue;const w=a.placementFacts[g.session_id];w&&w.at>=(s??0)||(O.add(g.session_id),delete d[g.session_id])}for(const[g,w]of Object.entries(a.placementFacts))w.locality==="remote"&&(C.has(g)||w.at>=r||y[w.owner_device]?.reachable!==!1&&(w.owner_device===""||!L.has(w.owner_device)||(O.add(g),delete d[g])));O.size>0&&(v=v.filter(g=>!O.has(g.session_id)));const I=v.map(g=>$R(g,y));return I.some((g,w)=>g!==v[w])&&(v=I,p=!0),!f&&A.length===0&&!p&&O.size===0&&Object.keys(o).length===0&&s===void 0?{}:{sessions:v,placementFacts:d,peerDeviceFacts:y,peerDeviceSnapshotAt:m?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:xx,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 Q$(e,t){return t?e.filter(n=>n.archived!==!0):e}function X$(e,t){let n=!1;const r=e.map(o=>{const s=t[o.session_id];return s===void 0||!s.answered||o.archived===s.archived?o:(n=!0,{...o,archived:s.archived})});return n?r:e}function q$(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function eN(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const tN="This backend cannot archive conversations. Update the backend and try again.",nN="This conversation is already archived. Use /unarchive to restore it.",rN="This conversation is not archived, so there is nothing to restore.",oN="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 sN(e,t,n){return n&&e&&t.trim().length>0}function iN(e,t){return t===e}const ae=e=>{const[t,n,r]=[1,3,5].map(f=>{const h=Number.parseInt(e.slice(f,f+2),16)/255;return h<=.04045?h/12.92:((h+.055)/1.055)**2.4}),o=(t*.4124564+n*.3575761+r*.1804375)/.95047,s=t*.2126729+n*.7151522+r*.072175,a=(t*.0193339+n*.119192+r*.9503041)/1.08883,c=f=>f>216/24389?Math.cbrt(f):841/108*f+4/29,[l,d,u]=[c(o),c(s),c(a)];return[116*d-16,500*(l-d),200*(d-u)]},ue=(e,t)=>{const[n,r,o]=ae(e),[s,a,c]=ae(t),l=Math.PI/180,d=180/Math.PI,u=(Math.hypot(r,o)+Math.hypot(a,c))/2,f=.5*(1-Math.sqrt(u**7/(u**7+25**7))),[h,m]=[(1+f)*r,(1+f)*a],[y,b]=[Math.hypot(h,o),Math.hypot(m,c)],v=(T,V)=>{if(T===0&&V===0)return 0;const Z=Math.atan2(T,V)*d;return Z<0?Z+360:Z},[p,A]=[v(o,h),v(c,m)],k=s-n,C=b-y;let L=0;y*b!==0&&(L=A-p,L>180?L-=360:L<-180&&(L+=360));const O=2*Math.sqrt(y*b)*Math.sin(L*l/2),I=(n+s)/2,g=(y+b)/2;let w;y*b===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),x=1+.015*(I-50)**2/Math.sqrt(20+(I-50)**2),F=1+.045*g,j=1+.015*g*S,X=-Math.sin(2*30*Math.exp(-(((w-275)/25)**2))*l)*2*Math.sqrt(g**7/(g**7+25**7));return Math.sqrt((k/x)**2+(C/F)**2+(O/j)**2+X*(C/F)*(O/j))},ii=([e,t,n])=>{const r=(e+16)/116,o=r+t/500,s=r-n/200,a=m=>m>6/29?m**3:3*(6/29)**2*(m-4/29),c=a(o)*.95047,l=a(r),d=a(s)*1.08883,f=[c*3.2404542+l*-1.5371385+d*-.4985314,c*-.969266+l*1.8760108+d*.041556,c*.0556434+l*-.2040259+d*1.0572252].map(m=>m<=.0031308?12.92*m:1.055*m**(1/2.4)-.055);if(f.some(m=>m<-.0015||m>1.0015))return null;const h=m=>Math.round(Math.min(1,Math.max(0,m))*255).toString(16).padStart(2,"0").toUpperCase();return`#${f.map(h).join("")}`},D=e=>Math.round(e*100)/100,hf=e=>{const t=e.replace("#","").trim(),n=t.length===3?t.split("").map(a=>a+a).join(""):t,[r,o,s]=[0,2,4].map(a=>{const c=Number.parseInt(n.slice(a,a+2),16)/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4});return .2126*r+.7152*o+.0722*s},oe=(e,t)=>{const[n,r]=[hf(e),hf(t)].sort((o,s)=>s-o);return(n+.05)/(r+.05)},Tx=/^#[0-9a-fA-F]{3,8}$/,W=e=>typeof e=="string"&&Tx.test(e),va=(e,t,n)=>{const r=f=>{const h=f.replace("#","").trim(),m=h.length===3?h.split("").map(y=>y+y).join(""):h;return[0,2,4].map(y=>Number.parseInt(m.slice(y,y+2),16))},[o,s,a]=r(e),[c,l,d]=r(t),u=(f,h)=>Math.round(f*n+h*(1-n));return`#${[u(o,c),u(s,l),u(a,d)].map(f=>f.toString(16).padStart(2,"0")).join("")}`},bn={"under-window":{dark:81,light:199},menu:{dark:102,light:171},popover:{dark:122,light:143}},Sl=["canvas","surface","elevated"],Ai=["ink","inkMuted","inkDim"],ts=4.5,Cx=3,Ox=1.5,tg=["danger","success","warning","info"],ng={hover:.05,selected:.08,field:.05,work:.08},rg=4,Px=1.5,El=.96,Mx=["sunken","surface"],og=3.5,mc=e=>{const t=e.replace("#",""),n=t.length===3?t.split("").map(a=>a+a).join(""):t.slice(0,6),[r,o,s]=[0,2,4].map(a=>{const c=Number.parseInt(n.slice(a,a+2),16)/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4});return .2126*r+.7152*o+.0722*s},Hr=(e,t)=>{const[n,r]=[mc(e),mc(t)].sort((o,s)=>s-o);return(n+.05)/(r+.05)},mf=(e,t)=>Number.parseInt(e.slice(1+t*2,3+t*2),16),Fn=e=>`#${e.toString(16).padStart(2,"0").repeat(3)}`,it=(e,t,n)=>`#${[0,1,2].map(r=>Math.round(mf(e,r)*t+mf(n,r)*(1-t)).toString(16).padStart(2,"0")).join("")}`,Pt=e=>mc(e.canvas)<.18?"dark":"light",sg=(e,t,n,r,o=ts)=>{for(let s=.2;s<=1.0001;s+=.01)if(Hr(e[n],it(e[t],s,r))>=o)return Math.round(s*100)/100;return 1},Al=(e,t,n,r,o)=>{for(let s=.2;s<=1.0001;s+=.01){const a=it(e[t],s,r);if(Hr(e[n],it(e.ink,o,a))>=(n==="inkDim"?og:ts))return Math.round(s*100)/100}return 1},jx=(e,t)=>it(e.ink,t,e.borderControl);function $x(e,t){const n={};for(const r of["dark","light"]){let o=0;for(const s of Object.keys(bn))for(const{palette:a}of t){if(Pt(a)!==r)continue;const c=it(a.canvas,e[s][r].canvas,Fn(bn[s][r]));let l=.01;for(;l<1&&ue(it(a.ink,l,c),c)<rg;)l=Math.round((l+.01)*100)/100;o=Math.max(o,l)}n[r]=Math.round(o*100)/100}return n}function Nx(e,t=ng){const n={};for(const[r,o]of Object.entries(bn)){n[r]={};for(const s of["dark","light"]){n[r][s]={};for(const a of Sl){let c=0;for(const{palette:l}of e)if(Pt(l)===s)for(const d of Ai)c=Math.max(c,sg(l,a,d,Fn(o[s])),...Object.values(t).map(u=>Al(l,a,d,Fn(o[s]),u)));n[r][s][a]=Math.min(1,Math.round((c+.02)*100)/100)}}}return n}function Dx(e){const t={};for(const n of["dark","light"]){let r=0;for(const{palette:o}of e){if(Pt(o)!==n)continue;const s=n==="dark"?"#ffffff":"#000000";for(const a of Ai)r=Math.max(r,sg(o,"elevated",a,s,a==="inkDim"?og:ts))}t[n]=Math.round(r*100)/100}return t}function ig(e,t){let n=1;for(const r of Object.keys(e))n=Math.min(n,e[r][t]?.canvas??1);return n}function ag(e,t,n,r){const o=r==="dark"?"#ffffff":"#000000";return it(e.elevated,t,it(e.canvas,ig(n,r),o))}function Lx(e,t){const n={};for(const r of["dark","light"]){const o=ig(t,r),s=r==="dark"?"#ffffff":"#000000";let a=0;for(const{palette:c}of e){if(Pt(c)!==r)continue;const l=it(c.canvas,o,s);for(const d of["inkMuted","ink"]){let u=.2;for(;u<=1.0001&&!(Hr(c[d],it(c.elevated,u,l))>=ts);u+=.01);a=Math.max(a,Math.round(Math.min(u,1)*100)/100)}}n[r]=Math.round(a*100)/100}return n}function Fx(e,t,n){const r={};for(const o of["dark","light"]){let s=0;for(const{palette:a}of e){if(Pt(a)!==o)continue;const c=ag(a,n[o],t,o);for(const l of tg){let d=0;for(;d<=1.0001&&!(Hr(it(a.ink,d,a[l]),c)>=ts);d+=.05);s=Math.max(s,Math.round(Math.min(d,1)*100)/100)}}r[o]=Math.round(s*100)/100}return r}function Ux(e,t,n){const r={};for(const o of["dark","light"]){const s=n[o],a=Math.max(El,s),c=[Math.round((a-.8*(a-s))*100)/100,s];let l=0;for(const{palette:d}of e)if(Pt(d)===o)for(const u of c){const f=ag(d,u,t,o);let h=0;for(;h<=1.0001&&!(Hr(it(d.ink,h,d.hairline),f)>=Ox);h+=.05);l=Math.max(l,Math.round(Math.min(h,1)*100)/100)}r[o]=Math.round(l*100)/100}return r}function Bx(e,t){const n={};for(const[r,o]of Object.entries(bn)){n[r]={};for(const s of["dark","light"]){let a=0;for(const{palette:c}of t)if(Pt(c)===s)for(const l of Sl){const d=it(c[l],e[r][s][l],Fn(o[s]));let u=0;for(;u<1&&Hr(jx(c,u),d)<Cx;)u=Math.round((u+.05)*100)/100;a=Math.max(a,u)}n[r][s]=Math.min(1,Math.round((a+.05)*100)/100)}}return n}const to=new Map;function Hx(e){const t=Pt(e),n=r=>Object.values(bn).every(o=>Sl.every(s=>Ai.every(a=>Al(e,s,a,Fn(o[t]),r)<=.95)));return Object.fromEntries(Object.entries(ng).map(([r,o])=>{let s=o;for(;s>.01&&!n(s);)s=Math.round((s-.01)*100)/100;return[r,s]}))}function Wx(e,t){const n=Pt(e);let r=$x(t,[{palette:e}])[n];const o=()=>Object.entries(bn).every(([s,a])=>Array.from({length:101},(c,l)=>{const d=t[s][n].canvas,u=Math.max(El,d),f=Math.round((u-l/100*(u-d))*100)/100,h=it(e.canvas,f,Fn(a[n]));return ue(it(e.ink,r,h),h)>=rg}).every(Boolean));for(;r<1&&!o();)r=Math.round((r+.01)*100)/100;return{dark:0,light:0,[n]:r}}function Gx(e,t){const n=Pt(e);for(const r of Mx)for(let o=5;o<=104;o++){const s=o/100;if(Object.entries(bn).every(([c,l])=>Array.from({length:101},(d,u)=>{const f=t[c][n].canvas,h=Math.max(El,f),m=Math.round((h-u/100*(h-f))*100)/100,y=Math.round(m*s*100)/100;if(y>1)return!1;const b=it(e.canvas,m,Fn(l[n]));return ue(it(e[r],y,b),b)>=Px}).every(Boolean)))return{dark:{role:r,scale:s},light:{role:r,scale:s}}}return null}function zx(e,t){const n=Pt(e);for(;;){const r=Wx(e,t);let o=!1;for(const[s,a]of Object.entries(bn)){const c=Math.min(1,Math.round((Math.max(...Ai.map(l=>Al(e,"canvas",l,Fn(a[n]),r[n])))+.02)*100)/100);c>t[s][n].canvas&&(t[s][n].canvas=c,o=!0)}if(!o)return r}}const Kx=["canvas","surface","elevated","sunken","ink","inkMuted","inkDim","borderControl","hairline",...tg];function Vx(e){for(const t of Kx){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 aN(e){Vx(e);const t=JSON.stringify(e),n=to.get(t);if(n)return n;const r=[{palette:e}],o=Hx(e),s=Nx(r,o);let a,c;for(let u=0;u<=99;u++){let f=!1;for(const h of Object.keys(bn)){const m=Pt(e),y=s[h][m].canvas,b=Math.max(y,u/100);f||=b!==y,s[h][m].canvas=b}if(!(u>0&&!f)&&(a=zx(e,s),c=Gx(e,s),c))break}if(!c)throw new Error("palette roles cannot form a readable transparent lane");const l=Lx(r,s),d={alphaFloor:s,blockVeil:a,laneWash:c,controlMix:Bx(s,r),bandFloor:Dx(r),overlayFloor:l,overlayInkMix:Fx(r,s,l),overlayEdgeMix:Ux(r,s,l),stateAlpha:o};return to.set(t,d),to.size>8&&to.delete(to.keys().next().value),d}const gc=new WeakMap,Zx=(e,t)=>{t?gc.set(e,t):gc.delete(e)},cN=e=>gc.get(e);/**
44
+ ${e}`}const ma={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function js(e,t,n){const r=[...e.attachments??[]],o=[],s=[],a=new Set;for(const h of t.attachments){const m=r.find(b=>b.path===h&&!a.has(b.id));if(m){a.add(m.id),s.push(m.id);continue}const y={id:n(),path:h};o.push(y),s.push(y.id)}const c=[...e.replies??[]],l=t.replies.filter(h=>!c.some(m=>m.id===h.id)),d=t.text,u=[...o,...r],f=[...l,...c];return{...e,attachments:u,replies:f,textRevision:(e.textRevision??0)+1,volatilePendingText:e.volatilePendingText===!0||t.volatileText===!0,pendingText:d===""?e.pendingText:Si(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:s,replyIds:t.replies.map(h=>f.find(m=>m.id===h.id)?.id).filter(h=>h!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function uR(e,t){const n=e.lateDeliveredText??e.returned?.text;if(!n||t.includes(n))return!0;const r=Math.max(8,Math.min(24,Math.floor(n.length/3)));for(let o=0;o+r<=n.length;o++)if(t.includes(n.slice(o,o+r)))return!0;return!1}function fR(e){return{text:Si(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function pR(e,t){if(!e||!t)return!1;const n=fR(e),r=e.attachments??[],o=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((s,a)=>s.id===t.chipIds[a])&&o.length===t.replyIds.length&&o.every((s,a)=>s.id===t.replyIds[a])}function hR(e,t=()=>crypto.randomUUID()){const n={};for(const[r,o]of Object.entries(e??{}))n[r]=o.inFlight?js(o,o.inFlight,t):o;return n}function mR(e,t){const n=t.text,r=Si(e.currentInput??"",e.pendingText??"");let o=r,s="overlap";n===""?s="draft-only":r.startsWith(n)&&(o=r.slice(n.length).replace(/^\n+/,""),s="draft-only");const a=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:o,pendingText:void 0,attachments:(e.attachments??[]).filter(l=>!a.has(l.id)),replies:(e.replies??[]).filter(l=>!c.has(l.id)),unredactedChars:n===""?e.unredactedChars??0:0},box:s}}const gR=300,Om="conversation-input-store";let Ho=null,Pm=Om,kt=null,ga=!1;const lc=()=>{try{return globalThis.localStorage??null}catch{return null}},yo=()=>{kt!==null&&(clearTimeout(kt),kt=null);const e=Ho;if(!e)return;const t=Pm,n=lc();if(n){try{n.setItem(t,JSON.stringify(e))}catch(r){ga||(ga=!0,console.warn("[composer] the draft could not be persisted; it stays in memory for this session",r));return}Ho=null,ga=!1}},n$=()=>{yo()},r$=()=>{Ho=null,kt!==null&&(clearTimeout(kt),kt=null)},_R={getItem:e=>{const t=lc();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)=>{Ho=t,Pm=e,kt!==null&&clearTimeout(kt),kt=setTimeout(()=>{kt=null,yo()},gR)},removeItem:e=>{Ho=null,kt!==null&&(clearTimeout(kt),kt=null),lc()?.removeItem(e)}};typeof window<"u"&&typeof window.addEventListener=="function"&&(window.addEventListener("pagehide",yo),window.addEventListener("beforeunload",yo),window.document?.addEventListener("visibilitychange",()=>{window.document.visibilityState==="hidden"&&yo()}));const ct=Qo()(_i((e,t)=>({inputByConversation:{},addReply:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=Array.isArray(o.replies)?o.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...o,replies:[...s,r]}}})},removeReply:(n,r)=>{const o=t().inputByConversation[n];o&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,replies:o.replies.filter(s=>s.id!==r)}}})},clearReplies:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:[]}}})},addAttachment:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=Array.isArray(o.attachments)?o.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...o,attachments:[...s,r]}}})},removeAttachment:(n,r)=>{const o=t().inputByConversation[n];o&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,attachments:o.attachments.filter(s=>s.id!==r)}}})},clearAttachments:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[]}}})},setCurrentInput:(n,r,o=0)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...s,lateDelivered:s.lateDelivered==="overlap"&&!uR(s,r)?void 0:s.lateDelivered,currentInput:r,unredactedChars:r?o:0}}})},getUnredactedChars:n=>t().inputByConversation[n]?.unredactedChars||0,getCurrentInput:n=>t().inputByConversation[n]?.currentInput||"",addSubmittedMessage:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=o.submittedMessages[o.submittedMessages.length-1],a=r&&r!==s?[...o.submittedMessages.slice(-19),r]:o.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...o,submittedMessages:a}}})},getSubmittedMessages:n=>t().inputByConversation[n]?.submittedMessages||[],clearSubmittedMessages:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,submittedMessages:[]}}})},getCurrentHistoryIndex:n=>t().inputByConversation[n]?.currentHistoryIndex??null,setCurrentHistoryIndex:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=o.submittedMessages;let a=null;typeof r=="number"&&s.length>0&&(a=Math.max(0,Math.min(r,s.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...o,currentHistoryIndex:a}}})},resetCurrentHistoryIndex:n=>{const r=t().inputByConversation[n];r&&(r.currentHistoryIndex??null)!==null&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentHistoryIndex:null}}})},clearAll:n=>{const{[n]:r,...o}=t().inputByConversation;e({inputByConversation:o})},restoreRow:(n,r)=>{e({inputByConversation:{...t().inputByConversation,[n]:{...r,textRevision:(r.textRevision??0)+1}}})},beginInFlight:(n,r,o=!0)=>{const s=t().inputByConversation[n]??ma,a=new Set(r.attachments.map(d=>d.id)),c=new Set(r.replies.map(d=>d.id)),l=s.currentInput===r.text;e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:l?"":s.currentInput,unredactedChars:l?0:s.unredactedChars,textRevision:l?(s.textRevision??0)+1:s.textRevision,attachments:(s.attachments??[]).filter(d=>!a.has(d.id)),replies:(s.replies??[]).filter(d=>!c.has(d.id)),inFlight:o?{text:r.text,attachments:r.attachments.map(d=>d.path),replies:[...r.replies],unredactedChars:l?s.unredactedChars:0,volatileText:r.volatileText}:s.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const r={...t().inputByConversation};let o=!1;for(const s of n){const a=r[s];!a||!a.inFlight&&!a.returned||(r[s]={...a,inFlight:void 0,returned:void 0},o=!0)}o&&e({inputByConversation:r})},returnInFlight:(n,r)=>{const o={...t().inputByConversation},s=o[n],a=s?.inFlight??o[r]?.inFlight;let c=o[r]??ma;n!==r&&s&&(c=js(c,{text:s.currentInput??"",attachments:(s.attachments??[]).map(l=>l.path),replies:s.replies??[],unredactedChars:s.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:o[r]?.returned},delete o[n]),a&&(c=js(c,a,()=>crypto.randomUUID())),!(!a&&n===r)&&(o[r]=c,e({inputByConversation:o}))},adoptReturnedText:n=>{const r=t().inputByConversation[n];if(r?.pendingText===void 0)return null;const o=Si(r.currentInput??"",r.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:o,pendingText:void 0,textRevision:(r.textRevision??0)+1}}}),o},returnPayload:(n,r)=>{const o=t().inputByConversation[n]??ma;o.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:js(o,r,()=>crypto.randomUUID())}})},reconcileDelivered:n=>{const r=t().inputByConversation[n];if(!r)return;const o=f=>(f.currentInput??"")===""&&(f.attachments??[]).length===0&&(f.replies??[]).length===0,s=r.returned!==void 0||r.inFlight!==void 0,a=r.returned?pR(r,r.returned):o(r),c=r.returned?mR(r,r.returned):null,l={...r,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,volatilePendingText:void 0,textRevision:(r.textRevision??0)+1},d=(c?.row.currentInput??"")==="",u=c&&!o(c.row)?{...c.row,returned:void 0,inFlight:void 0,volatilePendingText:d?void 0:r.volatilePendingText,lateDelivered:c.box==="overlap"&&d?"draft-only":c.box,lateDeliveredText:c.box==="overlap"&&!d?r.returned?.text:void 0,textRevision:(r.textRevision??0)+1}:{...r,returned:void 0,inFlight:void 0,lateDelivered:s&&r.returned?.text?"overlap":s?"delivered":void 0,lateDeliveredText:s?r.returned?.text:void 0};e({inputByConversation:{...t().inputByConversation,[n]:a||c!==null&&o(c.row)?l:u}})},dismissLateDelivery:n=>{const r=t().inputByConversation[n];r?.lateDelivered&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,lateDelivered:void 0,lateDeliveredText:void 0}}})},clearComposer:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,volatilePendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,textRevision:(r.textRevision??0)+1}}})},setComposerText:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...o,currentInput:r,unredactedChars:o.unredactedChars??0,textRevision:(o.textRevision??0)+1}}})}}),{name:Om,storage:_R,partialize:e=>({inputByConversation:Object.fromEntries(Object.entries(e.inputByConversation).map(([t,n])=>{let r=n;return r.inFlight?.volatileText&&(r={...r,inFlight:{...r.inFlight,text:""}}),r.returned?.volatileText&&(r={...r,returned:{...r.returned,text:""}}),r.volatilePendingText&&(r={...r,pendingText:void 0}),r.volatilePendingText&&(r={...r,lateDeliveredText:void 0}),[t,r]}))}),merge:(e,t)=>({...t,inputByConversation:hR(e?.inputByConversation)})}));function Mm(e){if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null}function o$(e,t){return t?e.filter(n=>n.session_id===t&&jm(n)).length:0}function jm(e){if(Mm(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function bR(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function s$(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 i$={cwd:""};function vR(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,bR(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function yR(e){return(await Je({op:"sessions.preview",requestId:crypto.randomUUID(),cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}})).frontend}function a$(e,t){const n=e.trim();if(!n)return{checked:!0,rung:null,confirmation:o=>_("ui.chat.session_readout.draft.confirm_model",{selector:o})};if(!t.ladderKnown)return{checked:!1,rung:null,refusal:_("ui.chat.session_readout.draft.refusal_ladder_unread")};const r=t.ladder.find(o=>o.trim().toLowerCase()===n.toLowerCase());return r?{checked:!0,rung:r,confirmation:o=>_("ui.chat.session_readout.draft.confirm_model_effort",{selector:o,effort:vs(r)})}:{checked:!0,rung:null,confirmation:o=>t.level?_("ui.chat.session_readout.draft.confirm_effort_changed",{selector:o,level:vs(t.level),wanted:vs(n)}):_("ui.chat.session_readout.draft.confirm_effort_unset",{selector:o,wanted:vs(n)})}}function c$(e,t){return e!==!0?null:t==="on"?_("ui.chat.fast_mode.stays_on"):t==="off"?_("ui.chat.fast_mode.turned_off"):_("ui.chat.fast_mode.unsupported_stays_off")}const l$=()=>_("ui.chat.fast_mode.service_cannot_carry"),d$="fast_unavailable";function yl(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function u$(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function f$(e){const t=e instanceof Te?e:null;return t?.code==="fast_mode_unsupported"?_("ui.chat.fast_mode.pick_unsupported"):t?.status===422?_("ui.chat.fast_mode.service_unavailable"):_("ui.chat.fast_mode.not_changed")}function p$(e,t){const n={...e,model:yl(e.model,t)};return{queryKey:vR(n),queryFn:()=>yR(n),placeholderData:y_,staleTime:3e4,retry:!1}}function ae(e){return typeof e=="string"?e.trim():""}function yr(e){const t=ae(e);return t||null}function Ln(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function po(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function $m(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function nr(e,t){return typeof e=="boolean"?e:t}function dc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Br(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 Br(t)}return[]}function wR(e){if(!On(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:$m(e.attempts),last_frame_at:Ln(e.last_frame_at),next_retry_at:Ln(e.next_retry_at),last_error:ae(e.last_error)}}function On(e){return typeof e=="object"&&e!==null}const kR=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function SR(e,t){const n=ae(e);return kR.includes(n)?n:t?"reachable":"unreachable_legacy"}const ER=["running","not_listening","unknown"];function AR(e){const t=ae(e);return ER.includes(t)?t:void 0}function IR(e){if(Array.isArray(e))return e.filter(On).map(t=>({endpoint:ae(t.endpoint),connected:t.connected===!0,detail:ae(t.detail),latency_ms:Ln(t.latency_ms)})).filter(t=>t.endpoint!=="")}function h$(e){const t=new Set,n=[];for(const a of Br(e)){const c=ae(a.device_id);if(!c||t.has(c)||typeof a.reachable!="boolean")continue;t.add(c);const l=AR(a.remote_relay),d=IR(a.attempts),u=a.reachable?void 0:wR(a.redial);n.push({device_id:c,name:ae(a.name),reachable:a.reachable,link_state:SR(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:yr(a.unreachable_reason??a.reason),last_seen_at:Ln(a.last_seen_at),session_count:po(a.session_count),rtt_ms:Ln(a.rtt_ms)})}const r=On(e)?e:{},o=ae(r.self_device_id),s=dc(r.degraded);return{peers:n,...o?{self_device_id:o}:{},...s.length?{degraded:s}:{}}}function RR(e){const t=ae(e.device_id);return t?{device_id:t,name:ae(e.name),role:ae(e.role),capabilities:dc(e.capabilities),active:nr(e.active,!0),suspect:nr(e.suspect,!1),endpoints:dc(e.endpoints),last_seen_at:Ln(e.last_seen_at),reachable:nr(e.reachable,!0),reason:ae(e.reason??e.unreachable_reason),scope:ae(e.scope)}:null}function xR(e){const t=ae(e.network_id);return t?{network_id:t,name:ae(e.name),epoch:$m(e.epoch),trust:ae(e.trust),members:Br(e.members).map(RR).filter(n=>n!==null)}:null}function m$(e){const t=On(e)?e:{},n=ae(t.self_device_id);return{networks:Br(t.networks).map(xR).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function TR(e){return e.live_state.trim().toLowerCase()==="busy"}function g$(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const o of Br(r)){const s=ae(o.id);if(!s||n.has(s))continue;const a=o.locality==="remote"?"remote":ae(o.locality)==="local"?"local":null;if(!a)continue;n.add(s);const c=On(o.status)?{code:ae(o.status.code),label:ae(o.status.label)}:null,l=On(o.binding)?{agent:yr(o.binding.agent),team:yr(o.binding.team)}:null,d=On(o.opened_by)?{agent:yr(o.opened_by.agent),label:yr(o.opened_by.label),session:yr(o.opened_by.session)}:null;t.push({id:s,name:ae(o.name),mtime:Ln(o.mtime)??0,locality:a,owner_device:ae(o.owner_device),owner_device_name:ae(o.owner_device_name),reachable:nr(o.reachable,!0),unreachable_reason:ae(o.unreachable_reason),live_state:ae(o.live_state),archived:nr(o.archived,!1),created_at:Ln(o.created_at),pinned:nr(o.pinned,!1),...typeof o.active=="boolean"?{active:o.active}:{},waiting_on:po(o.waiting_on),jobs_running:po(o.jobs_running),subagents_running:po(o.subagents_running),subagents_queued:po(o.subagents_queued),...typeof o.background_work=="boolean"?{background_work:o.background_work}:{},...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function _$(e){const{id:t,name:n,mtime:r,...o}=e;return{...o,session_id:t,title:n,updated_at:r}}function b$(e){if(!On(e))return null;const t=ae(e.session_id);if(!t)return null;const n=e.mode==="keep"?"keep":"move",r=ae(e.new_session_id)||(n==="move"?t:"");return r?{locality:e.locality==="local"?"local":"remote",owner_device:ae(e.owner_device),source_retired:nr(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:Br(e.phases).map(o=>({phase:ae(o.phase),peer:ae(o.peer),progress:typeof o.progress=="number"?o.progress:0}))}:null}const CR=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function v$(e){const t=e,n=ae(t?.code)||"move_refused",r=typeof t?.status=="number"?t.status:null;return{code:n,sentence:ae(t?.message)||_("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||CR.has(n)}}function y$(e){const t=ae(e.name);return t||_("ui.mesh.mesh_types.device_suffix",{suffix:ae(e.device_id).slice(-6)})}function OR(e){const t=ae(e.name);return t?JSON.stringify(t):_("ui.mesh.mesh_types.unnamed_device")}function PR(e,t){const n=ae(e);if(!t)return n;const r=t.map(ae).filter(s=>s.length>0&&s!==n);let o=Math.min(10,n.length);for(;o<n.length&&r.some(s=>s.startsWith(n.slice(0,o)));)o+=1;return o<n.length?`${n.slice(0,o)}…`:n}function w$(e,t,n=!1){const r=n?PR(e.id,t):ae(e.id);return`${OR(e)} ${r}`}function k$(e){const t=ae(e.name);return t||_("ui.mesh.mesh_types.network_suffix",{suffix:ae(e.network_id).slice(-6)})}const MR=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function jR(e){const t=e.trim();return t!==""&&MR.includes(t)}function Nm(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"||jR(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const S$=()=>_("ui.mesh.mesh_graph.identity_suspect");function Dm(e){switch(e){case"self":return _("ui.mesh.mesh_drop.this_device");case"reached":return _("ui.mesh.mesh_reach.reached");case"relay-down":return _("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return _("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return _("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return _("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return _("ui.mesh.mesh_reach.not_a_member");case"unanswered":return _("ui.mesh.mesh_reach.no_answer");case"not-attempted":return _("ui.mesh.mesh_reach.not_asked");default:return _("ui.mesh.mesh_reach.unknown")}}function E$(e){const t=Nm(e),n=Dm(t);return e.reason?`${n} — ${e.reason}`:n}const A$={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"},I$={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function R$(e){const t=e.trim();switch(t){case"ok":return _("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return _("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return _("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return _("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return _("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?_("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function x$(e){return e.reachable?"":e.remoteRelay==="not_listening"?_("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?_("ui.mesh.mesh_reach.peer_closed_handshake"):""}function T$(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>TR(r))?"working":"idle",source:"derived"}}function $R(e,t){const n={...e};for(const[r,o]of Object.entries(t))(!n[r]||o.at>=n[r].at)&&(n[r]=o);return n}function NR(e,t){if(e.locality!=="remote"||typeof e.owner_device!="string")return e;const n=t[e.owner_device];if(!n)return e.peer_reach||e.link_down?{...e,peer_reach:"unknown",link_down:!1,link_reconnecting:!1,reachable:!1,link_down_reason:null,last_seen_at:null}:e;const r=Nm({state:"unreachable",reachable:n.reachable,reason:n.reason??"",sessionCount:n.session_count??null}),o=r==="unanswered",s=o&&n.redial_state==="reconnecting";return e.peer_reach===r&&e.link_down===o&&(e.link_reconnecting??!1)===s&&e.reachable===n.reachable&&e.last_seen_at===n.last_seen_at&&e.link_down_reason===n.reason?e:{...e,reachable:n.reachable,link_down:o,link_reconnecting:s,peer_reach:r,last_seen_at:n.last_seen_at,link_down_reason:n.reason}}function C$(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${_("ui.chat.canonical.transcript.reconnecting")} · ${uc(n,t)}`:_("ui.presence.link_down_last_seen",{age:uc(n,t)})}function uc(e,t){if(e===null)return _("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?_("ui.presence.just_now"):n<3600?_("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?_("ui.presence.hours_ago",{count:Math.floor(n/3600)}):_("ui.presence.days_ago",{count:Math.floor(n/86400)})}function O$(e,t){if(e.link_reconnecting===!0)return _("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return _("ui.presence.link_down_compact",{age:uc(n,t)})}function DR(e,t,n,r){if(r<=n)return{facts:e,watermark:n,removed:[]};const o=Object.fromEntries(Object.entries(e).filter(([,s])=>s.at>r));for(const[s,a]of Object.entries(t))(!o[s]||a.at>=o[s].at)&&(o[s]=a);return{facts:o,watermark:r,removed:Object.keys(e).filter(s=>!o[s])}}function P$(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?Dm(e.peer_reach):null}const LR=Object.freeze({}),wl=["model","effort","fast","cwd"],FR=new Set(["pending","applying","queued_next_step","waiting_idle"]);function Lm(e){return!!(e&&FR.has(e.state))}function UR(e,t){return t?e.request_id===t.request_id?t.local?!0:e.generation>t.generation||e.generation===t.generation&&!af(e,t):e.generation!==t.generation?e.generation>t.generation:t.local?!1:!af(e,t):!0}function af(e,t){return!e.updated_at||!t.updated_at?!1:Date.parse(e.updated_at)<Date.parse(t.updated_at)}let Fm=0;const Um=new WeakMap;function BR(e){return Um.set(e,++Fm),e}function M$(){return Fm}function HR(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Wo(e,t,n){const r={...e};return Object.keys(n).length===0?delete r[t]:r[t]=n,r}function fc(e,t,n,r){const o=e[t]??{},s=o[n];if(r===null){if(!s||s.local)return e;const{[n]:a,...c}=o;return Wo(e,t,c)}return r.kind!==n||!UR(r,s)||s&&!s.local&&HR(r,s)?e:Wo(e,t,{...o,[n]:BR(r)})}function Bm(e,t,n,r){let o=e;for(const s of wl){const a=n[s];if(a){o=fc(o,t,s,a);continue}if(r===void 0)continue;const c=o[t]?.[s];c&&(Um.get(c)??0)>r||(o=fc(o,t,s,null))}return o}function WR(e,t,n,r=Number.POSITIVE_INFINITY){const o=n?[n]:[...new Set([...Object.keys(e),...Object.keys(t)])];let s=e;for(const a of o)s=Bm(s,a,t[a]??{},r);return s}function GR(e,t,n,r=Date.now()){const o=e[t]??{},s=o[n.kind],a=new Date(r).toISOString(),c={kind:n.kind,value:n.value,effort:n.effort??null,request_id:n.requestId,generation:(s?.generation??0)+1,base:s?.base??null,state:"pending",attempts:0,created_at:a,updated_at:a,error:null,local:!0};return Wo(e,t,{...o,[n.kind]:c})}function zR(e,t,n,r,o,s=Date.now()){const a=e[t],c=a?.[n];return!a||!c||c.request_id!==r?e:Wo(e,t,{...a,[n]:{...c,state:"failed",error:o,updated_at:new Date(s).toISOString()}})}function KR(e,t,n,r){const o=e[t],s=o?.[n];if(!o||!s||s.generation!==r)return e;const{[n]:a,...c}=o;return Wo(e,t,c)}function j$(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"),r=t("effort"),o=t("fast"),s=t("cwd");return{model:typeof n?.value=="string"?n.value:null,effort:typeof r?.value=="string"?r.value:typeof n?.effort=="string"&&n.effort?n.effort:null,fast:typeof o?.value=="boolean"?o.value:null,cwd:typeof s?.value=="string"?s.value:null}}function $$(e){if(!e)return null;let t=null;for(const n of wl){const r=e[n];if(r?.state==="failed")return r;!t&&r&&Lm(r)&&(t=r)}return t}function N$(e){if(!e)return[];const t=[];for(const n of wl){const r=e[n];r&&(Lm(r)||r.state==="failed")&&t.push(r)}return t}function D$(e){const t=e.status??null;return{code:e.code??(t===null?"runtime_unreachable":"refused"),message:e.message??"",retryable:t===null||t>=500}}function L$(e,t){if(e===t)return[];const n=[];for(const[r,o]of Object.entries(t)){const s=o.cwd;if(s?.state!=="applied"||typeof s.value!="string")continue;const a=e[r]?.cwd;a?.state==="applied"&&a.request_id===s.request_id||n.push(s.value)}return n}function F$(e){return e.local?e.state==="failed"&&e.error?.retryable===!0:!0}const cf=new Set;function U$(e){return cf.has(e)?!1:(cf.add(e),!0)}function B$(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?_("ui.chat.canonical.untitled"):n==="this chat"?_("ui.chat.canonical.this_chat"):n:t==="this_chat"?_("ui.chat.canonical.this_chat"):_("ui.chat.canonical.untitled")}function pc(e,t){return e.map((n,r)=>({id:`${t}:doc:${r}`,attachment:n.digest,filename:n.name??"Attached file",mimeType:n.mime_type??"application/octet-stream",path:n.path??null,storedPath:null,bytes:n.bytes??0}))}const ks=(e,t)=>e instanceof Te?Vc(e,t):e instanceof Error?e.message:t,Ei="session_unvalidated",VR=()=>_("ui.common.errors.session_unvalidated"),si="leading_slash_message",Hm=()=>_("ui.common.errors.leading_slash_message");function ZR(e,t){return e instanceof Te&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const Wm="attachment_read_failed",Gm="store_out_of_space",zm="store_unavailable";function lf(e){return e===Gm||e===zm}const YR="answer_not_sent",Km="aside_not_answered",Vm="aside_still_answering";function ho(e){return e===si||e===Wm||e===Gm||e===zm||e===YR||e===Km||e===Vm||e===Ei||e===mi}function JR(e){return e instanceof Te&&e.status===409&&kl(e)===void 0}function Zm(e,t=!1){return qR(e)||JR(e)&&!t?"not_sent":e instanceof Te&&e.status===404?"gone":"unknown"}function kl(e){if(e instanceof Te||e instanceof mn)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const gt={get unconfirmed(){return _("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return _("ui.chat.canonical.send_failure.unreachable")},get busy(){return _("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return _("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return _("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return _("ui.chat.canonical.send_failure.retiring")},get notReady(){return _("ui.chat.canonical.send_failure.not_ready")},get generic(){return _("ui.chat.canonical.send_failure.generic")},get gone(){return _("ui.chat.canonical.send_failure.gone")},get sendLock(){return _("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return _("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return _("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return _("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return _("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return _("ui.chat.canonical.send_failure.late_delivery_overlap")}};function H$(e){return e?gt.gateLock:gt.sendLock}const W$=()=>_("ui.common.actions.retry"),G$=()=>_("ui.common.actions.clear");function QR(e,t,n=!1){const r=Zm(e,n),o=t??kl(e),s=Vc(e,gt.generic);return r==="gone"?{message:gt.gone,retry:!1,code:o}:r==="not_sent"?o===mi?{message:gt.busy,retry:!0,code:o}:o===Pp?{message:gt.retiring,retry:!0,code:o}:o===Ue.serverUpdating?{message:Xn(o),retry:!0,code:o}:o===Ei?{message:gt.notReady,retry:!ho(o),code:o}:o===Km?{message:gt.asideNotAnswered,retry:!1,code:o}:o===Vm?{message:gt.asideStillAnswering,retry:!1,code:o}:o===si?{message:Hm(),retry:!1,code:o}:{message:s,retry:!1,code:o}:Kc(e)?{message:Xn(Ue.serverUpdating),retry:o===Ue.transportFailed,code:o}:o===Ue.transportFailed?{message:gt.unreachable,retry:!0,code:o}:gi(o)?{message:Xn(o),retry:!1,code:o}:o===Gc?{message:gt.unconfirmed,retry:!ho(o),code:o}:o===vy.runtimeUnreachable?{message:gt.unconfirmed,retry:!0,code:o}:o?{message:s,retry:!ho(o),code:o}:{message:gt.unconfirmed,retry:!ho(o),code:o}}function hc(e){return e.trim()}function z$(e,t){if(t.length===0)return hc(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
45
+ `);return hc(`${n}
46
+ ${e}`)}function mc(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function XR(e,t,n,r){if(t.peer!==void 0||n?.locality==="remote"||r?.locality==="remote")return!1;const o=t.submittedAt;if(o===void 0||o<=0)return!1;const s=e[0]?.ts;return s===void 0||s<=0?!1:s*1e3<=o}function K$(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,s])=>mc(s,t));return(r.find(([,s])=>s.submittedText!==void 0||s.undelivered!==void 0||s.error!==void 0||s.admissionAttempted===!0||s.pending===!0)??r[0])?.[0]??`send:${t}`}function Ai(e,t){return t??e??void 0}function Ym(e,t,n){return e?t??void 0:n??void 0}function V$(e,t,n){return Ai(e,Ym(e,t,n))}function Z$(e,t,n){const r=Ai(t,n);if(!e||r===void 0)return r;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 o=e.draftKey!==null&&e.sessionId===void 0&&t===e.draftKey&&n!==void 0,s=e.sessionId!==void 0&&n===e.sessionId;return o||s?e.key:r}function qR(e){return e instanceof Te?e.status===413||e.status===422?!0:e.code===mi||e.code===Pp||e.code===Ue.noCredential||e.code===Ue.serverUpdating||lf(e.code):e instanceof mn&&(e.code===Ei||e.code===Wm||lf(e.code))}function es(e,t){const n=e.startsWith("send:")?e.slice(5):null;return Ai(e.startsWith("draft:")?e:null,t??n)??e}function ex(e,t){const n=ct.getState(),r=es(e,t),o=r===""||r===e?[e]:[e,r];n.settleInFlight(o),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function Y$(e,t){if(!t||t.migratedHeld||t.pending||!(t.heldClaimCode!==void 0||t.errorRetry===void 0&&t.submittedRendered===void 0)||!t.admissionAttempted||t.submittedText===void 0)return!1;const r=es(e,t.sessionId);return ct.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),St.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:gt.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!ho(t.heldClaimCode),heldClaimCode:void 0}),!0}function J$(e,t){if(!t)return!1;const n=t.undelivered,r=t.submittedText,o=r!==void 0&&t.error!==void 0&&t.errorRetry!==void 0;if(!n&&!o)return!1;const s=es(e,t.sessionId);if(n){if(of(s,n.recordId))return!1;const c=Cm(s,n.recordId);return c!=="unseen"?(c==="owner"&&St.getState().retractUndelivered(e,n.recordId),!1):(ic(s,{id:n.recordId,text:n.text,images:[],documents:pc(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const a=t.admissionRequestId;return of(s,a)?!1:(ic(s,{id:a,text:t.submittedRendered??r,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${a}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type})),documents:pc(t.submittedFiles??[],a)}),!0)}function df(e,t,n){cR(es(e,t),n)}function tx(e,t,n){if(e.submittedText!==t)return!1;const r=e.submittedAttachments??[];return r.length!==n.length?!1:r.every((o,s)=>o===n[s])}function nx(e,t){return!!t&&e===t}const rx=3,ox=5e3,sx=2e3;async function ix(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=rx||!(n instanceof Te)||n.code!==mi)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??sx),ox);await new Promise(o=>setTimeout(o,r))}}async function ax(e){await ix(async()=>{await Je(e)})}async function Q$(e,t,n,r,o){const s=St.getState();if(nx(s.validatingSessionId,n))throw new mn(VR(),Ei);const a=s.drafts[e];if(a?.pending)return null;const c=hc(t.text),l=a?.submittedText!==void 0&&tx(a,c,t.attachments),d=a??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?a?.submittedImages??t.images:t.images,f=l?a?.submittedFiles??t.files:t.files,h=l?a?.submittedMode??t.mode:t.mode,m=l&&a?a.submittedInputMode:t.inputMode,y=l&&a?a.submittedInputPath:t.inputPath,b=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),v=Date.now();s.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:b,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:h,submittedInputMode:m,submittedInputPath:y,error:void 0,errorCode:void 0,submittedAt:v});const p=Ai(e.startsWith("draft:")?e:null,n??d.sessionId)??null;p&&ic(p,{id:b,submittedAt:v,text:c,images:u.map((F,C)=>({id:`${b}:${C}`,data:F.data_b64,attachment:null,mimeType:F.mime_type})),documents:pc(f??[],b),onPainted:r});let A=l,k=n??d.sessionId,T=null;try{if(!k){if(T="sessions.create",k=await s.createSession(t.cwd,d.target,d.createRequestId,yl(d.model??null,s.draftFastCarries),d.warmId,d.peer)??void 0,!k)throw new mn(St.getState().error??_("ui.common.errors.chat_start_simple"));s.updateDraft(e,{sessionId:k}),p&&rR(p,k),s.fetchSessions()}const F=l&&a?.submittedRendered!==void 0?a.submittedRendered:o?await o(k)??c:c;return A=!0,s.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:F}),k&&nR(k,b,F),T="sessions.message",await ax({op:"sessions.message",sessionId:k,requestId:b,text:F,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:h,inputMode:m,inputPath:y}),s.finishDraft(e,k),St.setState({error:null}),k}catch(F){St.setState({error:null});const C=l&&a?.admissionAttempted===!0,I=Zm(F,C),g=T==="sessions.message"&&ZR(F,c),w=g?si:kl(F),S=QR(F,w,C);let x=!1;const N=k??p??void 0;if(N&&I==="unknown"&&(x=A&&Cm(N,b)==="owner"),s.updateDraft(e,{pending:!1,admissionAttempted:I==="unknown"&&A,errorCode:w,error:S.message,errorRetry:S.retry}),x)return k?(s.finishDraft(e,k),k):null;const J=es(e,k??d.sessionId),M=p&&p!==J?[p,J]:[J];throw ct.getState().settleInFlight(M),p&&p!==J&&ct.getState().returnInFlight(p,J),N&&cc(N,b),e!==N&&cc(e,b),g?new Te(422,Hm(),F,si):F}}const Jm=50,uf="activity",cx=25,lx=500;function dx(e){return e?Jm:lx}function ff(e,t){return`${e}:${t}`}function ux(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function fx(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function px(e,t){const n=new Set;for(const[r,o]of Object.entries(t))o.locality==="remote"&&n.add(r);for(const r of e)r.locality==="remote"&&n.add(r.session_id);return n}function hx(e,t,n){if(t[n]?.locality==="remote")return!0;for(const r of e)if(r.session_id===n&&r.locality==="remote")return!0;return!1}function mx(e){const t=new Set(e.tailIds),n=new Set(e.keepIds??[]),r=new Set(e.page.map(c=>c.session_id)),o=e.sessions.filter(c=>r.has(c.session_id)?!1:e.scopeIds.has(c.session_id)||n.has(c.session_id)?!0:t.has(c.session_id)),s=e.merge(e.sessions,e.page),a=new Set(s.map(c=>c.session_id));for(const c of o)a.has(c.session_id)||(a.add(c.session_id),s.push(c));return{rows:s,tailIds:e.tailIds.filter(c=>a.has(c))}}function gx(e){const t=[...e.previousIds],n=new Set(t);for(const s of e.page)n.has(s.session_id)||(n.add(s.session_id),t.push(s.session_id));const r=[...e.sessions],o=new Map(r.map((s,a)=>[s.session_id,a]));for(const s of e.page){const a=o.get(s.session_id);if(a===void 0){o.set(s.session_id,r.length),r.push(s);continue}r[a]=e.merge(r[a],s)}return{rows:r,ids:t}}function Kn(e,t){return{...e,...t,...vx(e,t),...yx(t,e),attention:Ar(e?.attention,t.attention,t.session_id)}}const X$=Mm,_x=e=>e.filter(jm),pf=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const o=e[r],s=Ar(o.attention,n,t);if(s===o.attention)return e;const a=e.slice();return a[r]={...o,attention:s},a},bx=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function vx(e,t){const n=r=>typeof r?.status_revision=="number"&&typeof r?.status_epoch=="string"?{status_revision:r.status_revision,status_epoch:r.status_epoch}:void 0;return n(t)??n(e)??{}}function yx(e,t){const n=typeof t?.status_epoch=="string"&&t.status_epoch===e.status_epoch,r=t?.status_revision,o=e.status_revision;return t?.status!==void 0&&n&&typeof r=="number"&&typeof o=="number"&&r>o?{status:t?.status,status_revision:t?.status_revision,status_epoch:t?.status_epoch,...typeof t?.background_work=="boolean"?{background_work:t.background_work,subagents_running:t.subagents_running,subagents_queued:t.subagents_queued,jobs_running:t.jobs_running,waiting_on:t.waiting_on}:{}}:{}}function wx(e,t){const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(s.at<t){r=!0;continue}n[o]=s}return r?n:e}function _a(e,t){const n={...e.archiveFacts};delete n[t];const r={...e.placementFacts};delete r[t];const o=e.answerSeq+1;return{sessions:e.sessions.filter(s=>s.session_id!==t),archiveFacts:n,placementFacts:r,answerSeq:o,forgotten:{...e.forgotten,[t]:{at:o,title:e.sessions.find(s=>s.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function Qm(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 Xm(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 qm(e,t,n){const r=ct.getState();if(t&&t!==e){r.adoptReturnedText(t);const o=ct.getState().inputByConversation[t];o&&o.inFlight===void 0&&((o.currentInput??"")!==""||(o.attachments?.length??0)>0)&&r.returnInFlight(t,e)}n&&r.returnPayload(e,{text:n.text,attachments:n.attachments,replies:[]})}function kx(e,t,n){const r=ct.getState(),o=n??(e?r.getCurrentInput(e):"");o&&r.setComposerText(t,o),e&&e!==t&&r.setComposerText(e,"")}function Sx(e,t){let n=null;const r=[];for(const[o,s]of Object.entries(e))!s.sessionId||t[s.sessionId]===void 0||(n??={...e},n[o]=Qm(s),r.push({key:o,sessionId:s.sessionId,payload:Xm(s)}));return{drafts:n??e,restored:r}}function eg(e){return e.map(({id:t,name:n,mtime:r,...o})=>({...o,session_id:t,title:n,updated_at:r}))}function hf(e,t){return eg(e).filter(n=>t[n.session_id]===void 0)}function ba(e){return typeof e=="string"&&e.length>0?e:null}function Ex(e){if(e===null||typeof e!="object")return null;const t=e,n=c=>typeof c=="number"&&Number.isFinite(c)&&c>=0?Math.floor(c):null,r=n(t.total),o=n(t.active),s=n(t.unbound);if(r===null||o===null||s===null||!Array.isArray(t.scopes))return null;const a=[];for(const c of t.scopes){if(c===null||typeof c!="object")return null;const l=c;if(l.kind!=="team"&&l.kind!=="agent"||typeof l.name!="string"||l.name.length===0)continue;const d=n(l.total),u=n(l.active);d===null||u===null||a.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:r,active:o,unbound:s,scopes:a}}function Ax(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Kn(n.get(r.session_id),r)])).values()]}let va=0,gr=null;function Ix(e,t,n){const r=gr;if(r)return r.invalidated=!0,r.limit=e,r.withCounts=t,r.promise;const o={limit:e,withCounts:t,invalidated:!1,promise:null};return gr=o,o.promise=(async()=>{try{for(;;){o.invalidated=!1;let s;try{s=await n(o.limit,o.withCounts)}catch(a){if(o.invalidated)continue;throw a}if(!o.invalidated)return gr===o&&(gr=null),s}}finally{gr===o&&(gr=null)}})(),o.promise}function tg(){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 Rx(){const e=tg();return e.kind==="session"?e.sessionId:null}function xx(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 Tx(e,t){const n={...t,...e},{drafts:r,restored:o}=Sx(n.drafts,n.forgotten),s=r===n.drafts?n:{...n,drafts:r};for(const l of o)qm(l.key,l.sessionId,l.payload);const a=tg();if(a.kind==="session")return{...s,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...s,activeSessionId:null};const c=xx(s);return c?{...s,...c}:s}const St=Qo()(_i((e,t)=>({sessions:[],settingsIntents:LR,hydrateSettingsIntents:(n,r,o)=>{e(s=>{const a=WR(s.settingsIntents,n,r,o);return a===s.settingsIntents?s:{settingsIntents:a}})},applySettingsIntentFrame:(n,r,o)=>{e(s=>{const a=fc(s.settingsIntents,n,r,o);return a===s.settingsIntents?s:{settingsIntents:a}})},applySettingsIntentSlots:(n,r)=>{e(o=>{const s=Bm(o.settingsIntents,n,r);return s===o.settingsIntents?o:{settingsIntents:s}})},paintSettingsIntent:(n,r)=>{e(o=>({settingsIntents:GR(o.settingsIntents,n,r)}))},failSettingsIntent:(n,r,o,s)=>{e(a=>{const c=zR(a.settingsIntents,n,r,o,s);return c===a.settingsIntents?a:{settingsIntents:c}})},removeSettingsIntent:(n,r,o)=>{e(s=>{const a=KR(s.settingsIntents,n,r,o);return a===s.settingsIntents?s:{settingsIntents:a}})},cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:Rx(),activeDraftKey:null,drafts:{},validatingSessionId:null,pinFailure:null,pinFacts:{},answerSeq:0,readAckRearm:null,readAckNotice:null,loading:!1,truncated:!1,head:{pageIds:[],tailIds:[],nextCursor:null,tailCursor:null,tailStarted:!1,complete:!1,loading:!1,error:null,at:0},scopes:{},counts:null,statusUnavailable:[],archiveFacts:{},placementFacts:{},peerDeviceFacts:{},peerDeviceSnapshotAt:0,forgotten:{},stoppedTurns:{},archiveFailure:null,archiveUndo:null,draftsUndo:null,bulkReadDeferral:null,stagedByDiscard:null,deleteCandidate:null,archiveCandidate:null,error:null,cwd:"~",setCwd:n=>e(r=>{const o=Object.entries(r.drafts);return o.some(([,s])=>!s.sessionId)?{cwd:n,drafts:Object.fromEntries(o.map(([s,a])=>a.sessionId?[s,a]:[s,{...a,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=dx(t().cataloguePageable),r=!1)=>{const o=++va,s=t().answerSeq+1;e({answerSeq:s}),e({loading:!0,error:null});try{const a=await Ix(n,r,(l,d)=>Je({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:uf}:{}}));if(o!==va)return;const c=eg(a.sessions);e(l=>{const d={...l.pinFacts};for(const[g,w]of Object.entries(d))w.at>=s||delete d[g];const u=new Set(c.map(g=>g.session_id));let f=!1;const h={...l.forgotten};for(const[g,w]of Object.entries(h))w.at<s&&u.has(g)&&(delete h[g],f=!0);const m=f?h:l.forgotten,y=c.filter(g=>m[g.session_id]===void 0);let b=null;for(const g of y){const w=l.placementFacts[g.session_id];if(w===void 0||w.at>=s)continue;const S=g.locality==="remote"?"remote":g.locality==="local"?"local":null;S!==null&&(b??={...l.placementFacts},b[g.session_id]={locality:S,owner_device:typeof g.owner_device=="string"?g.owner_device:"",at:l.answerSeq+1})}const v=ba(a.next_cursor),p=v===null&&a.truncated!==!0,A=y.map(g=>g.session_id),k=l.sessions.filter(g=>m[g.session_id]===void 0&&(l.pinFacts[g.session_id]?.at??-1)>=s),T=mx({sessions:l.sessions,scopeIds:ux(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...fx(l.placementFacts)],tailIds:p?[]:l.head.tailIds,page:y,merge:Ax});let F=T.rows;for(const g of k){const w=l.pinFacts[g.session_id],S=F.findIndex(x=>x.session_id===g.session_id);S===-1?F=[...F,{...g,pinned:w.pinned}]:F[S]={...F[S],pinned:w.pinned}}const C=wx(l.archiveFacts,s),I=Ex(a.counts);return{sessions:F,pinFacts:d,archiveFacts:C,...b===null?{}:{placementFacts:b,answerSeq:l.answerSeq+1},forgotten:m,loading:!1,truncated:a.truncated===!0,head:{pageIds:A,tailIds:T.tailIds,nextCursor:v,tailCursor:p?null:l.head.tailStarted?l.head.tailCursor:v,tailStarted:l.head.tailStarted,complete:p,loading:!1,error:null,at:s},...I===null?{}:{counts:I},statusUnavailable:Array.isArray(a.degraded)?a.degraded.filter(g=>typeof g=="string"):[]}})}catch(a){o===va&&e({loading:!1,error:ks(a,_("ui.common.errors.chats_refresh"))})}},fetchCatalogueTail:async()=>{const n=t().head,r=n.tailCursor;if(!(r===null||n.loading)){e(o=>({head:{...o.head,loading:!0,error:null,tailStarted:!0,tailCursor:r}}));try{const o=await Je({op:"sessions.list",limit:Jm,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:uf}:{}}),s=hf(o.sessions,t().forgotten);e(a=>{const c=new Map(a.sessions.map((f,h)=>[f.session_id,h])),l=[...a.sessions],d=[];for(const f of s){const h=c.get(f.session_id);if(h===void 0){c.set(f.session_id,l.length),l.push(f),d.push(f.session_id);continue}l[h]=Kn(l[h],f)}const u=ba(o.next_cursor);return{sessions:l,head:{...a.head,tailIds:[...a.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(o){e(s=>({head:{...s.head,loading:!1,error:ks(o,_("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,o=null,s=cx)=>{const a=ff(n,r);if(t().scopes[a]?.loading)return;const c=t().answerSeq+1;e({answerSeq:c}),e(l=>({scopes:{...l.scopes,[a]:{ids:l.scopes[a]?.ids??[],nextCursor:l.scopes[a]?.nextCursor??null,loading:!0,error:null,at:c}}}));try{const l=await Je({op:"sessions.list",limit:s,include_archived:!1,scope_kind:n,scope_name:r,...o===null?{}:{cursor:o}}),d=hf(l.sessions,t().forgotten);e(u=>{const f=u.scopes[a];if(f===void 0||f.at!==c)return{};const h=o!==null&&l.cursor_missing!==!0,m=gx({sessions:u.sessions,previousIds:h?f.ids:[],page:d,merge:Kn}),y=ba(l.next_cursor);return{sessions:m.rows,scopes:{...u.scopes,[a]:{ids:m.ids,nextCursor:y,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[a];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[a]:{...u,loading:!1,error:ks(l,_("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const o=ff(n,r);e(s=>{const a=s.scopes[o];if(a===void 0)return{};const c={...s.scopes};delete c[o];const l=s.activeSessionId,d=new Set(a.ids),u=new Set(s.head.pageIds),f=s.sessions.filter(h=>!d.has(h.session_id)||u.has(h.session_id)||l!==null&&h.session_id===l);return{scopes:c,sessions:f}})},setCataloguePageable:n=>{t().cataloguePageable!==n&&e({cataloguePageable:n})},setCatalogueActivityHead:n=>{t().catalogueActivityHead!==n&&e({catalogueActivityHead:n})},setDraftFastCarries:n=>{t().draftFastCarries!==n&&e({draftFastCarries:n})},setDraftWarmable:n=>{if(t().draftWarmable===n||(e({draftWarmable:n}),!n))return;const r=t().activeDraftKey,o=r?t().drafts[r]:void 0;if(!r||!o||o.sessionId||o.warmId)return;ct.getState().inputByConversation[r]?.currentInput&&t().ensureDraftWarm(r)},setArchiveUndo:n=>{e({archiveUndo:n})},setDraftsUndo:n=>{e({draftsUndo:n})},raiseBulkReadDeferral:n=>{e(r=>({bulkReadDeferral:{count:n,at:r.answerSeq+1}}))},clearBulkReadDeferral:()=>{e({bulkReadDeferral:null})},setStagedByDiscard:n=>{e({stagedByDiscard:n})},restoreDraftsUndo:()=>e(n=>{const r=n.draftsUndo;if(!r)return{};const o={...n.drafts};for(const[a,c]of Object.entries(r.drafts))a in o||(o[a]=c);const s=ct.getState();for(const[a,c]of Object.entries(r.composer)){const l=s.inputByConversation[a];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||s.restoreRow(a,c)}return{drafts:o,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,r,o)=>{const s=t().answerSeq+1,a=t().archiveFacts[n]??null,c=o??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:s,archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:s,answered:!1}}}));try{return await Je({op:"sessions.archive",sessionId:n,archived:r}),e(l=>{const u=l.archiveFacts[n]?.at!==s;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:s,answered:!0}},archiveUndo:u?l.archiveUndo:r?{sessionId:n,title:c??void 0,archived:!0,at:s}:null,archiveFailure:l.archiveFailure?.sessionId===n?null:l.archiveFailure}}),!0}catch(l){return e(d=>{const u=d.archiveFacts[n]?.at!==s,f={...d.archiveFacts};return u||(a?.answered===!0?f[n]=a:(delete f[n],a!==null&&t().fetchSessions())),{archiveFacts:u?d.archiveFacts:f,answerSeq:d.answerSeq+1,archiveFailure:{sessionId:n,at:d.answerSeq+1,archived:r,title:c||"",detail:l instanceof Te&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await Je({op:"sessions.delete",sessionId:n,confirmed:!0}),e(r=>_a(r,n)),t().retireDraftsForSession(n),{ok:!0}}catch(r){const o=r instanceof Te?r.status:null,s=r instanceof Te?r.code??null:null;return o===404?(e(a=>_a(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:s==="session_delete_refused",detail:r instanceof Te&&r.message?r.message:_("ui.common.errors.conversation_delete")}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,o=crypto.randomUUID(),s,a,c)=>{try{const l=await Je({op:"sessions.create",requestId:o,cwd:n,...r?{target:r}:{},...s?{model:s}:{},...a?{draftId:a}:{},...c?{peer:c}:{}}),d=t().sessions.some(f=>f.session_id===l.session_id),u=Date.now()/1e3;return t().upsertSession({session_id:l.session_id,cwd:n,binding:l.binding,...d?{}:{created_at:u,updated_at:u}}),c&&t().settlePlacement(l.session_id,{locality:"remote",owner_device:c}),l.session_id}catch(l){throw e({error:ks(l,_("ui.common.errors.chat_start"))}),l}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,r=Date.now())=>e(o=>({stoppedTurns:{...o.stoppedTurns,[n]:r}})),clearTurnStopped:n=>e(r=>{if(!(n in r.stoppedTurns))return r;const{[n]:o,...s}=r.stoppedTurns;return{stoppedTurns:s}}),openDraft:n=>{t().drafts[n]&&e({activeDraftKey:n,activeSessionId:null,validatingSessionId:null,error:null})},confirmSessionLive:n=>{n&&t().validatingSessionId===n&&e({validatingSessionId:null})},confirmSessionMissing:n=>{!n||t().validatingSessionId!==n||(e({validatingSessionId:null,..._a(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:bx(r.readAckRearm,n)}))},publishReadAckNotice:(n,r,o)=>{e(s=>{const a=s.readAckNotice;return a?.sessionId===n&&a.kind===r?s:{readAckNotice:{sessionId:n,kind:r,revision:(a?.revision??0)+1,reason:o}}})},clearReadAckNotice:n=>{e(r=>r.readAckNotice?.sessionId===n?{readAckNotice:null}:r)},applyAttention:(n,r)=>{e(o=>{const s=pf(o.sessions,n,r);return s===o.sessions?o:{...o,sessions:s}})},applyAttentionMany:n=>{e(r=>{let o=r.sessions;for(const s of n){const a=s?.conversation_id;typeof a!="string"||!a.startsWith("session/")||(o=pf(o,a.slice(8),s))}return o===r.sessions?r:{...r,sessions:o}})},markAllRead:async()=>{const n=_x(t().sessions).map(a=>({sessionId:a.session_id,completionToken:a.attention?.completion_token}));if(n.length===0)return{attempted:0,cleared:0,superseded:0,unknown:0,deferred:0};const r=await Je({op:"attention.seen",items:n});t().applyAttentionMany(r.read);const o=px(t().sessions,t().placementFacts),s=r.unknown.filter(a=>o.has(a)).length;return{attempted:n.length,cleared:r.read.length,superseded:r.superseded.length,unknown:r.unknown.length,deferred:s}},applySessionStatus:(n,r,o,s,a)=>{e(c=>{const l=c.sessions.findIndex(y=>y.session_id===n);let d=!1;const u=c.sessions.map(y=>{if(y.status_epoch===void 0&&y.status_revision===void 0||y.status_epoch===s)return y;d=!0;const{status_revision:b,status_epoch:v,...p}=y;return p});if(l<0)return d?{...c,sessions:u}:c;const f=u[l],m=!(a!==void 0&&Object.keys(a).some(y=>f[y]!==a[y]))&&f.status?.code===r.code&&f.status?.label===r.label&&f.status_revision===o&&f.status_epoch===s;return m&&!d?c:(m||(u[l]={...f,...a,status:r,status_revision:o,status_epoch:s}),{...c,sessions:u})})},openSession:async n=>t().activeSessionId===n&&!t().activeDraftKey?(t().rearmReadAck(n),!0):(e({activeSessionId:n,activeDraftKey:null,validatingSessionId:n,error:null}),t().rearmReadAck(n),!0),stageDraft:(n,r=!1)=>{const s=(!r&&n?`draft:${n.kind}:${n.name}`:null)??`draft:${crypto.randomUUID()}`,a=t().drafts[s],c=Ym(t().activeDraftKey,t().activeDraftKey?t().drafts[t().activeDraftKey]?.sessionId:void 0,t().activeSessionId);if(a?.sessionId&&!a.pending&&a.sessionId!==c){const d=t().drafts[`send:${a.sessionId}`]?`draft:${crypto.randomUUID()}`:`send:${a.sessionId}`;e(u=>{const f={...u.drafts};return delete f[s],f[d]={...a,key:d},{drafts:f}})}const l=t().drafts[s];return e(d=>({activeDraftKey:s,validatingSessionId:null,error:null,drafts:{...d.drafts,[s]:l??{key:s,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),s},restageDraft:(n,r)=>{const o=t().activeDraftKey,s=t().stageDraft(n);return kx(o,s,r),s},startNewChat:n=>{const r=t().stageDraft();return e({activeSessionId:null,validatingSessionId:null}),n&&(ct.getState().adoptReturnedText(n),ct.getState().inputByConversation[n]?.pendingText===void 0&&ct.getState().returnInFlight(n,r)),r},updateDraft:(n,r)=>e(o=>{const s=o.drafts[n],a=r.key!==void 0&&r.createRequestId!==void 0&&r.admissionRequestId!==void 0;return!s&&!a?{}:{drafts:{...o.drafts,[n]:{...o.drafts[n],...r}}}}),setDraftPeer:(n,r)=>e(o=>{const s=o.drafts[n];if(!s)return{};const a=r??void 0;return(s.peer??void 0)===a?{}:{drafts:{...o.drafts,[n]:{...s,peer:a,...s.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}}),setDraftModel:(n,r)=>e(o=>{const s=o.drafts[n];return s?{drafts:{...o.drafts,[n]:{...s,model:r,...s.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}:{}}),ensureDraftWarm:n=>{const r=t();if(!r.draftWarmable)return;const o=r.drafts[n];if(!o||o.sessionId||o.warmId||!r.cwd||o.peer)return;const s=o.draftRequestId??crypto.randomUUID();o.draftRequestId||t().updateDraft(n,{draftRequestId:s});const a=yl(o.model??null,r.draftFastCarries);Je({op:"sessions.draft",requestId:s,cwd:r.cwd,...o.target?{target:o.target}:{},...a?{model:a}:{}}).then(c=>{const l=t().drafts[n];l&&!l.warmId&&!l.sessionId&&l.draftRequestId===s&&t().updateDraft(n,{warmId:c.draft_id})}).catch(()=>{})},finishDraft:(n,r)=>e(o=>{ex(n,r);const s={...o.drafts};return delete s[n],{drafts:s,...o.activeDraftKey===n?{activeDraftKey:null,activeSessionId:r}:{}}}),retireDraftSession:n=>{const r=t().drafts[n];if(!r?.sessionId||r.pending)return;const o=r.sessionId,s=Xm(r);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:Qm(c)}}}),qm(n,o,s)},retireDraftsForSession:n=>{for(const[r,o]of Object.entries(t().drafts))r.startsWith("draft:")&&o.sessionId===n&&t().retireDraftSession(r)},retireDraftWarm:n=>{const r=Object.entries(t().drafts).filter(([o,s])=>o.startsWith("draft:")&&s.warmId===n&&!s.sessionId);r.length!==0&&e(o=>{const s={...o.drafts};for(const[a]of r){const c=s[a];!c||c.warmId!==n||c.sessionId||(s[a]={...c,warmId:void 0,draftRequestId:crypto.randomUUID()})}return{drafts:s}})},discardDraft:n=>e(r=>{const o={...r.drafts},s=o[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),a=o[n],c=ct.getState().inputByConversation[n];ys(n),s&&s!==n&&ys(s),delete o[n],ct.getState().clearAll(n);const l=a?{at:r.answerSeq+1,keys:[n],drafts:{[n]:a},composer:c?{[n]:c}:{}}:null;return{drafts:o,...l?{answerSeq:l.at,draftsUndo:l}:{},...r.activeDraftKey===n?{activeDraftKey:null}:{}}}),discardDrafts:n=>e(r=>{const o={...r.drafts};let s=!1;const a=[],c={},l={};for(const u of n){if(!(u in o))continue;const f=o[u];if(!f)continue;const h=f.sessionId??(u.startsWith("send:")?u.slice(5):void 0);ys(u),h&&h!==u&&ys(h),a.push(u),c[u]=f;const m=ct.getState().inputByConversation[u];m&&(l[u]=m),delete o[u],ct.getState().clearAll(u),r.activeDraftKey===u&&(s=!0)}if(a.length===0)return{};const d=r.answerSeq+1;return{drafts:o,answerSeq:d,draftsUndo:{at:d,keys:a,drafts:c,composer:l},...s?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,r,o)=>e(s=>{const a=r.map(S=>S.id),c=Object.entries(s.drafts).filter(([,S])=>mc(S,n)&&S.undelivered!==void 0&&a.includes(S.undelivered.recordId));let l=s.drafts;if(c.length>0){l={...l};for(const[S,x]of c){const N=x.undelivered?.recordId,{undelivered:J,...M}=x;l[S]=M,N!==void 0&&df(S,x.sessionId,N)}}const d=Object.entries(l).find(([,S])=>mc(S,n)&&S.admissionAttempted===!0&&S.pending!==!0&&S.submittedText!==void 0);if(!d)return c.length>0?{drafts:l}:{};const[u,f]=d,h=f.admissionRequestId,m=a.includes(h);if(!m&&!o)return c.length>0?{drafts:l}:{};if(!m&&!XR(r,f,s.placementFacts[n],s.sessions.find(S=>S.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:y,submittedText:b,submittedAttachments:v,submittedImages:p,submittedMode:A,submittedInputMode:k,submittedInputPath:T,heldClaimCode:F,error:C,errorCode:I,errorRetry:g,...w}=f;return m||cc(n,h),{drafts:{...l,[u]:{...w,...m?{}:{undelivered:{recordId:h,text:b??"",attachments:v??[]}},admissionRequestId:crypto.randomUUID()}}}}),retractUndelivered:(n,r)=>{const o=t().drafts[n];!o||o.undelivered?.recordId!==r||(e(s=>{const{undelivered:a,...c}=s.drafts[n];return{drafts:{...s.drafts,[n]:c}}}),df(n,o.sessionId,r))},bindSession:(n,r)=>t().setActiveSession(r),beginAnswer:()=>{const n=t().answerSeq+1;return e({answerSeq:n}),n},applySearchAnswer:(n,r)=>e(o=>{let s=null,a=null,c=null;for(const l of r){const d=o.archiveFacts[l.id];if(d!==void 0&&d.at<n&&(c=c??{...o.archiveFacts},delete c[l.id]),!(d!==void 0&&d.at>=n)&&typeof l.archived=="boolean"&&o.sessions.some(f=>f.session_id===l.id&&f.archived!==l.archived)){a=a??o.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.archived=l.archived===!0)}if(typeof l.pinned!="boolean")continue;const u=o.pinFacts[l.id];if(!(u!==void 0&&u.at>=n)&&(u!==void 0&&(s=s??{...o.pinFacts},delete s[l.id]),o.sessions.some(f=>f.session_id===l.id&&f.pinned!==l.pinned))){a=a??o.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return s===null&&a===null&&c===null?{}:{...s===null?{}:{pinFacts:s},...a===null?{}:{sessions:a},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,r,o)=>{const s=t().sessions.find(h=>h.session_id===n),a=t().pinFacts[n]??null,c=s===void 0?a?.pinned??!1:s.pinned===!0,l=s===void 0&&o!==void 0?{session_id:n,title:o.title||"",updated_at:o.updated_at,pinned:r}:null,d=t().beginAnswer(),u=s?.title??o?.title,f=s?.updated_at??o?.updated_at;e(h=>({sessions:l===null?h.sessions.map(m=>m.session_id===n?{...m,pinned:r}:m):[...h.sessions,l],pinFacts:{...h.pinFacts,[n]:{pinned:r,at:d,title:u,updated_at:f}},pinFailure:null}));try{const h=await Je({op:"sessions.pin",sessionId:n,pinned:r});let m=!1;return e(y=>{const b=y.pinFacts[n];return b===void 0||b.at!==d?{}:(m=!0,{sessions:y.sessions.map(v=>v.session_id===n?{...v,pinned:h.pinned===!0}:v),pinFacts:{...y.pinFacts,[n]:{...b,pinned:h.pinned===!0}}})}),m}catch(h){return e(m=>{const y=m.pinFacts[n];if(y!==void 0&&y.at!==d)return{};const b={...m.pinFacts};return a===null&&s===void 0?delete b[n]:b[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:m.sessions.map(v=>v.session_id===n?{...v,pinned:c}:v),pinFacts:b,pinFailure:{sessionId:n,pinned:r,title:s?.title||"",detail:Vc(h,"")}}}),!1}},upsertSession:n=>e(r=>({sessions:r.sessions.some(s=>s.session_id===n.session_id)?r.sessions.map(s=>s.session_id===n.session_id?Kn(s,n):s):[...r.sessions,n]})),settlePlacement:(n,r)=>{const o=t().beginAnswer();e(s=>({sessions:s.sessions.map(a=>a.session_id===n?Kn(a,{session_id:n,locality:r.locality,owner_device:r.owner_device}):a),placementFacts:{...s.placementFacts,[n]:{locality:r.locality,owner_device:r.owner_device,at:o}}}))},settlePeerCatalogue:(n,r,o={},s=void 0)=>{e(a=>{const c={...a.forgotten};for(const g of n)c[g.session_id]?.at<r&&delete c[g.session_id];const l=n.filter(g=>{if(c[g.session_id]||g.locality==="remote"&&a.peerDeviceSnapshotAt>r&&typeof g.owner_device=="string"&&!a.peerDeviceFacts[g.owner_device])return!1;const w=a.placementFacts[g.session_id];return!w||w.at<r}),d={...a.placementFacts},u=new Set;let f=!1,h=0;for(const g of l){const w=g.locality==="remote"?"remote":g.locality==="local"?"local":null;if(w===null)continue;const S=a.placementFacts[g.session_id];if(S!==void 0){if(S.at>=r)continue}else if(w!=="remote")continue;h=h===0?a.answerSeq+1:h,u.add(g.session_id),d[g.session_id]={locality:w,owner_device:w==="remote"&&typeof g.owner_device=="string"?g.owner_device:"",at:h},f=!0}const m=s===void 0?null:DR(a.peerDeviceFacts,o,a.peerDeviceSnapshotAt,s),y=m?.facts??$R(a.peerDeviceFacts,Object.fromEntries(Object.entries(o).filter(([,g])=>g.at>a.peerDeviceSnapshotAt))),b=l.filter(g=>g.locality==="remote");let v=a.sessions,p=!1;const A=[],k=new Map;for(let g=0;g<v.length;g+=1)k.set(v[g].session_id,g);for(const g of b){const w=k.get(g.session_id);if(w===void 0){A.push(g);continue}v[w]!==g&&(p||(v=v.slice(),p=!0),v[w]=Kn(v[w],g))}A.length>0&&(v=[...v,...A]);for(const g of l){if(g.locality==="remote"||!u.has(g.session_id))continue;const w=k.get(g.session_id);w===void 0||v[w]===g||(p||(v=v.slice(),p=!0),v[w]=Kn(v[w],g))}const T=new Set(l.map(g=>g.session_id)),F=new Set;for(const g of l)g.locality==="remote"&&typeof g.owner_device=="string"&&g.owner_device!==""&&g.reachable!==!1&&F.add(g.owner_device);const C=new Set;for(const g of v){if(g.locality!=="remote"||typeof g.owner_device!="string"||!m?.removed.includes(g.owner_device))continue;const w=a.placementFacts[g.session_id];w&&w.at>=(s??0)||(C.add(g.session_id),delete d[g.session_id])}for(const[g,w]of Object.entries(a.placementFacts))w.locality==="remote"&&(T.has(g)||w.at>=r||y[w.owner_device]?.reachable!==!1&&(w.owner_device===""||!F.has(w.owner_device)||(C.add(g),delete d[g])));C.size>0&&(v=v.filter(g=>!C.has(g.session_id)));const I=v.map(g=>NR(g,y));return I.some((g,w)=>g!==v[w])&&(v=I,p=!0),!f&&A.length===0&&!p&&C.size===0&&Object.keys(o).length===0&&s===void 0?{}:{sessions:v,placementFacts:d,peerDeviceFacts:y,peerDeviceSnapshotAt:m?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:Tx,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 q$(e,t){return t?e.filter(n=>n.archived!==!0):e}function eN(e,t){let n=!1;const r=e.map(o=>{const s=t[o.session_id];return s===void 0||!s.answered||o.archived===s.archived?o:(n=!0,{...o,archived:s.archived})});return n?r:e}function tN(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function nN(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const rN="This backend cannot archive conversations. Update the backend and try again.",oN="This conversation is already archived. Use /unarchive to restore it.",sN="This conversation is not archived, so there is nothing to restore.",iN="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 aN(e,t,n){return n&&e&&t.trim().length>0}function cN(e,t){return t===e}const ie=e=>{const[t,n,r]=[1,3,5].map(f=>{const h=Number.parseInt(e.slice(f,f+2),16)/255;return h<=.04045?h/12.92:((h+.055)/1.055)**2.4}),o=(t*.4124564+n*.3575761+r*.1804375)/.95047,s=t*.2126729+n*.7151522+r*.072175,a=(t*.0193339+n*.119192+r*.9503041)/1.08883,c=f=>f>216/24389?Math.cbrt(f):841/108*f+4/29,[l,d,u]=[c(o),c(s),c(a)];return[116*d-16,500*(l-d),200*(d-u)]},de=(e,t)=>{const[n,r,o]=ie(e),[s,a,c]=ie(t),l=Math.PI/180,d=180/Math.PI,u=(Math.hypot(r,o)+Math.hypot(a,c))/2,f=.5*(1-Math.sqrt(u**7/(u**7+25**7))),[h,m]=[(1+f)*r,(1+f)*a],[y,b]=[Math.hypot(h,o),Math.hypot(m,c)],v=(P,z)=>{if(P===0&&z===0)return 0;const Z=Math.atan2(P,z)*d;return Z<0?Z+360:Z},[p,A]=[v(o,h),v(c,m)],k=s-n,T=b-y;let F=0;y*b!==0&&(F=A-p,F>180?F-=360:F<-180&&(F+=360));const C=2*Math.sqrt(y*b)*Math.sin(F*l/2),I=(n+s)/2,g=(y+b)/2;let w;y*b===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),x=1+.015*(I-50)**2/Math.sqrt(20+(I-50)**2),N=1+.045*g,J=1+.015*g*S,M=-Math.sin(2*30*Math.exp(-(((w-275)/25)**2))*l)*2*Math.sqrt(g**7/(g**7+25**7));return Math.sqrt((k/x)**2+(T/N)**2+(C/J)**2+M*(T/N)*(C/J))},ii=([e,t,n])=>{const r=(e+16)/116,o=r+t/500,s=r-n/200,a=m=>m>6/29?m**3:3*(6/29)**2*(m-4/29),c=a(o)*.95047,l=a(r),d=a(s)*1.08883,f=[c*3.2404542+l*-1.5371385+d*-.4985314,c*-.969266+l*1.8760108+d*.041556,c*.0556434+l*-.2040259+d*1.0572252].map(m=>m<=.0031308?12.92*m:1.055*m**(1/2.4)-.055);if(f.some(m=>m<-.0015||m>1.0015))return null;const h=m=>Math.round(Math.min(1,Math.max(0,m))*255).toString(16).padStart(2,"0").toUpperCase();return`#${f.map(h).join("")}`},L=e=>Math.round(e*100)/100,mf=e=>{const t=e.replace("#","").trim(),n=t.length===3?t.split("").map(a=>a+a).join(""):t,[r,o,s]=[0,2,4].map(a=>{const c=Number.parseInt(n.slice(a,a+2),16)/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4});return .2126*r+.7152*o+.0722*s},oe=(e,t)=>{const[n,r]=[mf(e),mf(t)].sort((o,s)=>s-o);return(n+.05)/(r+.05)},Cx=/^#[0-9a-fA-F]{3,8}$/,W=e=>typeof e=="string"&&Cx.test(e),ya=(e,t,n)=>{const r=f=>{const h=f.replace("#","").trim(),m=h.length===3?h.split("").map(y=>y+y).join(""):h;return[0,2,4].map(y=>Number.parseInt(m.slice(y,y+2),16))},[o,s,a]=r(e),[c,l,d]=r(t),u=(f,h)=>Math.round(f*n+h*(1-n));return`#${[u(o,c),u(s,l),u(a,d)].map(f=>f.toString(16).padStart(2,"0")).join("")}`},bn={"under-window":{dark:81,light:199},menu:{dark:102,light:171},popover:{dark:122,light:143}},Sl=["canvas","surface","elevated"],Ii=["ink","inkMuted","inkDim"],ts=4.5,Ox=3,Px=1.5,ng=["danger","success","warning","info"],rg={hover:.05,selected:.08,field:.05,work:.08},og=4,Mx=1.5,El=.96,jx=["sunken","surface"],sg=3.5,gc=e=>{const t=e.replace("#",""),n=t.length===3?t.split("").map(a=>a+a).join(""):t.slice(0,6),[r,o,s]=[0,2,4].map(a=>{const c=Number.parseInt(n.slice(a,a+2),16)/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4});return .2126*r+.7152*o+.0722*s},Hr=(e,t)=>{const[n,r]=[gc(e),gc(t)].sort((o,s)=>s-o);return(n+.05)/(r+.05)},gf=(e,t)=>Number.parseInt(e.slice(1+t*2,3+t*2),16),Fn=e=>`#${e.toString(16).padStart(2,"0").repeat(3)}`,st=(e,t,n)=>`#${[0,1,2].map(r=>Math.round(gf(e,r)*t+gf(n,r)*(1-t)).toString(16).padStart(2,"0")).join("")}`,jt=e=>gc(e.canvas)<.18?"dark":"light",ig=(e,t,n,r,o=ts)=>{for(let s=.2;s<=1.0001;s+=.01)if(Hr(e[n],st(e[t],s,r))>=o)return Math.round(s*100)/100;return 1},Al=(e,t,n,r,o)=>{for(let s=.2;s<=1.0001;s+=.01){const a=st(e[t],s,r);if(Hr(e[n],st(e.ink,o,a))>=(n==="inkDim"?sg:ts))return Math.round(s*100)/100}return 1},$x=(e,t)=>st(e.ink,t,e.borderControl);function Nx(e,t){const n={};for(const r of["dark","light"]){let o=0;for(const s of Object.keys(bn))for(const{palette:a}of t){if(jt(a)!==r)continue;const c=st(a.canvas,e[s][r].canvas,Fn(bn[s][r]));let l=.01;for(;l<1&&de(st(a.ink,l,c),c)<og;)l=Math.round((l+.01)*100)/100;o=Math.max(o,l)}n[r]=Math.round(o*100)/100}return n}function Dx(e,t=rg){const n={};for(const[r,o]of Object.entries(bn)){n[r]={};for(const s of["dark","light"]){n[r][s]={};for(const a of Sl){let c=0;for(const{palette:l}of e)if(jt(l)===s)for(const d of Ii)c=Math.max(c,ig(l,a,d,Fn(o[s])),...Object.values(t).map(u=>Al(l,a,d,Fn(o[s]),u)));n[r][s][a]=Math.min(1,Math.round((c+.02)*100)/100)}}}return n}function Lx(e){const t={};for(const n of["dark","light"]){let r=0;for(const{palette:o}of e){if(jt(o)!==n)continue;const s=n==="dark"?"#ffffff":"#000000";for(const a of Ii)r=Math.max(r,ig(o,"elevated",a,s,a==="inkDim"?sg:ts))}t[n]=Math.round(r*100)/100}return t}function ag(e,t){let n=1;for(const r of Object.keys(e))n=Math.min(n,e[r][t]?.canvas??1);return n}function cg(e,t,n,r){const o=r==="dark"?"#ffffff":"#000000";return st(e.elevated,t,st(e.canvas,ag(n,r),o))}function Fx(e,t){const n={};for(const r of["dark","light"]){const o=ag(t,r),s=r==="dark"?"#ffffff":"#000000";let a=0;for(const{palette:c}of e){if(jt(c)!==r)continue;const l=st(c.canvas,o,s);for(const d of["inkMuted","ink"]){let u=.2;for(;u<=1.0001&&!(Hr(c[d],st(c.elevated,u,l))>=ts);u+=.01);a=Math.max(a,Math.round(Math.min(u,1)*100)/100)}}n[r]=Math.round(a*100)/100}return n}function Ux(e,t,n){const r={};for(const o of["dark","light"]){let s=0;for(const{palette:a}of e){if(jt(a)!==o)continue;const c=cg(a,n[o],t,o);for(const l of ng){let d=0;for(;d<=1.0001&&!(Hr(st(a.ink,d,a[l]),c)>=ts);d+=.05);s=Math.max(s,Math.round(Math.min(d,1)*100)/100)}}r[o]=Math.round(s*100)/100}return r}function Bx(e,t,n){const r={};for(const o of["dark","light"]){const s=n[o],a=Math.max(El,s),c=[Math.round((a-.8*(a-s))*100)/100,s];let l=0;for(const{palette:d}of e)if(jt(d)===o)for(const u of c){const f=cg(d,u,t,o);let h=0;for(;h<=1.0001&&!(Hr(st(d.ink,h,d.hairline),f)>=Px);h+=.05);l=Math.max(l,Math.round(Math.min(h,1)*100)/100)}r[o]=Math.round(l*100)/100}return r}function Hx(e,t){const n={};for(const[r,o]of Object.entries(bn)){n[r]={};for(const s of["dark","light"]){let a=0;for(const{palette:c}of t)if(jt(c)===s)for(const l of Sl){const d=st(c[l],e[r][s][l],Fn(o[s]));let u=0;for(;u<1&&Hr($x(c,u),d)<Ox;)u=Math.round((u+.05)*100)/100;a=Math.max(a,u)}n[r][s]=Math.min(1,Math.round((a+.05)*100)/100)}}return n}const to=new Map;function Wx(e){const t=jt(e),n=r=>Object.values(bn).every(o=>Sl.every(s=>Ii.every(a=>Al(e,s,a,Fn(o[t]),r)<=.95)));return Object.fromEntries(Object.entries(rg).map(([r,o])=>{let s=o;for(;s>.01&&!n(s);)s=Math.round((s-.01)*100)/100;return[r,s]}))}function Gx(e,t){const n=jt(e);let r=Nx(t,[{palette:e}])[n];const o=()=>Object.entries(bn).every(([s,a])=>Array.from({length:101},(c,l)=>{const d=t[s][n].canvas,u=Math.max(El,d),f=Math.round((u-l/100*(u-d))*100)/100,h=st(e.canvas,f,Fn(a[n]));return de(st(e.ink,r,h),h)>=og}).every(Boolean));for(;r<1&&!o();)r=Math.round((r+.01)*100)/100;return{dark:0,light:0,[n]:r}}function zx(e,t){const n=jt(e);for(const r of jx)for(let o=5;o<=104;o++){const s=o/100;if(Object.entries(bn).every(([c,l])=>Array.from({length:101},(d,u)=>{const f=t[c][n].canvas,h=Math.max(El,f),m=Math.round((h-u/100*(h-f))*100)/100,y=Math.round(m*s*100)/100;if(y>1)return!1;const b=st(e.canvas,m,Fn(l[n]));return de(st(e[r],y,b),b)>=Mx}).every(Boolean)))return{dark:{role:r,scale:s},light:{role:r,scale:s}}}return null}function Kx(e,t){const n=jt(e);for(;;){const r=Gx(e,t);let o=!1;for(const[s,a]of Object.entries(bn)){const c=Math.min(1,Math.round((Math.max(...Ii.map(l=>Al(e,"canvas",l,Fn(a[n]),r[n])))+.02)*100)/100);c>t[s][n].canvas&&(t[s][n].canvas=c,o=!0)}if(!o)return r}}const Vx=["canvas","surface","elevated","sunken","ink","inkMuted","inkDim","borderControl","hairline",...ng];function Zx(e){for(const t of Vx){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 lN(e){Zx(e);const t=JSON.stringify(e),n=to.get(t);if(n)return n;const r=[{palette:e}],o=Wx(e),s=Dx(r,o);let a,c;for(let u=0;u<=99;u++){let f=!1;for(const h of Object.keys(bn)){const m=jt(e),y=s[h][m].canvas,b=Math.max(y,u/100);f||=b!==y,s[h][m].canvas=b}if(!(u>0&&!f)&&(a=Kx(e,s),c=zx(e,s),c))break}if(!c)throw new Error("palette roles cannot form a readable transparent lane");const l=Fx(r,s),d={alphaFloor:s,blockVeil:a,laneWash:c,controlMix:Hx(s,r),bandFloor:Lx(r),overlayFloor:l,overlayInkMix:Ux(r,s,l),overlayEdgeMix:Bx(r,s,l),stateAlpha:o};return to.set(t,d),to.size>8&&to.delete(to.keys().next().value),d}const _c=new WeakMap,Yx=(e,t)=>{t?_c.set(e,t):_c.delete(e)},dN=e=>_c.get(e);/**
47
47
  * @remix-run/router v1.23.0
48
48
  *
49
49
  * Copyright (c) Remix Software Inc.
@@ -52,7 +52,7 @@ ${e}`)}function hc(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}f
52
52
  * LICENSE.md file in the root directory of this source tree.
53
53
  *
54
54
  * @license MIT
55
- */function Go(){return Go=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Go.apply(this,arguments)}var Cn;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Cn||(Cn={}));const gf="popstate";function lN(e){e===void 0&&(e={});function t(o,s){let{pathname:a="/",search:c="",hash:l=""}=lr(o.location.hash.substr(1));return!a.startsWith("/")&&!a.startsWith(".")&&(a="/"+a),_c("",{pathname:a,search:c,hash:l},s.state&&s.state.usr||null,s.state&&s.state.key||"default")}function n(o,s){let a=o.document.querySelector("base"),c="";if(a&&a.getAttribute("href")){let l=o.location.href,d=l.indexOf("#");c=d===-1?l:l.slice(0,d)}return c+"#"+(typeof s=="string"?s:cg(s))}function r(o,s){Il(o.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(s)+")")}return Jx(t,n,r,e)}function ze(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Il(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Yx(){return Math.random().toString(36).substr(2,8)}function _f(e,t){return{usr:e.state,key:e.key,idx:t}}function _c(e,t,n,r){return n===void 0&&(n=null),Go({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?lr(t):t,{state:n,key:t&&t.key||r||Yx()})}function cg(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function lr(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function Jx(e,t,n,r){r===void 0&&(r={});let{window:o=document.defaultView,v5Compat:s=!1}=r,a=o.history,c=Cn.Pop,l=null,d=u();d==null&&(d=0,a.replaceState(Go({},a.state,{idx:d}),""));function u(){return(a.state||{idx:null}).idx}function f(){c=Cn.Pop;let v=u(),p=v==null?null:v-d;d=v,l&&l({action:c,location:b.location,delta:p})}function h(v,p){c=Cn.Push;let A=_c(b.location,v,p);n&&n(A,v),d=u()+1;let k=_f(A,d),C=b.createHref(A);try{a.pushState(k,"",C)}catch(L){if(L instanceof DOMException&&L.name==="DataCloneError")throw L;o.location.assign(C)}s&&l&&l({action:c,location:b.location,delta:1})}function m(v,p){c=Cn.Replace;let A=_c(b.location,v,p);n&&n(A,v),d=u();let k=_f(A,d),C=b.createHref(A);a.replaceState(k,"",C),s&&l&&l({action:c,location:b.location,delta:0})}function y(v){let p=o.location.origin!=="null"?o.location.origin:o.location.href,A=typeof v=="string"?v:cg(v);return A=A.replace(/ $/,"%20"),ze(p,"No window.location.(origin|href) available to create URL for href: "+A),new URL(A,p)}let b={get action(){return c},get location(){return e(o,a)},listen(v){if(l)throw new Error("A history only accepts one active listener");return o.addEventListener(gf,f),l=v,()=>{o.removeEventListener(gf,f),l=null}},createHref(v){return t(o,v)},createURL:y,encodeLocation(v){let p=y(v);return{pathname:p.pathname,search:p.search,hash:p.hash}},push:h,replace:m,go(v){return a.go(v)}};return b}var bf;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(bf||(bf={}));function Qx(e,t,n){return n===void 0&&(n="/"),Xx(e,t,n)}function Xx(e,t,n,r){let o=typeof t=="string"?lr(t):t,s=ug(o.pathname||"/",n);if(s==null)return null;let a=lg(e);qx(a);let c=null;for(let l=0;c==null&&l<a.length;++l){let d=u1(s);c=c1(a[l],d)}return c}function lg(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let o=(s,a,c)=>{let l={relativePath:c===void 0?s.path||"":c,caseSensitive:s.caseSensitive===!0,childrenIndex:a,route:s};l.relativePath.startsWith("/")&&(ze(l.relativePath.startsWith(r),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(r.length));let d=Pn([r,l.relativePath]),u=n.concat(l);s.children&&s.children.length>0&&(ze(s.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),lg(s.children,t,u,d)),!(s.path==null&&!s.index)&&t.push({path:d,score:i1(d,s.index),routesMeta:u})};return e.forEach((s,a)=>{var c;if(s.path===""||!((c=s.path)!=null&&c.includes("?")))o(s,a);else for(let l of dg(s.path))o(s,a,l)}),t}function dg(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,o=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return o?[s,""]:[s];let a=dg(r.join("/")),c=[];return c.push(...a.map(l=>l===""?s:[s,l].join("/"))),o&&c.push(...a),c.map(l=>e.startsWith("/")&&l===""?"/":l)}function qx(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:a1(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const e1=/^:[\w-]+$/,t1=3,n1=2,r1=1,o1=10,s1=-2,vf=e=>e==="*";function i1(e,t){let n=e.split("/"),r=n.length;return n.some(vf)&&(r+=s1),t&&(r+=n1),n.filter(o=>!vf(o)).reduce((o,s)=>o+(e1.test(s)?t1:s===""?r1:o1),r)}function a1(e,t){return e.length===t.length&&e.slice(0,-1).every((r,o)=>r===t[o])?e[e.length-1]-t[t.length-1]:0}function c1(e,t,n){let{routesMeta:r}=e,o={},s="/",a=[];for(let c=0;c<r.length;++c){let l=r[c],d=c===r.length-1,u=s==="/"?t:t.slice(s.length)||"/",f=l1({path:l.relativePath,caseSensitive:l.caseSensitive,end:d},u),h=l.route;if(!f)return null;Object.assign(o,f.params),a.push({params:o,pathname:Pn([s,f.pathname]),pathnameBase:m1(Pn([s,f.pathnameBase])),route:h}),f.pathnameBase!=="/"&&(s=Pn([s,f.pathnameBase]))}return a}function l1(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=d1(e.path,e.caseSensitive,e.end),o=t.match(n);if(!o)return null;let s=o[0],a=s.replace(/(.)\/+$/,"$1"),c=o.slice(1);return{params:r.reduce((d,u,f)=>{let{paramName:h,isOptional:m}=u;if(h==="*"){let b=c[f]||"";a=s.slice(0,s.length-b.length).replace(/(.)\/+$/,"$1")}const y=c[f];return m&&!y?d[h]=void 0:d[h]=(y||"").replace(/%2F/g,"/"),d},{}),pathname:s,pathnameBase:a,pattern:e}}function d1(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Il(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],o="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,c,l)=>(r.push({paramName:c,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),o+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?o+="\\/*$":e!==""&&e!=="/"&&(o+="(?:(?=\\/|$))"),[new RegExp(o,t?void 0:"i"),r]}function u1(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Il(!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 ug(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function f1(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:o=""}=typeof e=="string"?lr(e):e;return{pathname:n?n.startsWith("/")?n:p1(n,t):t,search:g1(r),hash:_1(o)}}function p1(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(o=>{o===".."?n.length>1&&n.pop():o!=="."&&n.push(o)}),n.length>1?n.join("/"):"/"}function ya(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function h1(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Rl(e,t){let n=h1(e);return t?n.map((r,o)=>o===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function xl(e,t,n,r){r===void 0&&(r=!1);let o;typeof e=="string"?o=lr(e):(o=Go({},e),ze(!o.pathname||!o.pathname.includes("?"),ya("?","pathname","search",o)),ze(!o.pathname||!o.pathname.includes("#"),ya("#","pathname","hash",o)),ze(!o.search||!o.search.includes("#"),ya("#","search","hash",o)));let s=e===""||o.pathname==="",a=s?"/":o.pathname,c;if(a==null)c=n;else{let f=t.length-1;if(!r&&a.startsWith("..")){let h=a.split("/");for(;h[0]==="..";)h.shift(),f-=1;o.pathname=h.join("/")}c=f>=0?t[f]:"/"}let l=f1(o,c),d=a&&a!=="/"&&a.endsWith("/"),u=(s||a===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(d||u)&&(l.pathname+="/"),l}const Pn=e=>e.join("/").replace(/\/\/+/g,"/"),m1=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),g1=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,_1=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function b1(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const fg=["post","put","patch","delete"];new Set(fg);const v1=["get",...fg];new Set(v1);/**
55
+ */function Go(){return Go=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Go.apply(this,arguments)}var Cn;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Cn||(Cn={}));const _f="popstate";function uN(e){e===void 0&&(e={});function t(o,s){let{pathname:a="/",search:c="",hash:l=""}=lr(o.location.hash.substr(1));return!a.startsWith("/")&&!a.startsWith(".")&&(a="/"+a),bc("",{pathname:a,search:c,hash:l},s.state&&s.state.usr||null,s.state&&s.state.key||"default")}function n(o,s){let a=o.document.querySelector("base"),c="";if(a&&a.getAttribute("href")){let l=o.location.href,d=l.indexOf("#");c=d===-1?l:l.slice(0,d)}return c+"#"+(typeof s=="string"?s:lg(s))}function r(o,s){Il(o.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(s)+")")}return Qx(t,n,r,e)}function ze(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Il(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Jx(){return Math.random().toString(36).substr(2,8)}function bf(e,t){return{usr:e.state,key:e.key,idx:t}}function bc(e,t,n,r){return n===void 0&&(n=null),Go({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?lr(t):t,{state:n,key:t&&t.key||r||Jx()})}function lg(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function lr(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function Qx(e,t,n,r){r===void 0&&(r={});let{window:o=document.defaultView,v5Compat:s=!1}=r,a=o.history,c=Cn.Pop,l=null,d=u();d==null&&(d=0,a.replaceState(Go({},a.state,{idx:d}),""));function u(){return(a.state||{idx:null}).idx}function f(){c=Cn.Pop;let v=u(),p=v==null?null:v-d;d=v,l&&l({action:c,location:b.location,delta:p})}function h(v,p){c=Cn.Push;let A=bc(b.location,v,p);n&&n(A,v),d=u()+1;let k=bf(A,d),T=b.createHref(A);try{a.pushState(k,"",T)}catch(F){if(F instanceof DOMException&&F.name==="DataCloneError")throw F;o.location.assign(T)}s&&l&&l({action:c,location:b.location,delta:1})}function m(v,p){c=Cn.Replace;let A=bc(b.location,v,p);n&&n(A,v),d=u();let k=bf(A,d),T=b.createHref(A);a.replaceState(k,"",T),s&&l&&l({action:c,location:b.location,delta:0})}function y(v){let p=o.location.origin!=="null"?o.location.origin:o.location.href,A=typeof v=="string"?v:lg(v);return A=A.replace(/ $/,"%20"),ze(p,"No window.location.(origin|href) available to create URL for href: "+A),new URL(A,p)}let b={get action(){return c},get location(){return e(o,a)},listen(v){if(l)throw new Error("A history only accepts one active listener");return o.addEventListener(_f,f),l=v,()=>{o.removeEventListener(_f,f),l=null}},createHref(v){return t(o,v)},createURL:y,encodeLocation(v){let p=y(v);return{pathname:p.pathname,search:p.search,hash:p.hash}},push:h,replace:m,go(v){return a.go(v)}};return b}var vf;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(vf||(vf={}));function Xx(e,t,n){return n===void 0&&(n="/"),qx(e,t,n)}function qx(e,t,n,r){let o=typeof t=="string"?lr(t):t,s=fg(o.pathname||"/",n);if(s==null)return null;let a=dg(e);e1(a);let c=null;for(let l=0;c==null&&l<a.length;++l){let d=f1(s);c=l1(a[l],d)}return c}function dg(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let o=(s,a,c)=>{let l={relativePath:c===void 0?s.path||"":c,caseSensitive:s.caseSensitive===!0,childrenIndex:a,route:s};l.relativePath.startsWith("/")&&(ze(l.relativePath.startsWith(r),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(r.length));let d=Pn([r,l.relativePath]),u=n.concat(l);s.children&&s.children.length>0&&(ze(s.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),dg(s.children,t,u,d)),!(s.path==null&&!s.index)&&t.push({path:d,score:a1(d,s.index),routesMeta:u})};return e.forEach((s,a)=>{var c;if(s.path===""||!((c=s.path)!=null&&c.includes("?")))o(s,a);else for(let l of ug(s.path))o(s,a,l)}),t}function ug(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,o=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return o?[s,""]:[s];let a=ug(r.join("/")),c=[];return c.push(...a.map(l=>l===""?s:[s,l].join("/"))),o&&c.push(...a),c.map(l=>e.startsWith("/")&&l===""?"/":l)}function e1(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:c1(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const t1=/^:[\w-]+$/,n1=3,r1=2,o1=1,s1=10,i1=-2,yf=e=>e==="*";function a1(e,t){let n=e.split("/"),r=n.length;return n.some(yf)&&(r+=i1),t&&(r+=r1),n.filter(o=>!yf(o)).reduce((o,s)=>o+(t1.test(s)?n1:s===""?o1:s1),r)}function c1(e,t){return e.length===t.length&&e.slice(0,-1).every((r,o)=>r===t[o])?e[e.length-1]-t[t.length-1]:0}function l1(e,t,n){let{routesMeta:r}=e,o={},s="/",a=[];for(let c=0;c<r.length;++c){let l=r[c],d=c===r.length-1,u=s==="/"?t:t.slice(s.length)||"/",f=d1({path:l.relativePath,caseSensitive:l.caseSensitive,end:d},u),h=l.route;if(!f)return null;Object.assign(o,f.params),a.push({params:o,pathname:Pn([s,f.pathname]),pathnameBase:g1(Pn([s,f.pathnameBase])),route:h}),f.pathnameBase!=="/"&&(s=Pn([s,f.pathnameBase]))}return a}function d1(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=u1(e.path,e.caseSensitive,e.end),o=t.match(n);if(!o)return null;let s=o[0],a=s.replace(/(.)\/+$/,"$1"),c=o.slice(1);return{params:r.reduce((d,u,f)=>{let{paramName:h,isOptional:m}=u;if(h==="*"){let b=c[f]||"";a=s.slice(0,s.length-b.length).replace(/(.)\/+$/,"$1")}const y=c[f];return m&&!y?d[h]=void 0:d[h]=(y||"").replace(/%2F/g,"/"),d},{}),pathname:s,pathnameBase:a,pattern:e}}function u1(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Il(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],o="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,c,l)=>(r.push({paramName:c,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),o+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?o+="\\/*$":e!==""&&e!=="/"&&(o+="(?:(?=\\/|$))"),[new RegExp(o,t?void 0:"i"),r]}function f1(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Il(!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 fg(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function p1(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:o=""}=typeof e=="string"?lr(e):e;return{pathname:n?n.startsWith("/")?n:h1(n,t):t,search:_1(r),hash:b1(o)}}function h1(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(o=>{o===".."?n.length>1&&n.pop():o!=="."&&n.push(o)}),n.length>1?n.join("/"):"/"}function wa(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function m1(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Rl(e,t){let n=m1(e);return t?n.map((r,o)=>o===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function xl(e,t,n,r){r===void 0&&(r=!1);let o;typeof e=="string"?o=lr(e):(o=Go({},e),ze(!o.pathname||!o.pathname.includes("?"),wa("?","pathname","search",o)),ze(!o.pathname||!o.pathname.includes("#"),wa("#","pathname","hash",o)),ze(!o.search||!o.search.includes("#"),wa("#","search","hash",o)));let s=e===""||o.pathname==="",a=s?"/":o.pathname,c;if(a==null)c=n;else{let f=t.length-1;if(!r&&a.startsWith("..")){let h=a.split("/");for(;h[0]==="..";)h.shift(),f-=1;o.pathname=h.join("/")}c=f>=0?t[f]:"/"}let l=p1(o,c),d=a&&a!=="/"&&a.endsWith("/"),u=(s||a===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(d||u)&&(l.pathname+="/"),l}const Pn=e=>e.join("/").replace(/\/\/+/g,"/"),g1=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),_1=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,b1=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function v1(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const pg=["post","put","patch","delete"];new Set(pg);const y1=["get",...pg];new Set(y1);/**
56
56
  * React Router v6.30.0
57
57
  *
58
58
  * Copyright (c) Remix Software Inc.
@@ -61,5 +61,5 @@ ${e}`)}function hc(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}f
61
61
  * LICENSE.md file in the root directory of this source tree.
62
62
  *
63
63
  * @license MIT
64
- */function zo(){return zo=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},zo.apply(this,arguments)}const Tl=R.createContext(null),y1=R.createContext(null),dr=R.createContext(null),Ii=R.createContext(null),vn=R.createContext({outlet:null,matches:[],isDataRoute:!1}),pg=R.createContext(null);function dN(e,t){let{relative:n}=t===void 0?{}:t;Wr()||ze(!1);let{basename:r,navigator:o}=R.useContext(dr),{hash:s,pathname:a,search:c}=S1(e,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:Pn([r,a])),o.createHref({pathname:l,search:c,hash:s})}function Wr(){return R.useContext(Ii)!=null}function Ri(){return Wr()||ze(!1),R.useContext(Ii).location}function hg(e){R.useContext(dr).static||R.useLayoutEffect(e)}function w1(){let{isDataRoute:e}=R.useContext(vn);return e?$1():k1()}function k1(){Wr()||ze(!1);let e=R.useContext(Tl),{basename:t,future:n,navigator:r}=R.useContext(dr),{matches:o}=R.useContext(vn),{pathname:s}=Ri(),a=JSON.stringify(Rl(o,n.v7_relativeSplatPath)),c=R.useRef(!1);return hg(()=>{c.current=!0}),R.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=xl(d,JSON.parse(a),s,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:Pn([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,a,s,e])}function uN(){let{matches:e}=R.useContext(vn),t=e[e.length-1];return t?t.params:{}}function S1(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=R.useContext(dr),{matches:o}=R.useContext(vn),{pathname:s}=Ri(),a=JSON.stringify(Rl(o,r.v7_relativeSplatPath));return R.useMemo(()=>xl(e,JSON.parse(a),s,n==="path"),[e,a,s,n])}function E1(e,t){return A1(e,t)}function A1(e,t,n,r){Wr()||ze(!1);let{navigator:o,static:s}=R.useContext(dr),{matches:a}=R.useContext(vn),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=Ri(),f;if(t){var h;let p=typeof t=="string"?lr(t):t;d==="/"||(h=p.pathname)!=null&&h.startsWith(d)||ze(!1),f=p}else f=u;let m=f.pathname||"/",y=m;if(d!=="/"){let p=d.replace(/^\//,"").split("/");y="/"+m.replace(/^\//,"").split("/").slice(p.length).join("/")}let b=Qx(e,{pathname:y}),v=C1(b&&b.map(p=>Object.assign({},p,{params:Object.assign({},l,p.params),pathname:Pn([d,o.encodeLocation?o.encodeLocation(p.pathname).pathname:p.pathname]),pathnameBase:p.pathnameBase==="/"?d:Pn([d,o.encodeLocation?o.encodeLocation(p.pathnameBase).pathname:p.pathnameBase])})),a,n,r);return t&&v?R.createElement(Ii.Provider,{value:{location:zo({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:Cn.Pop}},v):v}function I1(){let e=j1(),t=b1(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,o={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return R.createElement(R.Fragment,null,R.createElement("h2",null,"Unexpected Application Error!"),R.createElement("h3",{style:{fontStyle:"italic"}},t),n?R.createElement("pre",{style:o},n):null,null)}const R1=R.createElement(I1,null);class x1 extends R.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?R.createElement(vn.Provider,{value:this.props.routeContext},R.createElement(pg.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function T1(e){let{routeContext:t,match:n,children:r}=e,o=R.useContext(Tl);return o&&o.static&&o.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(o.staticContext._deepestRenderedBoundaryId=n.route.id),R.createElement(vn.Provider,{value:t},r)}function C1(e,t,n,r){var o;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var s;if(!n)return null;if(n.errors)e=n.matches;else if((s=r)!=null&&s.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,c=(o=n)==null?void 0:o.errors;if(c!=null){let u=a.findIndex(f=>f.route.id&&c?.[f.route.id]!==void 0);u>=0||ze(!1),a=a.slice(0,Math.min(a.length,u+1))}let l=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u<a.length;u++){let f=a[u];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(d=u),f.route.id){let{loaderData:h,errors:m}=n,y=f.route.loader&&h[f.route.id]===void 0&&(!m||m[f.route.id]===void 0);if(f.route.lazy||y){l=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}return a.reduceRight((u,f,h)=>{let m,y=!1,b=null,v=null;n&&(m=c&&f.route.id?c[f.route.id]:void 0,b=f.route.errorElement||R1,l&&(d<0&&h===0?(N1("route-fallback"),y=!0,v=null):d===h&&(y=!0,v=f.route.hydrateFallbackElement||null)));let p=t.concat(a.slice(0,h+1)),A=()=>{let k;return m?k=b:y?k=v:f.route.Component?k=R.createElement(f.route.Component,null):f.route.element?k=f.route.element:k=u,R.createElement(T1,{match:f,routeContext:{outlet:u,matches:p,isDataRoute:n!=null},children:k})};return n&&(f.route.ErrorBoundary||f.route.errorElement||h===0)?R.createElement(x1,{location:n.location,revalidation:n.revalidation,component:b,error:m,children:A(),routeContext:{outlet:null,matches:p,isDataRoute:!0}}):A()},null)}var mg=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(mg||{}),gg=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}(gg||{});function O1(e){let t=R.useContext(Tl);return t||ze(!1),t}function P1(e){let t=R.useContext(y1);return t||ze(!1),t}function M1(e){let t=R.useContext(vn);return t||ze(!1),t}function _g(e){let t=M1(),n=t.matches[t.matches.length-1];return n.route.id||ze(!1),n.route.id}function j1(){var e;let t=R.useContext(pg),n=P1(),r=_g();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function $1(){let{router:e}=O1(mg.UseNavigateStable),t=_g(gg.UseNavigateStable),n=R.useRef(!1);return hg(()=>{n.current=!0}),R.useCallback(function(o,s){s===void 0&&(s={}),n.current&&(typeof o=="number"?e.navigate(o):e.navigate(o,zo({fromRouteId:t},s)))},[e,t])}const yf={};function N1(e,t,n){yf[e]||(yf[e]=!0)}function fN(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function pN(e){let{to:t,replace:n,state:r,relative:o}=e;Wr()||ze(!1);let{future:s,static:a}=R.useContext(dr),{matches:c}=R.useContext(vn),{pathname:l}=Ri(),d=w1(),u=xl(t,Rl(c,s.v7_relativeSplatPath),l,o==="path"),f=JSON.stringify(u);return R.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:o}),[d,f,o,n,r]),null}function D1(e){ze(!1)}function hN(e){let{basename:t="/",children:n=null,location:r,navigationType:o=Cn.Pop,navigator:s,static:a=!1,future:c}=e;Wr()&&ze(!1);let l=t.replace(/^\/*/,"/"),d=R.useMemo(()=>({basename:l,navigator:s,static:a,future:zo({v7_relativeSplatPath:!1},c)}),[l,c,s,a]);typeof r=="string"&&(r=lr(r));let{pathname:u="/",search:f="",hash:h="",state:m=null,key:y="default"}=r,b=R.useMemo(()=>{let v=ug(u,l);return v==null?null:{location:{pathname:v,search:f,hash:h,state:m,key:y},navigationType:o}},[l,u,f,h,m,y,o]);return b==null?null:R.createElement(dr.Provider,{value:d},R.createElement(Ii.Provider,{children:n,value:b}))}function mN(e){let{children:t,location:n}=e;return E1(bc(t),n)}new Promise(()=>{});function bc(e,t){t===void 0&&(t=[]);let n=[];return R.Children.forEach(e,(r,o)=>{if(!R.isValidElement(r))return;let s=[...t,o];if(r.type===R.Fragment){n.push.apply(n,bc(r.props.children,s));return}r.type!==D1&&ze(!1),!r.props.index||!r.props.children||ze(!1);let a={id:r.props.id||s.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=bc(r.props.children,s)),n.push(a)}),n}const xi=260,Cl=220,Ol=320,bg=56,Pl=480,gN=8,Ml=44,jl=400,vg=1200;function $l(e){return Math.max(0,Math.min(vg,e-Pl))}function vc(e){return $l(e)>=jl?"docked":"overlay"}const L1=48,F1=16;function _N(e,t){if(vc(e)==="docked")return{mode:"docked",width:Math.min(t,$l(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,jl),e-L1));return e-n>=F1?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function bN({capacity:e,min:t,max:n,drawn:r}){const o=e>=t;return o?{resizable:o,value:Math.min(Math.max(r,t),e),minWidth:t,maxWidth:Math.min(n,e)}:{resizable:o,value:r,minWidth:r,maxWidth:r}}function U1(e,t=xi,n=Ml){return vc(e-yg(t)-n)==="overlay"&&vc(e-bg-n)==="docked"}function yg(e){return Number.isNaN(e)?xi:Math.min(Ol,Math.max(Cl,e))}function B1(e,t=Ml){return Math.max(0,Math.min(Ol,e-Pl-t))}function vN(e,t,n=xi,r=!1,o=Ml){const s=!t&&r&&U1(e,n,o),a=t||s,c=B1(e,o);return{mode:a?"strip":"docked",width:a?bg:Math.min(yg(n),c),collapsed:a,resizable:!a&&c>=Cl}}function yN(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const wN=e=>e?"⌘B":"Ctrl+B",H1="data-canvas-shortcuts",W1=`[${H1}]`,G1=e=>wg(e,W1),z1='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',kN=e=>wg(e,z1);function wg(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const SN=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&G1(e.target)?"new-file":null},kg="small",K1=["small","medium","large"],Sg="before:absolute before:-inset-0.5 before:content-['']",V1={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:Sg},medium:{px:28,className:"size-7",glyphClassName:"size-3.5",hitClassName:""},large:{px:36,className:"size-9",glyphClassName:"size-4",hitClassName:""}},Z1={small:{px:4,className:"mb-1"},medium:{px:6,className:"mb-1.5"},large:{px:8,className:"mb-2"}},EN={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:Sg,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 AN(e){for(const t of K1)if(e===t)return t;return kg}function IN(e){return V1[e].px+Z1[e].px}const Eg="delegating",Ss=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,wa=e=>Math.max(1,Math.floor(e)),Y1=e=>e===Eg,Ag=e=>e.locality==="remote"&&e.link_down===!0||e.peer_reach==="not-attempted"||e.peer_reach==="unknown";function Nl(e){return Ag(e)?!1:typeof e.background_work=="boolean"?e.background_work:e.status?.code===Eg}const J1=Intl.ListFormat;let ka=null;const Q1=e=>{const t=nn();return ka?.tag!==t&&(ka={tag:t,format:new J1(t,{type:"conjunction",style:"narrow"})}),ka.format.format(e)};function RN(e){if(Ag(e))return"";const t=Nl(e);if(!t&&typeof e.background_work=="boolean")return"";const n=!Y1(e.status?.code),r=[];n&&Ss(e.subagents_running)&&r.push(_("ui.chat.sidebar.row.bg.subagents",{count:wa(e.subagents_running)})),t&&Ss(e.jobs_running)&&r.push(_("ui.chat.sidebar.row.bg.jobs",{count:wa(e.jobs_running)}));const o=[];if(r.length>0&&o.push(_("ui.chat.sidebar.row.bg.running",{items:Q1(r)})),n&&Ss(e.subagents_queued)){const s=wa(e.subagents_queued);o.push(r.length>0?_("ui.chat.sidebar.row.bg.queued",{count:s}):_("ui.chat.sidebar.row.bg.subagents_queued",{count:s}))}return t&&o.length===0&&e.status?.code!=="waiting"&&Ss(e.waiting_on)&&o.push(_("ui.chat.sidebar.row.bg.waiting")),o.join(" · ")}const X1=new Set(["idle","recent"]);function xN(e,t){return t!==""&&X1.has(e.status?.code??"recent")&&Nl(e)}const q1=["active","created"],TN={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"},eT=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function Ti(e){return eT.has(e.status?.code??"")||Nl(e)}const tT=new Set(["approval","answer"]);function Ig(e){return tT.has(e.status?.code??"")}const nT=24*60*60*1e3,rT=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function Dl(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 oT="last_user_at";function sT(e){const t=e[oT],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 iT(e,t,n){if(Ti(e))return"running";const r=Dl(e,n);if(r===null)return"older";const o=rT(t);return r>=o?"today":r>=o-6*nT?"week":"older"}function CN(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const o of e)r[iT(o,t,n)].push(o);return r}function Rg(e,t,n){const r=Dl(e,n);if(r===null)return null;const o=Math.floor(Math.max(0,t-r)/6e4);if(o<1)return{unit:"now",count:0};if(o<60)return{unit:"minute",count:o};const s=Math.floor(o/60);if(s<24)return{unit:"hour",count:s};const a=Math.floor(s/24);return a<7?{unit:"day",count:a}:a<365?{unit:"week",count:Math.floor(a/7)}:{unit:"year",count:Math.floor(a/365)}}function ON(e,t,n){const r=Rg(e,t,n);return r?_("ui.chat.sidebar_view.relative_short",r):""}function PN(e,t,n){const r=Rg(e,t,n);return r?n==="created"?_("ui.chat.sidebar_view.relative_created",r):_("ui.chat.sidebar_view.relative_active",r):""}const yc=["pinned","running","today","week","older","agents","teams"],MN={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 jN(e){return e==="agents"||e==="teams"}const Ko=8;function aT(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function $N(e,t){return{...e,[t]:(e[t]??Ko)+Ko}}function NN(e,t,n,r,o){const s=!(e[n]??r);return{expanded:{...e,[n]:s},caps:!s&&!o?aT(t,n):t}}function xg(e){return`tag:${e}`}function Tg(e,t){return e[xg(t)]===!1}function DN(e,t){const n=xg(t);if(Tg(e,t)){const{[n]:r,...o}=e;return o}return{...e,[n]:!1}}function LN(e,t,n){return Tg(t,n)?[]:e}function FN(e,t,n,r){return(e||t!=="")&&(r>Ko||n.trim()!=="")}const UN="Collapse, then reopen, to restore the compact list";function BN(e){return(e??Ko)>Ko}const HN=e=>`section-grown-hint-${e}`,WN=e=>_("ui.chat.sidebar.catalogue.show_more",{hidden:e});function GN(e,t){return t==="agents"?_("ui.chat.sidebar.catalogue.show_more_agents",{count:e}):_("ui.chat.sidebar.catalogue.show_more_teams",{count:e})}function zN(e,t){return e.groupBy==="tag"&&!t?"section":e.groupBy}function KN(e){return e.tagsEnabled||e.groupBy==="tag"}const wr={hidden:[],order:[...yc],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},cT=10,no=[25,50],lT=50,dT=500,uT=64,fT=2;function VN(e){return e.groupBy==="tag"?Math.max(e.loads,fT):e.loads}function jr(e){const t=Math.max(0,Math.floor(e));return t===0?cT:t<=no.length?no[t-1]:no[no.length-1]+(t-no.length)*lT}function ZN(e,t){const n=jr(e+1)-jr(e),r=Math.max(0,Math.min(n,t));return _("ui.chat.sidebar.catalogue.show_more_chats",{add:r})}function YN(e,t,n){const r=jr(t+1)-jr(t),o=jr(t),s=Math.min(o+r,e.length);let a=0;for(let l=o;l<s;l+=1)Ci(e[l])&&(a+=1);const c=Math.max(0,s-o-a);return c>0?c:Math.max(0,Math.min(r,n))}function JN(e,t){if(!t)return null;const n=e.filter(r=>Ci(r));return n.length===0?null:{row:n.find(r=>Ig(r))??n[0],count:n.length}}function Ci(e){return Ti(e)}function pT(e){return Ig(e)?0:Ti(e)?1:2}function hT(e,t){return Ti(e)?sT(e):Dl(e,t)}function mT(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function QN(e,t,n){const r=e.map((o,s)=>({row:o,index:s,lane:t==="active-first"?pT(o):0,at:hT(o,n)}));return r.sort((o,s)=>o.lane-s.lane||mT(o.at,s.at)||o.index-s.index),r.map(o=>o.row)}function XN(e,t){const{limit:n,currentId:r,searching:o=!1}=t;if(o)return{rows:[...e],lifted:!1,remaining:0};const s=[];let a=Math.max(0,n);for(const d of e){if(a>0){s.push(d),a-=1;continue}Ci(d)&&s.push(d)}const c=Math.max(0,e.length-s.length);if(!r)return{rows:s,lifted:!1,remaining:c};const l=e.find(d=>d.session_id===r)??null;return l===null||s.includes(l)?{rows:s,lifted:!1,remaining:c}:{rows:[l,...s],lifted:!0,remaining:c}}function qN(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=jr(t.loads),r=[];let o=n;for(const l of e){if(Ci(l)){r.push(l);continue}o>0&&(r.push(l),o-=1)}const s=t.currentId,a=s==null?null:e.find(l=>l.session_id===s)??null,c=a!==null&&!r.includes(a);return{rows:c&&a!==null?[a,...r]:r,lifted:c,hidden:e.length-r.length-(c?1:0),held:e.length}}function eD(e){if(e.add<=0)return null;const t=_("ui.chat.sidebar.catalogue.show_more_chats",{add:e.add});if(e.drawn>=e.total)return{label:t,aria:t};const n=`${e.drawn} of ${e.total}`;return{label:`${t} · ${n}`,aria:`${t} · ${n}`}}const gT="mt-4",_T="mt-2";function tD(e){return e?gT:_T}function nD(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function rD(e,t){if(t==="section"||t==="tag")return null;if(t==="flat")return[{key:"all",label:"",rows:[...e]}];const n=new Map;for(const s of e){const a=s.binding?.team||s.binding?.agent||"",c=a||"ungrouped",l=n.get(c)??{key:c,label:a||_("ui.chat.sidebar_view.ungrouped"),rows:[]};l.rows.push(s),n.set(c,l)}const r=[...n.values()],o=r.findIndex(s=>s.key==="ungrouped");return o>0&&r.push(...r.splice(o,1)),r}function bT(e,t){return!e.hidden.includes(t)}function Cg(e){return e.order.filter(t=>bT(e,t))}function oD(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function sD(e,t,n){const r=Cg(e),o=r.indexOf(t),s=r[o+n];if(o<0||s===void 0)return e;const a=e.order.indexOf(t),c=e.order.indexOf(s),l=[...e.order];return l[a]=s,l[c]=t,{...e,order:l}}const vT=["running","today","week","older"];function wf(e){return vT.includes(e)}function iD(e,t,n,r){if(!wf(t)||r&&!r(t))return!1;const o=Cg(e),s=o.indexOf(t);if(s<0)return!1;const a=o[s+n];return a===void 0||!wf(a)?!1:r?r(a):!0}const yT=["section","tag","agent","flat"],wT=["active-first","recent"];function aD(e){if(typeof e!="object"||e===null)return wr;const t=e,n=new Set(yc),r=[];if(Array.isArray(t.order))for(const h of t.order)typeof h=="string"&&n.has(h)&&(r.includes(h)||r.push(h));for(const h of yc)r.includes(h)||r.push(h);const o=[];if(Array.isArray(t.hidden))for(const h of t.hidden)typeof h=="string"&&n.has(h)&&(o.includes(h)||o.push(h));const s=yT.includes(t.groupBy)?t.groupBy:wr.groupBy,a=q1.includes(t.basis)?t.basis:wr.basis,c=wT.includes(t.orderBy)?t.orderBy:wr.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(dT,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>=uT)break;d.push(h)}}const u=[],f=new Set;if(Array.isArray(t.pins))for(const h of t.pins)typeof h=="string"&&h.length!==0&&(f.has(h)||(f.add(h),u.push(h)));return{hidden:o,order:r,groupBy:s,tagsEnabled:typeof t.tagsEnabled=="boolean"?t.tagsEnabled:!1,autoTagForks:typeof t.autoTagForks=="boolean"?t.autoTagForks:wr.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const Og={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},kT=["recent","name","kind","modified","created","size"],ST=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function Ll(e){const t=e&&typeof e=="object"?e:{};return{sort:kT.includes(t.sort??"")?t.sort:Og.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=>[Vo,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>ST.includes(n)))]:[]}}const Vo="Attachments";function cD(e,t){const n=r=>{switch(t.sort){case"name":return r.row.name;case"kind":return`${r.row.kind}\0${r.row.name}`;case"modified":return r.modified;case"created":return r.created;case"size":return r.row.document.sizeBytes??null;default:return r.mentioned}};return[...e].sort((r,o)=>{const s=n(r),a=n(o);if(s===null||a===null)return s===a?0:s===null?1:-1;const c=typeof s=="string"&&typeof a=="string"?s.localeCompare(a,void 0,{numeric:!0}):Number(s)-Number(a);return(t.order==="asc"?c:-c)||r.mentioned-o.mentioned})}const ET=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 lD(e,t,n,r,o=[]){const s=e.filter(l=>l.highlighted),a=e.filter(l=>!l.highlighted),c=[];if(o.length&&c.push({id:Vo,label:_("ui.canvas.files.attachments"),items:o,open:n||!r.has(Vo),highlights:!1}),s.length&&c.push({id:"Highlights",label:_("ui.canvas.finder_layout.highlights"),items:s,open:n||!r.has("Highlights"),highlights:!0}),s.length&&a.length&&(c.push({id:"Working files",label:_("ui.canvas.finder_layout.working_files"),items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return c;if(!t.group)a.length&&c.push({id:"Files",label:_("ui.canvas.finder_layout.files"),items:a,open:!0,highlights:!1});else for(const l of["Images","Videos","Sounds","Documents","Spreadsheets","Other"]){const d=a.filter(u=>ET(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const AT=32,dD=4,Pg=32,Mg=18;function uD(e){return e.height-Pg-(e.kind==="tiles"&&e.section.id===Vo?Mg:0)}function fD(e,t,n){const r=[],o=new Map,s=Math.max(136,t-16),a=Math.max(1,Math.floor((s+4)/140));let c=0;const l=(d,u,f,h,m=1)=>{h.forEach((y,b)=>o.set(y.row.document.id,{band:r.length,column:b})),r.push({section:d,kind:u,height:f,top:c,items:h,cols:m}),c+=f};for(const d of e)if(l(d,"header",AT,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(d.id===Vo){const u=d.items.filter(y=>y.row.media!=="image"),f=d.items.filter(y=>y.row.media==="image");for(const y of u)l(d,"compact",36,[y]);const h=(s-4*(a-1))/a,m=Math.round((h-8)*3/4)+Pg+Mg;for(let y=0;y<f.length;y+=a)l(d,"tiles",m,f.slice(y,y+a),a)}else if(n&&d.id==="Images"){const u=(s-4*(a-1))/a,f=Math.round((u-8)*3/4)+32;for(let h=0;h<d.items.length;h+=a)l(d,"tiles",f,d.items.slice(h,h+a),a)}else if(n&&d.id==="Videos")for(const u of d.items)l(d,"video",Math.min(Math.round((s-8)*9/16),280)+32,[u]);else if(n&&d.id==="Sounds")for(const u of d.items)l(d,"audio",80,[u]);else for(const u of d.items)l(d,"compact",36,[u]);return{bands:r,height:c,columns:a,positions:o}}function pD(e,t,n,r){const o=Math.max(600,n*.75);let s=0,a=e.bands.length;for(;s<a;){const d=s+a>>>1,u=e.bands[d];u.top+u.height<t-o?s=d+1:a=d}const c=new Set;for(let d=s;d<e.bands.length&&e.bands[d].top<=t+n+o;d++)c.add(d);const l=r?e.positions.get(r):null;return l&&c.add(l.band),[...c].sort((d,u)=>d-u)}function hD(e,t,n,r){const o=e.positions.get(t);if(!o)return null;const s=e.bands[o.band],a=e.bands.filter(u=>u.section.id===s.section.id&&u.items.length);if(n==="Home")return a[0]?.items[0]?.row.document.id??null;if(n==="End")return a.at(-1)?.items.at(-1)?.row.document.id??null;if(n==="ArrowLeft"||n==="ArrowRight")return s.items[o.column+(n==="ArrowLeft"?-1:1)]?.row.document.id??null;const c=n==="ArrowUp"||n==="PageUp"?-1:1,l=s.top+(n.startsWith("Page")?r*c:c);let d=o.band+c;for(;d>=0&&d<e.bands.length;d+=c){const u=e.bands[d];if(u.items.length&&!(n.startsWith("Page")&&(c>0?u.top<l:u.top>l)))return u.items[Math.min(o.column,u.items.length-1)].row.document.id}if(n.startsWith("Page")){const u=e.bands.filter(h=>h.items.length),f=c<0?u[0]:u.at(-1);return f?.items[c<0?0:f.items.length-1]?.row.document.id??null}return null}const IT="both",jg="by-turn",RT=[{value:"by-turn"},{value:"by-response"}];function mD(e){for(const t of RT)if(e===t.value)return t.value;return jg}function gD(e){return e==="by-response"?_("ui.settings.appearance.transcript_display_mode_setting.by_response"):_("ui.settings.appearance.transcript_display_mode_setting.by_turn")}const _D="primary+alt+shift+space",xT=/^f([1-9]|1[0-9]|2[0-4])$/;function TT(e){return xT.test(e)}function CT(e,t){const n=OT(e,t);return t==="mac"?n.join(""):n.join("+")}function OT(e,t){const r=t==="mac"?{primary:"⌘",meta:"⌘",ctrl:"⌃",alt:"⌥",shift:"⇧"}:{primary:"Ctrl",meta:t==="win"?"Win":"Super",ctrl:"Ctrl",alt:"Alt",shift:"Shift"},o={space:"Space",backspace:"Backspace",delete:"Delete",insert:"Insert",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown",up:"Up",down:"Down",left:"Left",right:"Right"};return e.split("+").map(s=>s.trim().toLowerCase()).filter(s=>s.length>0).map(s=>s in r?r[s]:s in o?o[s]:TT(s)||s.length===1?s.toUpperCase():s)}const Oi=[{id:"panel.console",get label(){return _("ui.settings.shortcuts.action.open_console")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return _("ui.settings.shortcuts.action.open_canvas")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return _("ui.settings.shortcuts.action.open_run_details")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return _("ui.settings.shortcuts.action.open_asks")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return _("ui.settings.shortcuts.action.open_browser")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return _("ui.settings.shortcuts.action.open_code_review")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],PT=new Map(Oi.map(e=>[e.id,e])),MT=e=>PT.get(e),jT=new Set(["primary+0","primary+r","primary+shift+r","primary+t","primary+shift+t","primary+l",...[1,2,3,4,5,6,7,8,9].map(e=>`primary+${e}`)]);class $T extends Map{copy;constructor(t){super(),this.copy=new Map(t)}get(t){return this.copy.get(t)?.()}has(t){return this.copy.has(t)}get size(){return this.copy.size}*entries(){for(const[t,n]of this.copy)yield[t,n()]}*keys(){yield*this.copy.keys()}*values(){for(const t of this.copy.values())yield t()}forEach(t,n){for(const[r,o]of this)t.call(n,o,r,this)}[Symbol.iterator](){return this.entries()}}const Fl=new $T([["primary+p",()=>_("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>_("ui.settings.shortcuts.reserved.palette_commands")],["primary+k",()=>_("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>_("ui.settings.shortcuts.reserved.new_chat")],["primary+b",()=>_("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>_("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>_("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>_("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>_("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>_("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>_("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>_("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>_("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>_("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>_("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>_("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>_("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>_("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>_("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>_("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>_("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>_("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>_("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>_("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>_("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>_("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>_("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>_("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>_("ui.settings.shortcuts.reserved.browser_last_tab"):()=>_("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>_("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>_("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>_("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>_("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>_("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>_("ui.settings.shortcuts.reserved.close")],["primary+m",()=>_("ui.settings.shortcuts.reserved.minimise")]]),NT=["primary","alt","shift"],DT={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},LT=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),FT=e=>LT.has(e)||/^[a-z0-9]$/.test(e);function Ul(e){if(typeof e!="string")return null;const t=e.toLowerCase().split("+").map(s=>s.trim()).filter(s=>s.length>0);if(t.length===0)return null;const n=t[t.length-1];if(!FT(n))return null;const r=new Set;for(const s of t.slice(0,-1)){const a=DT[s];if(a===void 0)return null;r.add(a)}return[...NT.filter(s=>r.has(s)),n].join("+")}const $g=e=>e.split("+").includes("primary");function Pi(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!Fl.has(n)?n:MT(e)?.defaultChord??null}function bD(e){const t=new Map;for(const n of Oi){const r=Pi(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const UT=e=>e==="mac"?_("ui.settings.shortcuts.capture.needs_modifier_mac"):_("ui.settings.shortcuts.capture.needs_modifier");function BT(e,t,n,r="linux",o=new Map){const s=e===null?null:Ul(e);if(s===null)return _("ui.settings.shortcuts.capture.unbindable");if(!$g(s))return UT(r);const a=Fl.get(s);if(a!==void 0)return a;const c=o.get(s);if(c!==void 0)return _("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of Oi)if(l.id!==t&&Pi(l.id,n)===s)return _("ui.settings.shortcuts.capture.already_assigned",{label:l.label});return null}function HT(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const o of Oi){const s=t[o.id];if(s===null){r[o.id]=null;continue}const a=typeof s=="string"?Ul(s):null,c=a!==null&&jT.has(a),l=a!==null&&$g(a)&&(c||!Fl.has(a)&&!n.has(a))?a:null;l!==null&&(r[o.id]=l);const d=Pi(o.id,r);d!==null&&n.add(d)}return r}function vD(e,t,n){const r=Pi(e,t);return r===null?null:Ng(r,n)}function Ng(e,t){return CT(e,t)}function yD(e,t){const n=e.split("+"),r=n[n.length-1],o=n.slice(0,-1).map(s=>s==="primary"?t==="mac"?"Meta":"Control":s==="shift"?"Shift":s==="alt"?"Alt":s);return{glyph:Ng(e,t),aria:[...o,r.length===1?r.toUpperCase():r].join("+")}}const kf=e=>{for(const t of[e.role,...e.variants])if(!l_.includes(t))throw new Error(`Unknown accent role: ${t}`);return Object.freeze({...e,variants:Object.freeze(e.variants)})},Dg=Object.freeze([kf({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"}),kf({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"})]),wD=e=>Dg.some(t=>t.role===e||t.variants.includes(e)),Me={strongText:7,text:4.5,nonText:3},Sf=new Set(["inkDisabled"]),Ge=["canvas","surface","elevated","sunken"],Lg=[["ink",Me.strongText],["inkMuted",5.5],["inkDim",5]],fn=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Vt={dark:{canvasMin:9,canvasMax:15,elevatedMax:22},light:{canvasMax:94,sunkenMin:80}},Rn={canvasSurface:[2.5,5],surfaceElevated:[2,6],canvasSunken:[1.5,6]},WT=2,GT=1.03,Bl=8,ai=2,Ef=.8,Af=3,If=2,Rf=4,wc=2.5,xf=4,Tf=2.5,Cf=2,Of=2,zT=[{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:Ge,fill:"accent",border:"accent",ink:"onAccent"},{name:"primary button (hover)",on:Ge,fill:"accentHover",border:"accentHover",ink:"onAccent"},{name:"primary button (pressed)",on:Ge,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:Ge,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:Ge,fill:"accentWash",border:null,ink:"inkMuted",edge:!1},{name:"input field",on:Ge,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:Ge,fill:"surface",border:"borderControl",ink:"ink"},{name:"browser file-transfer row (refused)",on:Ge,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:Ge,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}],KT=[{name:"context wheel arc against its track",a:["info","warning","danger"],b:"sunken",floor:Me.nonText}],VT=[{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:Ge,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"}],ZT=[{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}],YT=["borderControl","accent","successBorder","warningBorder","dangerBorder","infoBorder"],JT=["accent","success","warning","danger","info"],QT=[{fg:"surface",on:"accent",floor:Me.text,name:"the console terminal's cursor ink on its own cursor (9.1)"}],XT=[],qT=[{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"}],kr=15,Sr=8,eC=[{theme:"catppuccinMocha",a:"accentAlt",b:"info",floor:kr,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:kr,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:kr,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:kr,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:kr,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:Sr,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:Sr,got:0,why:"`info` IS `accent` (`#00EFFF`), the palette's single cyan"},{theme:"obsidian",a:"info",b:"accent",floor:Sr,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:Sr,got:0,why:"`info` IS `accent` (`#91B7E9`), the palette's single steel blue"},{theme:"githubLight",a:"info",b:"accent",floor:Sr,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"}],tC=[],nC=[],rC=["mode",...Ge,"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"],Es=["success","warning","danger","info"],oC=["success","warning","danger","info","ink"],Rr=8,ro="tokenCommand",As=Rr,sC=["surface","elevated","messageSurface"],iC=[{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."}],cn=15,Zo=15,wo=Rr,at=2,Pf=4,aC=.75,Mf=.12,jf=.1,cC=[["surface","canvas"],["surface","elevated"],["elevated","canvas"]],lC=4,dC=2,uC=2,Sa=1,ci=2,Ea=2,$f=.5,fC=1.5,pC=1.5,Fg=5,li=2.5,Ug=.5,di=5,kc=4,Sc=24,Nf=12,hC=.45,Df=.75,mC=.25,pn=2,Bg=2,gC=[{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"}],_C=[{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"}],Ec=10,Is="surface",Lf=2,Ff=1.15,bC=({composed:e=!1,capturePairs:t=!1}={})=>{const n={assertions:0,failures:0,composed:e},r=[],o=(I,g)=>e?g>=I-.01:Math.abs(I-g)<.01,s=(I,g,w)=>e?g>=I-w:Math.abs(I-g)<=w,a=new Set,c=(I,g,w,S)=>{const x=qT.find(F=>F.theme===I&&F.role===g&&F.ground===w&&o(F.got,S));return x&&a.add(x),x},l=new Set,d=(I,g,w,S)=>{const x=eC.find(F=>F.theme===I&&F.a===g&&F.b===w&&o(F.got,S));return x&&l.add(x),x},u=new Set,f=new Set,h=new Set,m=(I,g,w)=>`${I} on ${g} in ${w}`,y=[],b=I=>{n.failures++,y.push(`FAIL ${I}`)},v=new Set,p=(I,g,w,S)=>{const x=XT.find(F=>F.theme===I&&F.fg===g&&F.bg===w&&o(F.got,S));return x&&v.add(x),x};return Object.assign(n,{readings:r,pinMatches:o,ledgerHolds:s,log:y,fail:b,exceptionSeen:v,perceptibleSeen:a,pairPinSeen:l,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:h,controlEdgeKey:m,pinClaims:new Set,findException:p,findPerceptibleException:c,findPairPin:d,assertPair:(I,g,w,S,x,F)=>{const j=g[w],X=g[S];if(!W(j)||!W(X))return;n.assertions++;const T=oe(j,X);if(t&&r.push({foreground:w,background:S,value:T,floor:x}),T>=x)return;const V=D(T);p(I,w,S,V)||b(`${I}: ${F} — ${w} ${j} on ${S} ${X} = ${V}:1, need ${x}:1`)},assertIdentityPair:(I,g,w,S,x,F)=>{const j=g[w],X=g[S];if(!W(j)||!W(X))return;n.assertions++;const T=D(ue(j,X));if(T>=x)return;const V=d(I,w,S,T);if(V){V.floor!==x&&b(`${I}: \`${w}\`/\`${S}\` is pinned at floor ${V.floor} but this assertion asks for ${x} — a pin records the bound it was granted under, so the pin and the floor have to be raised together`);return}b(`${I}: ${F} — \`${w}\` ${j} and \`${S}\` ${X} are ΔE00 ${T} apart (need ${x}) — two roles a reader has to tell apart at this site cannot be one colour at two weights; move the palette value, or pin the palette in \`PAIR_PINS\` with the constraint that refuses it`)},floorUnreachablePin:(I,g)=>gC.find(S=>S.id===I&&S.role===g)??null,shortfallPin:(I,g,w)=>_C.find(x=>x.id===I&&x.role===g&&x.bound===w)??null}),n},vC=(e,t)=>{const{fail:n,assertPair:r,assertIdentityPair:o,findException:s,findPerceptibleException:a,floorUnreachablePin:c,shortfallPin:l,pinClaims:d,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:h,controlEdgeKey:m,pinMatches:y,ledgerHolds:b}=e;for(const{id:v,palette:p}of[t]){for(const g of rC)e.assertions++,g in p||n(`${v}: missing required role \`${g}\``);for(const[g,w]of Lg)if(!Sf.has(g))for(const S of fn)r(v,p,g,S,w,"body ink");for(let g=0;g<Ge.length;g++)for(let w=g+1;w<Ge.length;w++){const S=p[Ge[g]],x=p[Ge[w]];!W(S)||!W(x)||(e.assertions++,oe(S,x)<1.03&&n(`${v}: grounds \`${Ge[g]}\` ${S} and \`${Ge[w]}\` ${x} are indistinguishable (${D(oe(S,x))}:1) — elevation is a lightness step here, so they must differ`))}const A=[{role:"rowHover",castFloor:g=>Math.max(li,Ug*g),castCeiling:g=>Math.max(g,li),stepFloor:fC,stepCeiling:null},{role:"rowSelected",castFloor:g=>Math.max(di,g),castCeiling:g=>Math.min(Math.max(g+kc,di),Sc),stepFloor:pC,stepCeiling:Fg}];for(const g of A){const w=g.role,S=p[w];if(!W(S))continue;const[x,F,j]=ae(S),[X,T,V]=ae(p.surface),[,Z,ge]=ae(p.accent),z=Math.hypot(Z,ge),me=Math.hypot(T,V),se=Math.hypot(F,j),je=g.castFloor(me),De=g.castCeiling(me),Ke=me<pn;e.assertions++;const tt=me>=pn?{name:"the panel's",hue:Math.atan2(V,T)}:z>=Bg?{name:"`accent`'s",hue:Math.atan2(ge,Z)}:{name:"the panel's",hue:Math.atan2(V,T)},_e=Math.atan2(j,F),Ce=Math.abs(((_e-tt.hue)*180/Math.PI+540)%360-180);se>=pn&&Ce>Nf&&n(`${v}: \`${w}\` ${S} sits ${D(Ce)} degrees off ${tt.name} hue (the limit is ${Nf}) — 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 ${tt.name} and re-author the value at it`),e.assertions++,je>De+1e-9?(d.add(`${v}:${w}:floor`),e.assertions++,c(v,w)||n(`${v}: \`${w}\` ${S} carries C* ${D(se)}, and its cast floor ${D(je)} is ABOVE its ceiling ${D(De)} — the panel's own cast is louder than this role is allowed to be, so the value has to sit at the ceiling and \`${v}\`'s \`${w}\` has to be in ROW_STATE_FLOOR_UNREACHABLE naming the constraint that refuses the floor (the flat cap, the rise, or the role's absolute term)`),e.assertions++,se<De-Df&&n(`${v}: \`${w}\` ${S} carries C* ${D(se)} where its cast floor ${D(je)} is above its ceiling ${D(De)} — the floor cannot be held, but the CEILING is reachable and is what the ledger row promises this value sits at`)):se<je-hC&&n(`${v}: \`${w}\` ${S} carries C* ${D(se)}, under the cast floor ${D(je)} — a row state has to carry the cast of the panel it sits on, and a fill quieter than its own backdrop reads as a grey wash of that backdrop. This is the defect that was reachable because the two \`ROW_*_CHROMA_FLOOR\` constants were declared and asserted NOWHERE, and the measurement that found it was a hover at C* 4.79 on a panel of 13.44. Author the value at the panel's own hue, at the cast the rule names and the step the inks allow`),e.assertions++,se>De+Df&&n(`${v}: \`${w}\` ${S} carries C* ${D(se)}, past the ${D(De)} this file allows — ${w==="rowHover"?"the hover may be lighter than its ground, it may not be a MORE coloured plane than it":`the selection may carry the panel's cast and the rule's rise of ${kc} above it, and no more`}, and the flat cap is ${Sc}. Search the chroma back toward the panel and let the step and the pair's cast rank carry what the fill no longer can`),e.assertions++;const Rt=x-X,Le=p.mode==="dark"?Rt:-Rt;if(Le<g.stepFloor-1e-9&&n(`${v}: \`${w}\` ${S} sits ${D(Math.abs(Rt))} \`L*\` ${p.mode==="dark"?"above":"below"} \`surface\` ${p.surface}, so the step is ${p.mode==="dark"?"LIGHTER":"DARKER"}-by-${D(Le)} where the floor is ${g.stepFloor} \`L*\` in the mode's raised direction — ΔE00 is a budget a chroma-only step can spend while moving the wrong way in lightness, and the three palettes that did exactly that were the same report answered twice`),g.stepCeiling!==null&&(e.assertions++,Le>g.stepCeiling+mC+1e-9&&n(`${v}: \`${w}\` ${S} sits ${D(Le)} \`L*\` from \`surface\`, past the ${g.stepCeiling} \`L*\` ceiling — every L* the row rises is ink headroom spent on the caps drawn inside it, so the step is taken as far as the inks allow and no further`)),w==="rowSelected"&&W(p.rowHover)){const[Ae,ft,_t]=ae(p.rowHover),jt=p.mode==="dark"?Ae-X:X-Ae,Gr=Math.hypot(ft,_t);if(e.assertions++,Le<jt+Sa-1e-9){const ur=l(v,"rowSelected","rank");d.add(`${v}:rowSelected:rank`),e.assertions++,ur?b(ur.measured,Le-jt,.05)||n(`${v}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${ur.measured} and the pair now ranks ${D(Le-jt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${v}: \`rowSelected\` ${S} is ${D(Le)} \`L*\` from \`surface\` where \`rowHover\` ${p.rowHover} is ${D(jt)} — the selection has to be at least ${Sa} \`L*\` further out than the hover, or a reader scanning sees one mark at two strengths rather than two states. A palette that cannot reach it has its whole legal step consumed by the ink floors, and that is a ledger row rather than a relaxed floor`)}else!e.composed&&l(v,"rowSelected","rank")&&n(`${v}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — the pair ranks ${D(Le-jt)} \`L*\`, clear of the ${Sa} the row claims it misses. Remove the row`);e.assertions++,se<Gr+ci-1e-9&&n(`${v}: \`rowSelected\` ${S} carries C* ${D(se)} where \`rowHover\` ${p.rowHover} carries ${D(Gr)} — the selection has to carry at least ${ci} chroma more than the hover. This is the rank that costs nothing: a fill may be ranked on cast without spending a single L* of the ink budget, and the shipped fleet's chroma rank was INVERTED on 14 palettes because the hover desaturated while the selection did not`),e.assertions++,jt<$f*Le-1e-9&&n(`${v}: \`rowHover\` ${p.rowHover} takes ${D(jt)} \`L*\` of the ${D(Le)} the selection takes (${Math.round(jt/Le*100)}%), under the ${Math.round($f*100)}% this file requires — the operator asked for MORE of the brightening than the shipped 30%, and an absolute hover floor cannot state that on a fleet whose budgets differ by 2.5x`)}e.assertions++;const Mt=ue(S,p.surface);if(Mt<at-1e-9){const Ae=l(v,w,"band");d.add(`${v}:${w}:band`),e.assertions++,Ae?b(Ae.measured,Mt,.05)||n(`${v}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Ae.measured} and the palette now measures ${D(Mt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${v}: \`${w}\` ${S} is ΔE00 ${D(Mt)} from \`surface\` ${p.surface} (the field floor is ${at}) — below this the mark is not findable while scanning, which is the operator's report restated. The band this role used to be held to was 4.0 and is WITHDRAWN because a backdrop-faithful fill cannot reach it on lightness; this floor is what is left, and a palette that misses even it needs a ledger row with the floor that refuses it`)}else!e.composed&&l(v,w,"band")&&n(`${v}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${D(Mt)} from \`surface\`, clear of the ${at} the row claims it misses. Remove the row`);e.assertions++;const ve=ue(S,p.accentWash);if(!Ke&&ve<Ea){const Ae=l(v,w,"wash");d.add(`${v}:${w}:wash`),e.assertions++,Ae?b(Ae.measured,ve,.05)||n(`${v}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Ae.measured} and the palette now measures ${D(ve)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${v}: \`${w}\` ${S} is ΔE00 ${D(ve)} from \`accentWash\` ${p.accentWash} (need ${Ea}) — 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&&!Ke&&l(v,w,"wash")&&n(`${v}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${D(ve)} from \`accentWash\`, clear of the ${Ea} the row claims it misses. Remove the row`)}if(W(p.rowHover)&&W(p.rowSelected)){e.assertions++;const g=ue(p.rowSelected,p.rowHover),w=uC;g<w-1e-9&&n(`${v}: \`rowHover\` ${p.rowHover} and \`rowSelected\` ${p.rowSelected} are ΔE00 ${D(g)} apart (need ${w}) — the reader sees two marks and cannot rank them. This was the second half of the operator's report: on \`neon\` the shipped pair sat 1.80 ΔE apart while each was ~6.2 ΔE off the panel. The ranking is the fill's now, so a palette that misses this is missing because the two fills are the SAME MARK — give the selection more step or more cast than the hover`)}if(W(p.sunken)&&W(p.rowHover)&&W(p.rowSelected)&&W(p.borderControl))for(const g of["rowHover","rowSelected"]){e.assertions++;const w=ue(p.sunken,p[g]),S=oe(p.borderControl,p[g]);w<at&&S<Me.nonText&&n(`${v}: the agents sidebar's avatar plate has no perceivable edge against \`${g}\` — its \`sunken\` fill ${p.sunken} is ΔE00 ${D(w)} from it (need ${at}) and the plate's \`borderControl\` edge ${p.borderControl} is ${D(S)}:1 against that same fill (need ${Me.nonText}:1), so the row's own ${g==="rowHover"?"hover":"selection"} turns the avatar into a disc of the row's fill. Give the plate an edge the row's state cannot overrun, or a fill that state cannot land on`)}if(typeof p.scrim=="string"&&W(p.ink)){const g=p.scrim.match(/rgb\((\d+)\s+(\d+)\s+(\d+)\s*\/\s*([\d.]+)\)/);if(g){const[w,S,x,F]=g.slice(1).map(Number);for(const j of fn){if(!W(p[j]))continue;const X=[1,3,5].map(Z=>Number.parseInt(p[j].slice(Z,Z+2),16)),T=`#${[w,S,x].map((Z,ge)=>Math.round(Z*F+X[ge]*(1-F)).toString(16).padStart(2,"0")).join("")}`;e.assertions++;const V=oe(p.ink,T);V<Me.nonText&&n(`${v}: the lightbox's current-tile ring has no perceivable edge over \`${j}\` — \`ink\` is ${D(V)}:1 against the scrim composited over it (need ${Me.nonText}:1). The scrim dims whatever is open under it, so the ring's role has to clear every ground the overlay can open over`)}}}for(const g of YT)for(const w of Ge)r(v,p,g,w,Me.nonText,"structural edge");const k=[...Ge,"accentWash","messageSurface"];for(const g of JT)for(const w of k)r(v,p,g,w,Me.text,"colour as text");r(v,p,"warning","elevated",Me.text,"the picker's partial-listing note"),r(v,p,"danger","elevated",Me.text,"danger as text on a dialog's ground"),r(v,p,"warning","rowSelected",Me.text,"integration status text on a deep-linked row"),r(v,p,"accent","warningWash",Me.text,"model-access band links on the warning wash"),r(v,p,"warning","rowHover",Me.text,"the partial delivery word on the hovered row's ground"),r(v,p,"dangerBorder","elevated",Me.nonText,"the danger control's only edge on a dialog's ground");for(const g of zT)for(const w of g.on){const S=p[w],x=g.fill?p[g.fill]:S,F=p[g.ink],j=g.border?p[g.border]:null;if(!W(S)||!W(x)||!W(F))continue;e.assertions++;const X=oe(F,x);if(X<Me.text&&!Sf.has(g.ink)&&!s(v,g.ink,g.fill??w,X)&&n(`${v}: ${g.name} on ${w} — ink ${g.ink} ${F} on fill ${x} = ${X}:1, need ${Me.text}:1`),g.edge!==!1){e.assertions++;const T=oe(x,S),V=W(j)?oe(j,S):0,Z=Math.max(T,V);if(Z<Me.nonText){const ge=nC.find(z=>z.control===g.name&&z.ground===w&&z.theme===v&&y(z.got,D(Z)));ge?h.add(m(ge.control,ge.ground,ge.theme)):n(`${v}: ${g.name} on ${w} has no perceivable edge — fill ${T}:1, border ${V}:1, need one at ${Me.nonText}:1`)}}}for(const g of QT)r(v,p,g.fg,g.on,g.floor,g.name);for(const g of VT)for(const w of g.on)r(v,p,g.fg,w,g.floor??Me.nonText,g.name);for(const g of KT){const w=p[g.b];if(W(w))for(const S of g.a){const x=p[S];if(!W(x))continue;e.assertions++;const F=oe(x,w);F<g.floor&&!s(v,S,g.b,F)&&n(`${v}: ${g.name} — ${S} ${x} against ${g.b} ${w} = ${F}:1, need ${g.floor}:1`)}}for(const g of ZT){const w=p[g.role];if(!W(w))continue;for(const T of g.on){if(!W(p[T]))continue;e.assertions++;const V=ue(w,p[T]);V<g.minDeltaE&&!a(v,g.role,T,D(V))&&n(`${v}: ${g.name} — ${g.role} ${w} on ${T} ${p[T]} is ΔE00 ${D(V)}, need ${g.minDeltaE} to be seen at all`)}if(!g.pairedWith||!g.against)continue;const S=p[g.pairedWith],x=p[g.against];if(!W(S)||!W(x))continue;e.assertions++;const F=oe(w,x),j=oe(S,x),X=Math.max(F/j,j/F);X>g.maxWeightChange&&n(`${v}: ${g.name} — ${g.role} is ${D(X)}x the weight of ${g.pairedWith} against ${g.against}; one component must not change weight by more than ${g.maxWeightChange}x between states`)}for(let g=0;g<Es.length;g++)for(let w=g+1;w<Es.length;w++){const[S,x]=[Es[g],Es[w]];if(!W(p[S])||!W(p[x]))continue;e.assertions++;const F=ue(p[S],p[x]);F<cn&&n(`${v}: \`${S}\` ${p[S]} and \`${x}\` ${p[x]} are too close to tell apart (ΔE00 ${D(F)}, need ${cn}) — a semantic a reader cannot distinguish from another semantic is not a semantic`)}if(W(p.accentAlt)){if(W(p.accent)){e.assertions++;const x=ue(p.accentAlt,p.accent);x<cn&&n(`${v}: the second accent \`accentAlt\` ${p.accentAlt} is ΔE00 ${D(x)} from \`accent\` ${p.accent} (need ${cn}) — 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 x of["success","warning","danger"]){if(!W(p[x]))continue;e.assertions++;const F=ue(p.accentAlt,p[x]);F<cn&&n(`${v}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${D(F)} from \`${x}\` ${p[x]} (need ${cn}) — a decorative mark a reader can mistake for "${x==="danger"?"something broke":x}" costs them something real, so the palette moves the hue rather than the assertion`)}if(W(p.info)){e.assertions++;const x=ue(p.accentAlt,p.info);x<Rr&&n(`${v}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${D(x)} from \`info\` ${p.info} (need ${Rr}) — \`info\` is the family the port mapped the TUI's \`signal\` onto, so the floor here is the reduced one and not ${cn}; below it the two take the same name`)}const[,g,w]=ae(p.accentAlt),S=Math.hypot(g,w);e.assertions++,S<Zo&&n(`${v}: \`accentAlt\` ${p.accentAlt} is C* ${D(S)} (need ${Zo}) — 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 x of["canvas","surface","sunken"])r(v,p,"accentAlt",x,Me.text,"second accent as text");r(v,p,"accentAlt","elevated",Me.text,"second accent as text on a row's state ground")}if(o(v,p,"accentAlt","info",kr,"the tool row's two category inks"),o(v,p,"info","accent",Sr,"the settled read ink against the liveness ink"),W(p.accentAltWash)&&W(p.accentWash)){e.assertions++;const g=ue(p.accentAltWash,p.accentWash);g<at&&n(`${v}: \`accentAltWash\` ${p.accentAltWash} is ΔE00 ${D(g)} from \`accentWash\` ${p.accentWash} (need ${at}) — the two washes sit adjacent in mermaid's categorical ramp, so a step the reader cannot see is not a step`)}for(const g of oC){if(!W(p[g])||!W(p.inkDim))continue;e.assertions++;const w=ue(p[g],p.inkDim);w<Rr&&n(`${v}: syntax \`${g}\` ${p[g]} sits at ΔE00 ${D(w)} from comment \`${p.inkDim}\` (need ${Rr}) — a token the eye cannot separate from the comment beside it is not highlighted`)}if(W(p[ro])&&W(p.ink)){const g=iC.find(w=>w.theme===v);for(const w of sC){if(!W(p[w]))continue;e.assertions++;const S=oe(p[ro],p[w]);S<4.5&&n(`${v}: the command token \`tokenCommand\` ${p[ro]} reads ${D(S)}:1 on \`${w}\` (need 4.5) - the token is text a user typed (the composer's leading /word, or the sent \`$skill\` mention), not decoration`)}for(const w of["ink","accent","success"]){if(!W(p[w]))continue;e.assertions++;const S=ue(p[ro],p[w]);if(!!g?.against.includes(w)){y(g.got,S)||n(`${v}: COMMAND_TOKEN_PINNED records ${g.got} for \`command\`/\`${w}\` but it now measures ${D(S)} - re-measure and update the pin (${g.why})`);continue}S<As&&n(`${v}: the command token \`tokenCommand\` ${p[ro]} sits at ΔE00 ${D(S)} from \`${w}\` ${p[w]} (need ${As}) - the composer paints this run in the same box as that ink, so a reader cannot tell which is which`)}if(W(p.success)){e.assertions++;const w=ue(p.success,p.ink);w<As&&n(`${v}: the roster NAME's ink \`success\` ${p.success} sits at ΔE00 ${D(w)} from prose \`ink\` ${p.ink} (need ${As}) - a resolved name that reads as prose is not a run`)}}if(W(p.inkMuted)&&W(p.inkDim)){e.assertions++,u.add(v);const g=ue(p.inkMuted,p.inkDim),w=tC.find(S=>S.theme===v);w&&f.add(w),g<wo?w?y(w.got,g)||n(`${v}: INK_STEP_PINNED records ${w.got} but \`inkMuted\`/\`inkDim\` now measure ${D(g)} - re-measure and update the pin, so the recorded number stays the one in the palette`):n(`${v}: the control ink \`inkMuted\` ${p.inkMuted} sits at ΔE00 ${D(g)} from the readout ink \`inkDim\` ${p.inkDim} (need ${wo}) - a chip that opens cannot be told from a reading that does not`):w&&!e.composed&&n(`${v}: the ink step is pinned at ${w.got} but now measures ${D(g)}, clearing the ${wo} floor - delete the pin rather than leaving dead weight in the contract`)}for(const[g,w,S=at]of[["canvas","surface"],["surface","elevated"],["elevated","sunken"],["accent","accentHover"],["accentHover","accentActive"],["accent","accentActive"],["surface","sunken"],["canvas","elevated",lC]]){if(!W(p[g])||!W(p[w]))continue;e.assertions++;const x=ue(p[g],p[w]);x<S&&n(`${v}: adjacent \`${g}\` and \`${w}\` are ΔE00 ${D(x)} apart (need ${S}) — a step the eye cannot see is not a step`)}{const g=ae(p.canvas)[0],w=ae(p.surface)[0],S=ae(p.elevated)[0],x=ae(p.sunken)[0],F=p.mode==="dark";e.composed||(e.assertions++,F&&(g<Vt.dark.canvasMin||g>Vt.dark.canvasMax)&&n(`${v}: dark \`canvas\` ${p.canvas} sits at L* ${D(g)} — the band is [${Vt.dark.canvasMin}, ${Vt.dark.canvasMax}] in L*. Below the floor the three ink weights and the three ladder steps stop fitting above each other without one of them breaking its own floor; above the ceiling the canvas is no longer the darker tone the operator asked for (2026-11-03), and a palette above it was not re-lit by the band's proportional map`),e.assertions++,F&&S>Vt.dark.elevatedMax&&n(`${v}: dark \`elevated\` ${p.elevated} sits at L* ${D(S)} — the ceiling is L* ${Vt.dark.elevatedMax}, because at L* 34 an \`inkDim\` at its floor needs L* 85 and the ink/hover distinction disappears into the top of the ramp`),e.assertions++,!F&&g>Vt.light.canvasMax&&n(`${v}: light \`canvas\` ${p.canvas} sits at L* ${D(g)} — the ceiling is L* ${Vt.light.canvasMax}. \`elevated\` at L* 100 is the end of sRGB's ramp and the minimum canvas-to-elevated spread is 2.5 + 2.5 L*, so a canvas above 95 has no room for both steps; 94 leaves 1 L* for 8-bit rounding`),e.assertions++,!F&&x<Vt.light.sunkenMin&&n(`${v}: light \`sunken\` ${p.sunken} sits at L* ${D(x)} — the floor is L* ${Vt.light.sunkenMin}. A light theme's recessed ground is the darkest plane in it, so it is the cap for every ink there and the keycap's ground on every selected row`));for(const[j,X,T,[V,Z],ge]of[["canvas -> surface","canvas","surface",Rn.canvasSurface,w-g],["surface -> elevated","surface","elevated",Rn.surfaceElevated,S-w],["canvas -> sunken","canvas","sunken",Rn.canvasSunken,g-x]])if(e.assertions++,(ge<V-1e-9||ge>Z+1e-9)&&n(`${v}: the ${j} step is ${D(ge)} L*, outside [${V}, ${Z}] — the bounds are both ends of the same budget: below the floor the two grounds merge, and above the ceiling the step eats the room the ink ladder needs`),r(v,p,X,T,GT,`${j} step`),X==="canvas"&&T==="sunken"||X==="surface"&&T==="elevated"){e.assertions++;const z=ue(p[X],p[T]),me=X==="canvas"?WT:dC;z<me&&n(X==="canvas"?`${v}: \`canvas\` and \`sunken\` are ΔE00 ${D(z)} apart (need ${me}) — a well nobody can see is not a well, and both blocks that paint one are read inside a trace that sits on the canvas`:`${v}: \`surface\` ${p.surface} and \`elevated\` ${p.elevated} are ΔE00 ${D(z)} apart (need ${me}) — the hover rung is the ground a hover, a menu and a dialog are all painted on, so it cannot sit closer to the panel than this and still report the pointer; it is also the ground the current row has to outrank, so a rung at this floor is what the row/hover ordering is measured against. Place it at the lowest \`L*\` that clears this and no lower - the row's own rank against the hover is asserted in the row-state loop below, so a rung placed here is a rung the two row fills have to fit above`)}}r(v,p,"ink","canvas",Bl,"the transcript's body ink");for(const g of fn){if(!W(p.inkDisabled)||!W(p.inkDim)||!W(p[g]))continue;e.assertions++;const w=oe(p.inkDisabled,p[g]),S=oe(p.inkDim,p[g]);w>Ef*S+1e-9&&n(`${v}: \`inkDisabled\` on ${g} measures ${D(w)}:1 against \`inkDim\`'s ${D(S)}:1 — a factor of ${D(w/S)}, over the ${Ef} ceiling. A disabled control that meets the ink floors does not read as disabled`)}for(const[g,w]of[["inkDim","inkMuted"],["inkMuted","ink"]]){if(!W(p[g])||!W(p[w]))continue;e.assertions++;const S=ue(p[g],p[w]);S<ai&&n(`${v}: \`${w}\` and \`${g}\` are ΔE00 ${D(S)} apart (need ${ai}) — the three weights are a ladder, and a rung the eye cannot see is not a rung`)}{const g=ue(p.sunken,p.elevated);e.assertions++,g<Af&&n(`${v}: the palette/picker active row (\`sunken\` ${p.sunken}) is ΔE00 ${D(g)} from the dialog ground it is painted on (\`elevated\` ${p.elevated}), need ${Af} — a selection is a state the reader has to find while scanning, not a surface they read, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ae(p.sunken)[0]-ae(p.elevated)[0]);w<If&&n(`${v}: the palette/picker active row sits ${D(w)} L* from \`elevated\`, under the ${If} L* floor — ΔE00 is a budget a chroma-only step can spend while the mark vanishes in a greyscale render, so the lightness half is asserted too`)}{if(p.messageSurface===void 0)continue;if(!W(p.messageSurface)){n(`${v}: the user message block's fill \`messageSurface\` ${JSON.stringify(p.messageSurface)} is present but not a flat hex colour, so the role's floor would be silently unmeasured - a malformed value must not switch a floor off`);continue}if(!W(p.canvas))continue;const g=ue(p.messageSurface,p.canvas);e.assertions++,g<Rf&&n(`${v}: the user message block's fill \`messageSurface\` ${p.messageSurface} is ΔE00 ${D(g)} from \`canvas\` ${p.canvas} (need ${Rf}) — the fill IS the block's boundary, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ae(p.messageSurface)[0]-ae(p.canvas)[0]);w<wc&&n(`${v}: the user message block's fill sits ${D(w)} L* from \`canvas\`, under the ${wc} L* floor — ΔE00 is a budget a chroma-only step can spend while the mark vanishes in a greyscale render, so the lightness half is asserted too`)}{if(p.mediaSurface===void 0)continue;if(!W(p.mediaSurface)){n(`${v}: the media tile's fill \`mediaSurface\` ${JSON.stringify(p.mediaSurface)} is present but not a flat hex colour, so the role's floor would be silently unmeasured - a malformed value must not switch a floor off`);continue}if(!W(p.canvas))continue;const g=ue(p.mediaSurface,p.canvas);e.assertions++,g<xf&&n(`${v}: the media tile's fill \`mediaSurface\` ${p.mediaSurface} is ΔE00 ${D(g)} 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(ae(p.mediaSurface)[0]-ae(p.canvas)[0]);w<Tf&&n(`${v}: the media tile's fill sits ${D(w)} L* from \`canvas\`, under the ${Tf} L* floor — ΔE00 is a budget a chroma-only step can spend while the fill vanishes in a greyscale render, so the lightness half is asserted too`)}for(const g of Ge){if(!W(p.accentWash)||!W(p[g]))continue;e.assertions++;const w=ue(p.accentWash,p[g]);w<Cf&&n(`${v}: the accent wash on ${g} is ΔE00 ${D(w)} (need ${Cf}) — a hover tint the reader cannot see is a hover state the pointer cannot report, and this pair reads 1.00-1.24:1, so no ratio assertion in this file can see it`)}for(const g of["canvas","surface","elevated","accentWash"]){if(!W(p.sunken)||!W(p[g]))continue;e.assertions++;const w=ue(p.sunken,p[g]);w<Of&&n(`${v}: the keycap's ground \`sunken\` ${p.sunken} is ΔE00 ${D(w)} from ${g} ${p[g]} (need ${Of}) — the cap annotates the row the reader has just selected, so its ground has to survive being painted on that row`)}if(W(p.chartBarHover)&&W(p.accent)&&W(p[Is])){e.assertions++;const g=ue(p.chartBarHover,p.accent);g<Ec&&n(`${v}: \`chartBarHover\` ${p.chartBarHover} is ΔE00 ${D(g)} from \`accent\` ${p.accent}, need ${Ec} — a mark the reader has to find among its SIBLINGS is compared with them, not with itself across two states`),e.assertions++;const w=oe(p.chartBarHover,p[Is]),S=oe(p.accent,p[Is]);w<S&&n(`${v}: \`chartBarHover\` is ${D(w)}:1 on ${Is} where \`accent\` is ${D(S)}:1 — the hovered mark must not recede toward the ground it is drawn on`)}for(const g of Ge){if(!W(p.hairline)||!W(p[g]))continue;e.assertions++;const w=ue(p.hairline,p[g]);w<Pf&&n(`${v}: \`hairline\` on \`${g}\` is ΔE00 ${D(w)} (need ${Pf}) — a 1px line has no area to integrate over, so a step that reads between two fields disappears in a rule`);const S=oe(p.hairline,p[g]);e.assertions++,S<Ff&&n(`${v}: \`hairline\` on \`${g}\` is ${D(S)}:1 (need ${Ff}) — its ΔE00 is carried in chroma, which a 1px line does not survive`),e.assertions++,S>Lf&&n(`${v}: \`hairline\` on \`${g}\` is ${D(S)}:1 (max ${Lf}) — past this it is drawing a border, and the system already has one of those`)}for(const[g,w]of cC){if(!W(p.hairline)||!W(p[g])||!W(p[w]))continue;const S=va(p.hairline,p[g],aC);e.assertions++;const x=ue(S,p[g]);x<at&&n(`${v}: the panel seam over \`${g}\` is ΔE00 ${D(x)} from that ground (need ${at}) — the seam is half the boundary, and half a boundary the reader cannot see is a panel edge that disappears`),e.assertions++;const F=ue(S,p[w]);F<at&&n(`${v}: the panel seam over \`${g}\` is ΔE00 ${D(F)} from \`${w}\` (need ${at}) — the seam has to read from the plane it faces as well as the one it sits on`)}const C=va(p.accent,p.surface,Mf);for(const[g,w,S]of[["inkMuted",Me.text,"washed row metadata ink"],["ink",Me.text,"washed row body ink"]]){const x=p[g];if(!W(x))continue;e.assertions++;const F=D(oe(x,C));F>=w||n(`${v}: ${S} — ${g} ${x} on the arrival band ${C} (accent ${Mf} over surface) = ${F}:1, need ${w}:1`)}for(const g of["canvas","surface","elevated","accentWash"]){const w=va(p.accent,p[g],jf);for(const[S,x,F]of[["inkMuted",Me.text,"loading pill label"]]){const j=p[S];if(!W(j))continue;e.assertions++;const X=D(oe(j,w));X>=x||n(`${v}: ${F} — ${S} ${j} on the loading pill ${w} (accent ${jf} over ${g}) = ${X}:1, need ${x}:1`)}}const L=oe(C,p.surface),O=oe(p.rowHover,p.surface),I=oe(p.rowSelected,p.surface);e.assertions+=2,L<=O&&n(`${v}: the arrival band is ${D(L)}:1 over the pane and the row hover is ${D(O)}:1 — the mark the reader was TOLD about cannot be drawn more quietly than one their pointer rests on`),L<=I&&n(`${v}: the arrival band is ${D(L)}:1 over the pane and the selected row is ${D(I)}:1 — the arrival must outrank the row the reader is already on, or the landing reads as a selection`)}},yC=Object.freeze({soft:-100,gentle:-50,standard:0,strong:50,high:100}),wC=Object.freeze({dark:Object.freeze({high:5,soft:20}),light:Object.freeze({high:97,soft:89})}),kC=["canvas","surface","elevated","sunken","messageSurface","mediaSurface","rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash","hairline","hairlineStrong","inkDisabled"],SC=new Set(["rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash"]),$s=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Ct=$s.slice(0,4),oo=[...Ct,"accentWash","messageSurface"],Aa={ink:[$s,7],inkMuted:[$s,5.5],inkDim:[$s,5],borderControl:[Ct,3],accent:[[...oo,"warningWash"],4.5],accentHover:[Ct,4.5],accentActive:[Ct,4.5],tokenCommand:[["surface","elevated","messageSurface"],4.5],accentAlt:[Ct,4.5],success:[oo,4.5],warning:[[...oo,"rowSelected","rowHover"],4.5],danger:[oo,4.5],info:[oo,4.5],successBorder:[Ct,3],warningBorder:[Ct,3],dangerBorder:[Ct,3],infoBorder:[Ct,3],chartBarHover:[["surface"],3]},Ot=.05,Uf=.3,Bf=4.1,EC=.06,AC=/^#[0-9A-Fa-f]{6}$/,st=e=>typeof e=="string"&&AC.test(e),Bt=e=>e.slice(0,7).toUpperCase(),lt=(e,t,n)=>{const r=Math.max(0,Math.min(100,e));for(let o=1;o>=0;o-=.02){const s=ii([r,t*o,n*o]);if(s)return s}return ii([r,0,0])},rr=(e,t,n)=>Math.min(...n.filter(r=>st(e[r])).map(r=>oe(t,e[r]))),Ac=(e,t,n,r,o=()=>!0)=>{const s=e[t];if(!st(s)||rr(e,s,n)>=r+Ot&&o(s))return s;const[a,c,l]=ae(s),d=e.mode==="dark"?1:-1;for(let u=.25;u<=100;u+=.25){const f=lt(a+d*u,c,l);if(rr(e,f,n)>=r+Ot&&o(f))return f}return s},Hl=(e,t)=>{const n=t.filter(st).map(Bt),r=n.find(o=>oe(o,e)>=4.5);return r||[...n].sort((o,s)=>oe(s,e)-oe(o,e))[0]},Rs=e=>1+.015*(e-50)**2/Math.sqrt(20+(e-50)**2),or=e=>{const[,t,n]=ae(e);return Math.hypot(t,n)},Hf=(e,t)=>{const[n,r,o]=ae(e),s=Math.hypot(r,o);return s<1e-6?e:lt(n,r/s*t,o/s*t)},IC=e=>{if(!st(e.rowHover)||!st(e.rowSelected))return;TC(e);const t=or(e.surface),n=Math.max(li,Ug*t),r=Math.max(t,li),o=Math.max(di,t),s=Math.min(Math.max(t+kc,di),Sc),a=(f,h,m)=>Math.min(Math.max(f,h),m),c=or(e.rowHover),l=or(e.rowSelected);if(c>=n&&c<=r&&l>=o&&l<=s&&l>=c+ci)return;const d=a(c,n+.1,r-.1),u=a(Math.max(l,d+ci+.2),o+.1,s-.1);e.rowHover=Hf(e.rowHover,d),e.rowSelected=Hf(e.rowSelected,u)},RC=6,xC=e=>{const[,t,n]=ae(e);return Math.atan2(n,t)},TC=e=>{const n=or(e.surface)>=pn?e.surface:or(e.accent)>=Bg?e.accent:e.surface,r=xC(n);for(const o of["rowHover","rowSelected"]){const[s,a,c]=ae(e[o]),l=Math.hypot(a,c);l<pn||Math.abs(((Math.atan2(c,a)-r)*180/Math.PI+540)%360-180)<=RC||(e[o]=lt(s,l*Math.cos(r),l*Math.sin(r)))}},CC=e=>{const t=e.mode==="dark"?1:-1,n=(r,o,s,a,c)=>{const l=e[r];if(!st(l))return;const d=m=>rr(e,m,o)>=s+Ot&&(!a||ue(m,e[a])>=c+Ot)&&(r!=="ink"||oe(m,e.canvas)>=Bl+Ot);if(d(l))return;const[u,f,h]=ae(l);for(let m=.25;m<=100;m+=.25){const y=lt(u+t*m,f,h);if(d(y)){e[r]=y;return}}};n("inkDim",fn,Ns("inkDim"),null,0),n("inkMuted",fn,Ns("inkMuted"),"inkDim",wo),n("ink",fn,Ns("ink"),"inkMuted",ai)},Ns=e=>Lg.find(([t])=>t===e)[1],OC=.15,Hg=.12,PC=(e,t,n)=>{if(!st(e.ink)||!st(e.canvas))return;const r=Math.abs(n)/100,o=e.mode==="dark"?1:-1;if(n>0){const[l,d,u]=ae(e.ink),f=t*(1+OC*r);if(oe(e.ink,e.canvas)>=f)return;for(let h=.25;h<=100;h+=.25){const m=l+o*h;if(m<0||m>100)break;const y=lt(m,d,u);if(e.ink=y,oe(y,e.canvas)>=f)return}return}const s=t*(1-Hg*r),a=["ink","inkMuted","inkDim"].filter(l=>st(e[l])),c=l=>a.every(d=>rr(e,l[d],fn)>=Ns(d)+Ot)&&oe(l.ink,e.canvas)>=Bl&&(!l.inkMuted||ue(l.ink,l.inkMuted)>=ai+Ot)&&(!l.inkMuted||!l.inkDim||ue(l.inkMuted,l.inkDim)>=wo+Ot);for(const l of[a,a.slice(0,2),a.slice(0,1)]){const d=Object.fromEntries(l.map(u=>[u,ae(e[u])]));for(let u=.25;u<=60;u+=.25){if(oe(e.ink,e.canvas)<=s)return;const f={...e};for(const h of l){const[m,y,b]=d[h];f[h]=lt(m-o*u,y,b)}if(!c(f))break;for(const h of l)e[h]=f[h]}}},xs=(e,t,n,r,o=()=>!0)=>{const s=e[t];if(!st(s)||!n.split(",").every(f=>st(e[f])))return;const a=f=>n.split(",").every(h=>ue(f,e[h])>=r+Ot)&&o(f);if(a(s))return;const[c,l,d]=ae(s),u=e.mode==="dark"?1:-1;for(const f of[u,-u])for(let h=.25;h<=40;h+=.25){const m=lt(c+f*h,l,d);if(a(m)){e[t]=m;return}}},Wg=(e,t,{spread:n=1,narrow:r=!1,ease:o=EC,travel:s=1}={})=>{if(t===0)return e;const a=t>0?"high":"soft",c=Math.abs(t)/100,l={...e},d=z=>ae(Bt(e[z])),u=d("canvas")[0],f=wC[e.mode][a],h=kC.filter(z=>st(e[z])),m=a==="high"==(e.mode==="light")?1:-1;let y=Math.max(0,(f-u)*m)*m*c*s,b=u+y;const v=a==="soft"?1-.4*c:1,p=Rs(b)/Rs(u),A=(a==="soft"?p:Math.max(1,p))*n,k=Object.fromEntries(h.map(z=>[z,b+(d(z)[0]-u)*A])),C=e.mode==="dark"?1:-1,L=(z,[,me],se)=>{const je=(d(z)[0]-u)*se,De=(k[z]-b)*se,Ke=Math.max(je,me-.15);De>Ke&&(k[z]=b+se*Ke)};L("surface",Rn.canvasSurface,C),L("sunken",Rn.canvasSunken,-C);{const z=(d("elevated")[0]-d("surface")[0])*C,me=(k.elevated-k.surface)*C,se=Math.max(z,Rn.surfaceElevated[1]-.15);me>se&&(k.elevated=k.surface+C*se)}const O=d("surface")[0],I=e.mode==="dark"?1:-1,g=(d("rowSelected")[0]-O)*I,w=(d("rowHover")[0]-O)*I,S=g>0?Math.min(A,Fg/g):A,x=a==="soft"?S:Math.max(1,S);if(k.rowSelected=k.surface+I*g*x,k.rowHover=k.surface+I*w*x,e.mode==="light"&&a==="high"){const z=u+y,me=Object.keys(k).filter(je=>d(je)[0]>u),se=Math.max(0,...me.map(je=>d(je)[0]-u));if(se>0){const je=ve=>{const Ae=Math.min(1,(100-Uf-ve)/se),ft={canvas:lt(ve,...d("canvas").slice(1))};for(const _t of me)ft[_t]=lt(ve+(d(_t)[0]-u)*Ae,...d(_t).slice(1));return ft},De=[["canvas","surface",at],["surface","elevated",at],["canvas","elevated",Bf],["canvas","messageSurface",Bf]].filter(([ve,Ae])=>(ve==="canvas"||me.includes(ve))&&me.includes(Ae)),Ke=[["canvas","surface",Rn.canvasSurface[0]],["surface","elevated",Rn.surfaceElevated[0]],["canvas","messageSurface",wc]].filter(([ve,Ae])=>(ve==="canvas"||me.includes(ve))&&me.includes(Ae)),tt=(ve,Ae,ft)=>ft+.02,_e=ve=>De.every(([Ae,ft,_t])=>ue(ve[Ae],ve[ft])>=tt(Ae,ft,_t))&&Ke.every(([Ae,ft,_t])=>ae(ve[ft])[0]-ae(ve[Ae])[0]>=_t+.15);let Ce=z;for(;Ce>u&&!_e(je(Ce));)Ce=Math.max(u,Ce-.25);const Rt=Ce<=u?1:Math.min(1,(100-Uf-Ce)/se),Le=Math.max(1,Rs(Ce)/Rs(u))*n,Mt={rowHover:k.rowHover-k.surface,rowSelected:k.rowSelected-k.surface};for(const ve of Object.keys(k))k[ve]=me.includes(ve)?Ce+(d(ve)[0]-u)*Rt:Ce+(k[ve]-z)*(Le/A);for(const ve of["rowHover","rowSelected"])ve in k&&Number.isFinite(Mt[ve])&&(k[ve]=k.surface+Mt[ve]);b=Ce,y=Ce-u}}if(a==="soft"&&r){const z=_e=>e.mode==="dark"?_e>b:_e<b,me=_e=>_e>8?((_e+16)/116)**3:Math.max(0,_e)/903.3,se=(_e,Ce)=>{const[Rt,Le]=[me(_e),me(Ce)];return(Math.max(Rt,Le)+.05)/(Math.min(Rt,Le)+.05)},je=fn.filter(_e=>_e in k&&z(k[_e])),Ke=Math.max(1,...fn.filter(_e=>_e in k&&(e.mode==="dark"?d(_e)[0]>u:d(_e)[0]<u)).map(_e=>se(u,d(_e)[0])))*(1-o*c),tt=_e=>Math.max(1,...je.map(Ce=>se(b,b+(k[Ce]-b)*_e)));if(je.length>0&&tt(1)>Ke){let _e=1;for(;_e>.3&&tt(_e)>Ke;)_e-=.01;for(const Ce of Object.keys(k))z(k[Ce])&&(k[Ce]=b+(k[Ce]-b)*_e)}}const F=Math.min(...Object.values(k)),j=Math.max(...Object.values(k)),X=F<.5?.5-F:j>100?100-j:0,T=or(Bt(e.surface)),V=T>=pn?Math.max(v,Math.min(1,(pn+.4)/T)):v;for(const z of h){const[,me,se]=d(z),je=SC.has(z)?1:z==="surface"?V:v;l[z]=lt(k[z]+X,me*je,se*je)}IC(l),y=b+X-u;for(const z of Object.keys(Aa))st(e[z])&&(l[z]=Bt(e[z]));CC(l),PC(l,oe(Bt(e.ink),Bt(e.canvas)),t);const Z=ae(l.accent)[0];l.accent=Ac(l,"accent",...Aa.accent);const ge=ae(l.accent)[0]-Z;for(const z of["accentHover","accentActive"]){if(!st(l[z])||ge===0)continue;const[me,se,je]=ae(l[z]);l[z]=lt(me+ge,se,je)}for(const[z,[me,se]]of Object.entries(Aa))z.startsWith("ink")||z==="accent"||(l[z]=Ac(l,z,me,se));return xs(l,"accentHover","accent",at,z=>rr(l,z,Ct)>=4.5+Ot),xs(l,"accentActive","accent,accentHover",at,z=>rr(l,z,Ct)>=4.5+Ot),xs(l,"accentAlt","accent",cn,z=>rr(l,z,Ct)>=4.5+Ot&&or(z)>=Zo),xs(l,"chartBarHover","accent",Ec,z=>oe(z,l.surface)>=oe(l.accent,l.surface)),l.onAccent=Hl(l.accent,[e.onAccent,l.ink,l.canvas,"#FFFFFF","#000000"]),l},ui=(e,t="custom")=>{const n=bC({composed:!0});return vC(n,{id:t,palette:e}),n.log},Ds=(e,t)=>{const n=Hl(e.accent,[t.onAccent,e.ink,e.canvas,"#FFFFFF","#000000"]);return n===e.onAccent?e:{...e,onAccent:n}},Wf=new Set(["mode","overlayShadow","scrim","onAccent"]),MC=["rowHover","rowSelected","accentWash","surface"],jC=/\b[a-z][A-Za-z]+\b/g,$C=(e,t)=>{const n=new Map;for(const[o,s]of Object.entries(e))!Wf.has(o)&&st(s)&&n.set(s.toUpperCase(),o);const r=new Set;for(const o of t){if(o.includes("ROW_STATE_MEASURED_SHORTFALL"))for(const s of MC)r.add(s);for(const[s]of o.matchAll(jC))s in e&&!Wf.has(s)&&st(e[s])&&r.add(s);for(const[s]of o.matchAll(NC)){const a=n.get(s.toUpperCase());a&&r.add(a)}}return[...r]},NC=/#[0-9A-Fa-f]{6}\b/g,DC=/(?:= |ΔE00 )(\d+(?:\.\d+)?)(?::1)?[\s\S]*?need (\d+(?:\.\d+)?)/,LC=e=>{let t=0;for(const n of e){const r=n.match(DC);if(!r){t+=1;continue}const o=Number(r[1]),s=Number(r[2]);t+=s>0?Math.min(1,Math.max(0,(s-o)/s)):1}return t},Gf=e=>e.length*1e3+LC(e),FC=[.5,-.5,1,-1,2,-2,4,-4,7,-7,11,-11],UC=[.7,.85,1.15,1.35],BC=60,Gg=(e,t,n=e,{pinned:r=[],maxEvaluations:o=Number.POSITIVE_INFINITY,lightnessOnly:s=!1}={})=>{const a=new Set(r),c=h=>a.has("onAccent")?h:Ds(h,n);let l=0,d=c(e),u=ui(d,t),f=Gf(u);for(let h=0;h<BC&&u.length>0;h++){let m=null;for(const y of $C(d,u)){if(a.has(y))continue;const[b,v,p]=ae(d[y]),A=[...FC.map(k=>lt(b+k,v,p)),...s?[]:UC.map(k=>lt(b,v*k,p*k))];for(const k of A){if(k===d[y])continue;if(++l>o)return{palette:d,findings:u};const C=c({...d,[y]:k}),L=ui(C,t),O=Gf(L);O<(m?m.score:f)-1e-9&&(m={next:C,findings:L,score:O})}}if(!m)break;d=m.next,u=m.findings,f=m.score}return{palette:d,findings:u}},HC=5,WC=[1,1.15],GC=[{spread:1,narrow:!0},{spread:1,narrow:!0,ease:0},...WC.map(e=>({spread:e})),{spread:1,travel:.5,soft:!0},{spread:1,travel:0,soft:!0}],zf=.015,zC=(e,t,n)=>{const r=oe(Bt(e.ink),Bt(e.canvas)),o=oe(t.ink,t.canvas),s=ae(Bt(e.canvas))[0],a=ae(t.canvas)[0],c=n>0==(e.mode==="light")?1:-1;return n>0?o>=r-zf&&(a-s)*c>=-.05:o<=r+zf},KC=(e,t,n,r)=>{const s=oe(Bt(t.ink),Bt(t.canvas))*(1-Hg*(Math.abs(n)/100)),a=e.mode==="dark"?-1:1,c=["ink","inkMuted","inkDim"].filter(d=>st(e[d]));let l=e;for(const d of[c,c.slice(0,2),c.slice(0,1)]){const u=Object.fromEntries(d.map(f=>[f,ae(l[f])]));for(let f=.25;f<=20;f+=.25){if(oe(l.ink,l.canvas)<=s)return l;const h={...l};for(const m of d){const[y,b,v]=u[m];h[m]=lt(y+a*f,b,v)}if(ui(Ds(h,t),r).length>0)break;l=Ds(h,t)}}for(let d=0;d<6&&oe(l.ink,l.canvas)>s;d++){let u=null;for(const f of[0,1,2])for(const h of[1,-1]){const y=Number.parseInt(l.ink.slice(1+2*f,3+2*f),16)+h;if(y<0||y>255)continue;const b=`#${l.ink.slice(1,1+2*f)}${y.toString(16).padStart(2,"0").toUpperCase()}${l.ink.slice(3+2*f)}`,v=oe(b,l.canvas);if(v>=oe(l.ink,l.canvas))continue;const p=Ds({...l,ink:b},t);ui(p,r).length>0||(!u||v>u.r)&&(u={r:v,next:p})}if(!u)break;l=u.next}return l},VC=(e,t,{id:n="custom"}={})=>{if(!Number.isInteger(t)||t<-100||t>100)throw new RangeError(`contrast must be an integer in -100..100, got ${t}`);if(t===0)return{palette:e,effectiveContrast:0};const r=Math.sign(t);for(let o=t;o!==0;o-=r*Math.min(HC,Math.abs(o)))for(const s of GC){if((s.narrow||s.soft)&&o>0)continue;const a=Wg(e,o,s),c=Gg(a,n,e);if(o<0&&c.findings.length===0&&(c.palette=KC(c.palette,e,o,n)),c.findings.length===0&&zC(e,c.palette,o))return{palette:c.palette,effectiveContrast:o}}return{palette:e,effectiveContrast:0}},Vn=/^#[0-9A-Fa-f]{6}$/,ZC=/^#[0-9A-Fa-f]{3}$/,gt=e=>{if(typeof e!="string")return null;let t=e.trim();return t.startsWith("#")||(t=`#${t}`),ZC.test(t)&&(t=`#${[...t.slice(1)].map(n=>n+n).join("")}`),Vn.test(t)?t.toUpperCase():null},YC=["accentHover","accentActive","accentWash","chartBarHover"],Ft=e=>{const[t,n,r]=ae(e);return[t,Math.hypot(n,r),Math.atan2(r,n)]},JC=e=>Ft(e)[1],fi=(e,t,n)=>lt(e,Math.max(0,t)*Math.cos(n),Math.max(0,t)*Math.sin(n)),QC=4,XC=(e,t,n)=>{const[r,o,s]=Ft(e),[a,c,l]=Ft(t),[d,u,f]=Ft(n);return o<QC?fi(d+(a-r),c,f):fi(d+(a-r),u*(c/o),f+(l-s))},qC=(e,t,n)=>{if(!e||e.kind==="theme")return null;if(e.kind==="theme-alt")return gt(t.accentAlt);if(e.kind==="palette"){const r=typeof n=="function"?n(e.id):null;return gt(r)}return e.kind==="custom"?gt(e.hex):null},eO=(e,t,{authored:n=e,id:r="custom",paletteAccent:o,preserveSecondary:s=!1}={})=>{const a=qC(t,n,o);if(!a)return{palette:e,applied:!1,adjusted:0,requested:a};const c={...e,accent:a};for(const h of YC)!Vn.test(n[h]??"")||!Vn.test(n.accent??"")||(c[h]=XC(n.accent,n[h],a));if(Vn.test(e.accentWash??"")&&Vn.test(n.accentWash??"")){const h=Ft(e.accentWash)[0],[,m,y]=Ft(c.accentWash);c.accentWash=fi(h,Math.max(m,Ft(n.accentWash)[1]),y)}if(JC(c.surface)<pn){const h=Ft(c.accent)[2];for(const m of["rowHover","rowSelected"]){if(!Vn.test(c[m]??""))continue;const[y,b]=Ft(c[m]);b>=pn&&(c[m]=fi(y,b,h))}}!s&&t.kind==="theme-alt"?Ft(n.accent)[1]>=Zo&&(c.accentAlt=gt(n.accent)):!s&&ue(c.accent,c.accentAlt)<cn&&Ft(n.accent)[1]>=Zo&&(c.accentAlt=gt(n.accent));const l=ae(c.accent)[0];c.accent=Ac(c,"accent",tO,4.5,h=>ue(h,c.ink)>=3);const d=ae(c.accent)[0]-l;if(d!==0)for(const h of["accentHover","accentActive","chartBarHover"]){if(!Vn.test(c[h]??""))continue;const[m,y,b]=ae(c[h]);c[h]=lt(m+d,y,b)}c.onAccent=Hl(c.accent,[n.onAccent,c.ink,c.canvas,"#FFFFFF","#000000"]);const u=Gg(c,r,n);return s&&Dg.filter(h=>h.storage==="overrides").flatMap(h=>[h.role,...h.variants]).some(h=>u.palette[h]!==e[h])||u.findings.length>0||ue(u.palette.accent,u.palette.ink)<3?{palette:e,applied:!1,adjusted:0,requested:a}:{palette:u.palette,applied:!0,adjusted:ue(a,u.palette.accent),requested:a}},tO=["canvas","surface","elevated","sunken","accentWash","messageSurface","warningWash"],Kf=["dark","light"],nO=12,kD=50,SD="custom-themes-storage",rO=60,zg=Object.freeze({dark:0,light:0}),xn=Object.freeze({kind:"theme"}),Kg=Object.freeze({dark:xn,light:xn}),Ic=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(-100,Math.min(100,Math.round(e))),Vg=e=>!e||typeof e!="object"?zg:{dark:Ic(e.dark),light:Ic(e.light)},Rc=(e,t=()=>!0)=>{if(!e||typeof e!="object")return xn;switch(e.kind){case"theme":return xn;case"theme-alt":return{kind:"theme-alt"};case"palette":return typeof e.id=="string"&&t(e.id)?{kind:"palette",id:e.id}:xn;case"custom":{const n=gt(e.hex);return n?{kind:"custom",hex:n}:xn}default:return xn}},Zg=(e,t)=>!e||typeof e!="object"?Kg:{dark:Rc(e.dark,t),light:Rc(e.light,t)},Ur=e=>{if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=gt(n);if(r&&!t.includes(r)&&t.push(r),t.length===nO)break}return t},oO=(e,t)=>{const n=gt(t);return Ur(n?[n,...Array.isArray(e)?e:[]]:e)},sO=/^custom-[a-z0-9]{1,30}$/,Wl=e=>typeof e=="string"&&sO.test(e)?e:null,ED=(e,{isThemeName:t,isRole:n})=>{if(!e||typeof e!="object"||e.format!=="local-operator-theme"||e.version!==1)return null;const r=Wl(e.id);if(!r||!Mc(r)||typeof e.base!="string"||!t(e.base))return null;const o=typeof e.name=="string"&&e.name.trim()?e.name.trim().slice(0,rO):null;if(!o)return null;const s=a=>{const c={};if(!a||typeof a!="object")return c;for(const[l,d]of Object.entries(a)){if(!n(l))continue;const u=gt(d);u&&jc(u)&&(c[l]=u)}return c};return{format:"local-operator-theme",version:1,id:r,name:o,base:e.base,seeds:s(e.seeds),overrides:s(e.overrides),updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:0}},Qt=Object.freeze(Object.entries(yC).sort(([,e],[,t])=>e-t).map(([e,t])=>Object.freeze({name:e,value:t}))),Vf=5,iO=8,aO=e=>Math.max(-100,Math.min(100,e)),AD=(e,{snap:t=!0}={})=>{if(!Number.isFinite(e))return 0;const n=aO(Math.round(e/Vf)*Vf);if(!t)return n;for(const{value:r}of Qt)if(Math.abs(e-r)<=iO)return r;return n},cO=e=>Qt.find(t=>t.value===e)?.name??null,ID=e=>{let t=Qt[2];for(const n of Qt){const r=Math.abs(n.value-e),o=Math.abs(t.value-e);(r<o||r===o&&Math.abs(n.value)<Math.abs(t.value))&&(t=n)}return t.name},RD=e=>{if(cO(e))return null;for(let t=1;t<Qt.length;t++)if(e<Qt[t].value)return[Qt[t-1].name,Qt[t].name];return null},xD=(e,t)=>{const r=(t>0?Qt:[...Qt].reverse()).find(o=>t>0?o.value>e:o.value<e);return r?r.value:e},lO=[[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"]],Gl=8,zl=e=>{const[t,n,r]=ae(e),o=Math.atan2(r,n)*180/Math.PI;return{L:t,C:Math.hypot(n,r),h:o<0?o+360:o}},TD=e=>{const{C:t,h:n}=zl(e);if(t<Gl)return"neutral";for(const[r,o]of lO)if(n<r)return o;return"pink"},CD=(e,t,n)=>{const r=e.find(l=>l.id===n)?.palette.accent,o=e.filter(l=>l.palette.mode===t&&l.id!==n&&typeof l.palette.accent=="string"&&l.palette.accent.toUpperCase()!==r?.toUpperCase()),s=new Map;let a=null;for(const l of o){const{C:d,h:u}=zl(l.palette.accent);if(d<Gl){(!a||d<a.C)&&(a={...l,C:d});continue}const f=Math.floor(u/36),h=Math.abs(u-(f*36+18)),m=s.get(f);(!m||h<m.off||h===m.off&&l.id<m.id)&&s.set(f,{...l,off:h})}const c=[...s.entries()].sort(([l],[d])=>l-d).map(([,l])=>({id:l.id,hex:l.palette.accent.toUpperCase()}));return a&&c.push({id:a.id,hex:a.palette.accent.toUpperCase()}),c},OD=(e,t)=>{const n=new Set,r=[];for(const s of e){if(s.palette.mode!==t)continue;const a=String(s.palette.accent).toUpperCase();n.has(a)||(n.add(a),r.push({id:s.id,hex:a}))}const o=s=>{const{C:a,h:c}=zl(s);return a<Gl?1e3:c};return r.sort((s,a)=>o(s.hex)-o(a.hex))},dO=40,Ls=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return{};const n={};for(const r of Array.isArray(t)?t:[]){const o=e[r];if(typeof o!="string")continue;const s=[...o].map(a=>{const c=a.codePointAt(0)??0;return c<32||c===127?" ":a}).join("").replace(/\s+/g," ").trim().slice(0,dO);s&&(n[r]=s)}return n},PD=Object.freeze({strip:"lo-preview",chip:e=>`lo-preview-${e}`}),MD=(e,t,n=null)=>{const r=[];for(const{id:o,contrast:s}of t){if(!Mc(o))continue;const a=s===0?e:Wg(e,s),c=n?{...a,...n}:a;Object.entries(c).every(([d,u])=>d==="mode"||jc(u))&&r.push(np(o,c))}return r.join(`
65
- `)},jD=e=>{const[t,n,r]=ae(e),o=Math.atan2(r,n)*180/Math.PI;return{l:t,c:Math.hypot(n,r),h:o<0?o+360:o}},$D=({l:e,c:t,h:n})=>{const r=Math.max(0,Math.min(100,e)),o=n*Math.PI/180;for(let s=Math.max(0,t);s>=0;s-=1){const a=ii([r,s*Math.cos(o),s*Math.sin(o)]);if(a)return a}return ii([r,0,0])??"#000000"},ND=e=>{const t=oe("#FFFFFF",e),n=oe("#000000",e);return t>=n?{ink:"#FFFFFF",ratio:t}:{ink:"#000000",ratio:n}},DD=Object.freeze(["accent","accentHover","accentActive","accentWash","onAccent","chartBarHover","accentAlt","accentAltWash"]),Zf=64,xc=["canvas","run","browser","console","code"],uO={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function Yg(e){return typeof e=="string"&&xc.includes(e)}function Kl(e){return e.startsWith("draft:")}function ns(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function Vl(e){return e.length>Zf?e.slice(e.length-Zf):e}function Jg(e,t,n){return Vl([...e.filter(([r])=>r!==t),[t,n]])}function fO(e,t,n){return ns(e,t)!==n?e:e.filter(([r])=>r!==t)}function pO(e,t){return ns(e,t)===void 0?e:e.filter(([n])=>n!==t)}function hO(e,t,n){const r=ns(e,t);return r===void 0?e:Vl([...e.filter(([o])=>o!==t&&o!==n),[n,r]])}const Yf=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function Jf(e,t,n){if(n||typeof t!="string")return Yf;const r=ns(e,t);return r===void 0?Yf:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function mO(e){if(!Array.isArray(e))return[];const t=new Map;for(const n of e){if(!Array.isArray(n)||n.length!==2)continue;const[r,o]=n;typeof r!="string"||r===""||Kl(r)||Yg(o)&&(t.delete(r),t.set(r,o))}return Vl([...t.entries()])}function LD(e){const t=new Set(Object.keys(e.forgotten));for(const[n,r]of Object.entries(e.archiveFacts))r?.archived===!0&&r.answered===!0&&t.add(n);return t}function Qf(e){return uO[e]}const gO={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},rs=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,Mi=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,_O=e=>{const t=rs(e);return t===null||t==="ask"?null:gO[t]},An=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:Jg(e.rightSlotMemory,n,t)}},so=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=fO(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},bO=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=pO(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},vO=Object.freeze({mounted:!1,session:!1}),Qg=Object.freeze([]);function FD(e,t){const n=rs(t);if(n===null||!Mi(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=io(jl,t.rightSlotWidth);break;case"run":r=io(qf,t.rightSlotWidth);break;case"browser":r=io(EO,t.rightSlotWidth);break;case"console":r=io(AO,t.rightSlotWidth);break;case"code":r=io(qf,t.rightSlotWidth);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,$l(e)):Math.min(r,Math.max(0,e-Pl))}function io(e,t){return Math.min(vg,Math.max(e,t||yO))}function UD(e){const t=rs(e);return t!==null&&Mi(t,e)}function BD(e){const t=rs(e);return t!==null&&Mi(t,e)?t:null}function HD(e){const t=rs(e);return(t==="canvas"||t==="ask")&&Mi(t,e)}const yO=640,Xf=xi,wO=20,kO=4,SO=20,qf=320,EO=480,AO=480,IO=5e3,WD=(e,t)=>e.some(n=>n.surface===t),GD=(e,t=Date.now())=>e.some(n=>t-n.at<IO),RO=[],xO=5,TO=["chatMeasureWidth"],zD=Qo()(_i((e,t)=>({finderFiles:Og,setFinderFiles:n=>e({finderFiles:Ll({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:jg,agentAvatarSize:kg,themeName:i_,contrast:zg,accent:Kg,customAccents:[],customAccentNames:{},customThemeId:null,setContrast:(n,r)=>e(o=>({contrast:{...o.contrast,[n]:Ic(r)}})),setAccent:(n,r)=>e(o=>({accent:{...o.accent,[n]:Rc(r,Oc)}})),addCustomAccent:(n,r)=>e(o=>{const s=oO(o.customAccents,n),a=gt(n),c=Ls(o.customAccentNames,s);return!r||!a?{customAccents:s,customAccentNames:c}:{customAccents:s,customAccentNames:c,accent:{...o.accent,[r]:{kind:"custom",hex:a}}}}),removeCustomAccent:n=>e(r=>{const o=gt(n),s={...r.accent};for(const c of Kf){const l=s[c];l.kind==="custom"&&l.hex===o&&(s[c]=xn)}const a={...r.customAccentNames};return o&&delete a[o],{customAccents:r.customAccents.filter(c=>c!==o),customAccentNames:a,accent:s}}),renameCustomAccent:(n,r)=>e(o=>{const s=gt(n);return!s||!o.customAccents.includes(s)?{}:{customAccentNames:Ls({...o.customAccentNames,[s]:r},o.customAccents)}}),replaceCustomAccent:(n,r)=>e(o=>{const s=gt(n),a=gt(r);if(!s||!a||s===a)return{};if(o.customAccents.indexOf(s)<0)return{};const l=o.customAccents.filter(h=>h!==a);l.splice(l.indexOf(s),1,a);const d=Ur(l),u={...o.customAccentNames};u[s]!==void 0&&u[a]===void 0&&(u[a]=u[s]),delete u[s];const f={...o.accent};for(const h of Kf){const m=f[h];m.kind==="custom"&&m.hex===s&&(f[h]={kind:"custom",hex:a})}return{customAccents:d,customAccentNames:Ls(u,d),accent:f}}),rightSlotWidth:0,chatSidebarWidth:Xf,chatSidebarRegions:IT,chatSidebarView:wr,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:Qg,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:vO,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:RO,isCreateAgentDialogOpen:!1,mentionRecents:null,profileRecents:{agent:[],team:[]},conversationRecents:[],shortcutBindings:{},openCreateAgentDialog:()=>{e({isCreateAgentDialogOpen:!0})},closeCreateAgentDialog:()=>{e({isCreateAgentDialogOpen:!1})},openCommandPalette:()=>{e({isCommandPaletteOpen:!0})},closeCommandPalette:()=>{e({isCommandPaletteOpen:!1,commandPaletteQuery:""})},toggleCommandPalette:(n="")=>{e(r=>({isCommandPaletteOpen:!r.isCommandPaletteOpen,commandPaletteQuery:r.isCommandPaletteOpen?r.commandPaletteQuery:n}))},setCommandPaletteQuery:n=>{e({commandPaletteQuery:n})},toggleSidebar:()=>{e(n=>({isSidebarCollapsed:!n.isSidebarCollapsed}))},setSidebarOverflowExpanded:n=>{e({sidebarOverflowExpanded:n})},setSidebarCollapsed:n=>{e({isSidebarCollapsed:n})},setShowAgentReasoning:n=>{e({showAgentReasoning:n})},setTranscriptDisplayMode:n=>{e({transcriptDisplayMode:n})},setAgentAvatarSize:n=>{e({agentAvatarSize:n})},setTheme:n=>{e({themeName:n,customThemeId:null})},setCanvasOpen:n=>{e(r=>n?{...An("isCanvasOpen"),...Wn(r,"canvas")}:{isCanvasOpen:!1,...so(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...An("isRunPanelOpen"),...Wn(r,"run")}:{isRunPanelOpen:!1,...so(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...An("isBrowserPaneOpen"),...Wn(r,"browser")}:{isBrowserPaneOpen:!1,...so(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...An("isConsolePaneOpen"),...Wn(r,"console")}:{isConsolePaneOpen:!1,...so(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...An("isCodeReviewPaneOpen"),...Wn(r,"code")}:{isCodeReviewPaneOpen:!1,...so(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...An("isCodeReviewPaneOpen"),...Wn(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,o)=>{e(s=>{const a=typeof s.rightSlotKey=="string";if(n)return{...An("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:a?null:_O(s),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?o?.dismissSlot?{...c,...bO(s)}:{...c,...Jf(s.rightSlotMemory,s.rightSlotKey,!1)}:s.rightSlotKey===null?o?.dismissSlot?{...c,rightSlotLegacySeed:null}:c:o?.dismissSlot?{...c,rightSlotLegacySeed:null}:{...c,...s.askDrawerEvictedPane===null?null:{[s.askDrawerEvictedPane]:!0}}})},requestAskOpen:(n,r="menu")=>{e({askOpenIntent:{scope:n,via:r}})},clearAskOpenIntent:n=>{e(r=>r.askOpenIntent?.scope===n?{askOpenIntent:null}:{})},setConsoleActiveSurface:n=>{e({consoleActiveSurface:n})},requestConsoleOpen:n=>{e({consoleOpenIntent:n})},clearConsoleOpenIntent:n=>{e(r=>r.consoleOpenIntent===n?{consoleOpenIntent:null}:{})},setConsoleLiveSurface:(n,r)=>{e(o=>{if(n===null||r<=0)return o.consoleLiveSurface===null?{}:{consoleLiveSurface:null};const s=o.consoleLiveSurface;return s?.sessionId===n&&s.count===r?{}:{consoleLiveSurface:{sessionId:n,count:r}}})},markConsoleUnseen:(n,r)=>{e(o=>o.consoleUnseen.some(s=>s.surface===r)?{}:{consoleUnseen:[...o.consoleUnseen,{sessionId:n,surface:r,at:Date.now()}]})},clearConsoleUnseen:n=>{const r=Array.isArray(n)?n:[n];e(o=>{const s=o.consoleUnseen.filter(a=>!r.includes(a.surface));return s.length===o.consoleUnseen.length?{}:{consoleUnseen:s}})},setRightSlotWidth:n=>{e({rightSlotWidth:n})},restoreDefaultRightSlotWidth:()=>{e({rightSlotWidth:0})},bindRightSlotKey:(n,r)=>{e(o=>{let s=o.rightSlotMemory,a=o.rightSlotLegacySeed;const c=r?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(s=hO(s,c,n)),n===null||(Kl(n)?a=null:a!==null&&ns(s,n)===void 0&&(s=Jg(s,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:s,rightSlotLegacySeed:a,...Jf(s,n,o.isAskDrawerOpen)}})},setRightSlotRoute:n=>{const r=t().rightSlotRoute;r.mounted===n.mounted&&r.session===n.session||e({rightSlotRoute:{...n}})},setShortcutBinding:(n,r,o)=>{if(r===null){e(a=>{const c={...a.shortcutBindings};return delete c[n],{shortcutBindings:c}});return}const s=Ul(r);s!==null&&BT(s,n,t().shortcutBindings,"linux",o)===null&&e(a=>({shortcutBindings:{...a.shortcutBindings,[n]:s}}))},clearShortcutBinding:n=>{e(r=>({shortcutBindings:{...r.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(r=>({...An("isRunPanelOpen"),...Wn(r,"run"),runPanelReveal:{section:n,nonce:(r.runPanelReveal?.nonce??0)+1}}))},clearRunPanelReveal:n=>{e(r=>r.runPanelReveal?.nonce===n?{runPanelReveal:null}:{})},setChatSidebarWidth:n=>{e({chatSidebarWidth:Math.min(Ol,Math.max(Cl,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:Xf})},rememberMention:(n,r)=>{e(o=>{const s=o.mentionRecents,a=s?.cwd===n?s.paths:[],c=[r,...a.filter(l=>l!==r)].slice(0,wO);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(o=>({profileRecents:{...o.profileRecents,[n]:CO(o.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const o=MO(r.conversationRecents),s=OO(o,n);return s.length===o.length&&s.every((a,c)=>a===o[c])?r:{conversationRecents:s}})}}),{name:"ui-preferences-storage",version:xO,migrate:DO,partialize:jO,merge:NO}));function CO(e,t){return[t,...e.filter(n=>n!==t)].slice(0,kO)}function OO(e,t){return[t,...e.filter(n=>n!==t)].slice(0,SO)}const PO=[];function MO(e){return Array.isArray(e)?e:PO}function jO(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:r,consoleLiveSurface:o,askOpenIntent:s,isAskDrawerOpen:a,askDrawerScope:c,askDrawerEvictedPane:l,rightSlotRoute:d,isCanvasOpen:u,isRunPanelOpen:f,isBrowserPaneOpen:h,isConsolePaneOpen:m,isCodeReviewPaneOpen:y,rightSlotKey:b,...v}=e;return{...v,rightSlotMemory:$O(e.rightSlotMemory)}}function $O(e){return(e??Qg).filter(([t])=>!Kl(t))}function NO(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:o,isBrowserPaneOpen:s,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:Ll(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:mO(n.rightSlotMemory),rightSlotLegacySeed:Yg(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:HT(n.shortcutBindings),contrast:Vg(n.contrast),accent:Zg(n.accent,Oc),customAccents:Ur(n.customAccents),customAccentNames:Ls(n.customAccentNames,Ur(n.customAccents)),customThemeId:Wl(n.customThemeId)}}function DO(e,t){const n={...e??{}};if(t<1&&LO(n),t<2)for(const r of TO)delete n[r];if(t<3){let r=null;for(const o of xc)if(n[Qf(o)]===!0){r=o;break}r!==null&&(n.rightSlotLegacySeed=r);for(const o of xc)delete n[Qf(o)]}return t<4&&(n.finderFiles=Ll(n.finderFiles)),t<5&&(n.contrast=Vg(n.contrast),n.accent=Zg(n.accent,Oc),n.customAccents=Ur(n.customAccents),n.customThemeId=Wl(n.customThemeId)),n}function LO(e){const t=[["canvasWidth",800],["runPanelWidth",420],["browserPanelWidth",640],["consolePanelWidth",796]];let n=0;for(const[r,o]of t){const s=e[r];if(typeof s=="number"&&s>0&&s!==o){n=s;break}}for(const[r]of t)delete e[r];e.rightSlotWidth=n}const Tc=e=>e.replace(/\\/g,"/"),KD=()=>window.location.hash?Tc(window.location.hash.substring(1)):Tc(window.location.pathname),VD=(e,t)=>{if(t!==null&&(e===t||e.startsWith(`${t}/`)||e.startsWith(`${t}\\`))){const r=e.substring(t.length);return r.startsWith("/")||r.startsWith("\\")||r===""?`~${r.replace(/\\/g,"/")}`:`~/${r.replace(/\\/g,"/")}`}return e==="~"?"~":e.replace(/\\/g,"/")},ZD=(e,t)=>{if(e.length<=t)return e;const n=e.split("/"),r=n[n.length-1]??"";if(r.length+1>=t)return`…${r.slice(-39)}`;const o=n[0]==="~"||n[0]==="",s=o?n.slice(0,2):n.slice(0,1),a=n.slice(s.length),c=y=>{const b=t-y.length-(y?3:2);let v=[];for(let p=a.length-1;p>=0;p-=1){const A=[a[p],...v];if(A.join("/").length>b)break;v=A}return v},l=(y,b)=>y?`${y}/…/${b.join("/")}`:`…/${b.join("/")}`,d=s.join("/"),u=c(d);if(u.length>0)return u.length===a.length?e:l(d,u);const f=o?n[0]:"",h=c(f);if(h.length>0)return l(f,h);const m=t-(f?`${f}/…/`.length:2);return m>0?l(f,[r.slice(-m)]):"…"},YD=(e,t)=>Tc(e).includes(t),Cc=e=>{const t=JSON.stringify(Object.keys(e).sort().map(r=>[r,e[r]]));let n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n.toString(36).padStart(7,"0").slice(-8)},FO=(e,{contrast:t=0,accent:n={kind:"theme"},id:r,paletteAccent:o,preserveSecondary:s=!1}={})=>{const a=!n||n.kind==="theme";if(t===0&&a)return{identity:!0,palette:e,id:r,effectiveContrast:0,requestedContrast:0,accentApplied:!0,accentAdjusted:0};const c=VC(e,t,{id:r});let l=c.palette,d=!0,u=0;if(!a){const f=eO(l,n,{authored:e,id:r,paletteAccent:o,preserveSecondary:s});l=f.palette,d=f.applied,u=f.adjusted}return l===e?{identity:!0,palette:e,id:r,effectiveContrast:0,requestedContrast:t,accentApplied:d,accentAdjusted:u}:{identity:!1,palette:l,id:`lo-${Cc(l)}`,effectiveContrast:c.effectiveContrast,requestedContrast:t,accentApplied:d,accentAdjusted:u}},ep="lo-composed-theme",UO=4,Gn=new Map,BO=(e,t)=>{const n=Gn.get(e);if(n)return Gn.delete(e),Gn.set(e,n),n;const r=a_(t);if(Gn.set(e,r),Gn.size>UO){const o=Gn.keys().next().value;o!==void 0&&Gn.delete(o)}return r},HO=e=>Pc(e)?.palette.accent,WO=16,_r=new Map,GO=(e,t,n)=>{const r=tp(e.themeName),o=Pc(r.id);if(!o)throw new Error(`no palette for theme ${r.id}`);const s=t??o.palette,a=s.mode,c=n??r.id,l=e.contrast[a]??0,d=e.accent[a],u=JSON.stringify([r.id,n??null,t?Cc(t):null,l,d??null]);let f=_r.get(u);if(f?_r.delete(u):f=FO(s,{contrast:l,accent:d,id:c,preserveSecondary:t!==void 0,paletteAccent:HO}),_r.set(u,f),_r.size>WO){const m=_r.keys().next().value;m!==void 0&&_r.delete(m)}if(f.identity&&!n)return{...f,id:r.id,muiTheme:r.theme};const h=`lo-${Cc(f.palette)}`;return{...f,id:h,identity:!1,muiTheme:BO(h,f.palette)}},zO=(e,t)=>Mc(e)&&Object.entries(t).every(([n,r])=>n==="mode"||jc(r))&&(t.mode==="dark"||t.mode==="light"),JD=(e,t=document,n,r,o=s=>GO(s,n,r))=>{let s=o(e);if(!s.identity&&!zO(s.id,s.palette)){console.error(`[theme] refused to publish composed theme ${JSON.stringify(s.id).slice(0,60)}: an id or value is outside the CSS grammar; showing the built-in theme`);const l=tp(e.themeName),d=Pc(l.id);if(!d)throw new Error(`no palette for theme ${l.id}`);s={identity:!0,palette:d.palette,id:l.id,effectiveContrast:0,requestedContrast:s.requestedContrast,accentApplied:!1,accentAdjusted:0,muiTheme:l.theme}}const a=t.documentElement,c=t.getElementById(ep);if(s.identity)c?.remove();else{const l=c??t.createElement("style");l.id=ep,l.textContent=np(s.id,s.palette),c||t.head.appendChild(l)}return Zx(t,s.identity?null:s.palette),a.dataset.theme=s.id,a.classList.toggle("dark",s.palette.mode==="dark"),s},QD=e=>({themeName:e.themeName,customThemeId:e.customThemeId??null,contrast:e.contrast,accent:e.accent}),XD=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{R$ as $,XR as A,JR as B,JD as C,_D as D,QD as E,zD as F,ct as G,OT as H,XD as I,GO as J,Qo as K,dP as L,i as M,zp as N,xe as O,Gd as P,CR as Q,OR as R,mt as S,x$ as T,Hm as U,$m as V,S$ as W,A$ as X,Nm as Y,E$ as Z,y$ as _,qP as a,gt as a$,k$ as a0,I$ as a1,pN as a2,WP as a3,KD as a4,ia as a5,Ej as a6,BP as a7,HP as a8,Zm as a9,_P as aA,Lp as aB,Tc as aC,j0 as aD,lP as aE,AM as aF,pP as aG,_v as aH,fP as aI,hP as aJ,XO as aK,ap as aL,Di as aM,Bc as aN,fv as aO,uv as aP,rI as aQ,bR as aR,Ij as aS,xj as aT,Tj as aU,Sm as aV,AN as aW,K1 as aX,EN as aY,V1 as aZ,Z1 as a_,Q$ as aa,X$ as ab,Ri as ac,kN as ad,MO as ae,bn as af,it as ag,Hr as ah,Ac as ai,YO as aj,$w as ak,f$ as al,e$ as am,vP as an,QO as ao,He as ap,Ua as aq,_i as ar,Qv as as,mo as at,QP as au,GP as av,ay as aw,cy as ax,Jd as ay,bP as az,VP as b,mn as b$,nO as b0,TD as b1,ND as b2,dO as b3,aN as b4,cO as b5,ID as b6,Qt as b7,PD as b8,Vf as b9,Z_ as bA,vd as bB,V_ as bC,z_ as bD,iN as bE,gx as bF,J$ as bG,U$ as bH,YD as bI,cP as bJ,aP as bK,iP as bL,sP as bM,uP as bN,kv as bO,Lt as bP,vo as bQ,Hp as bR,Lv as bS,Lw as bT,JP as bU,$P as bV,YP as bW,ZP as bX,BD as bY,vD as bZ,Qj as b_,AD as ba,RD as bb,xD as bc,CD as bd,OD as be,MD as bf,DD as bg,eS as bh,cx as bi,XP as bj,Dg as bk,FO as bl,jD as bm,wD as bn,RT as bo,mD as bp,Yo as bq,ot as br,op as bs,j_ as bt,L_ as bu,B_ as bv,K_ as bw,W_ as bx,G_ as by,bd as bz,Ji as c,BN as c$,Rd as c0,Wc as c1,by as c2,mi as c3,Op as c4,xR as c5,w$ as c6,ce as c7,v$ as c8,yr as c9,zN as cA,KN as cB,bT as cC,wf as cD,jN as cE,oD as cF,sD as cG,iD as cH,MN as cI,Ym as cJ,sN as cK,aD as cL,VN as cM,QN as cN,XN as cO,ZN as cP,YN as cQ,wr as cR,CN as cS,Cg as cT,FN as cU,nD as cV,Ko as cW,tD as cX,rD as cY,jr as cZ,uf as c_,lc as ca,dc as cb,_$ as cc,b$ as cd,p$ as ce,h$ as cf,m$ as cg,yD as ch,GD as ci,IO as cj,WD as ck,Fp as cl,NP as cm,xP as cn,Bp as co,Iw as cp,Rv as cq,v_ as cr,xv as cs,Dl as ct,OP as cu,cf as cv,DP as cw,ax as cx,j$ as cy,VD as cz,Qe as d,rN as d$,UN as d0,HN as d1,GN as d2,WN as d3,$N as d4,qN as d5,eD as d6,RN as d7,xN as d8,T$ as d9,gD as dA,oP as dB,dI as dC,rM as dD,UD as dE,vc as dF,vO as dG,io as dH,FD as dI,_N as dJ,bN as dK,gN as dL,jl as dM,$l as dN,jP as dO,MP as dP,EO as dQ,vg as dR,AO as dS,qf as dT,Pl as dU,kj as dV,Sj as dW,tN as dX,eN as dY,nN as dZ,oN as d_,O$ as da,ON as db,C$ as dc,Ti as dd,PN as de,q$ as df,Tg as dg,JN as dh,DN as di,LN as dj,NN as dk,TN as dl,cD as dm,lD as dn,fD as dp,pD as dq,AT as dr,dD as ds,Ts as dt,Vo as du,uD as dv,hD as dw,mP as dx,SN as dy,ZD as dz,eM as e,Y_ as e$,n0 as e0,es as e1,KP as e2,hp as e3,kl as e4,Xj as e5,Pj as e6,c$ as e7,l$ as e8,Km as e9,r$ as eA,Eh as eB,Zs as eC,TM as eD,Ln as eE,nr as eF,Av as eG,bD as eH,Da as eI,wN as eJ,mN as eK,D1 as eL,yg as eM,tM as eN,nM as eO,R_ as eP,CT as eQ,nP as eR,Kl as eS,LD as eT,md as eU,tP as eV,eP as eW,Ra as eX,ko as eY,O_ as eZ,H_ as e_,tx as ea,Ei as eb,V$ as ec,Z$ as ed,B0 as ee,qj as ef,$j as eg,F$ as eh,aR as ei,ZR as ej,zm as ek,KR as el,rf as em,B$ as en,G1 as eo,K$ as ep,g$ as eq,SP as er,AP as es,EP as et,UP as eu,Oi as ev,Pi as ew,Ng as ex,BT as ey,Fl as ez,Nw as f,$D as f$,zS as f0,cN as f1,dr as f2,ug as f3,dN as f4,S1 as f5,cg as f6,lN as f7,fN as f8,hN as f9,Qh as fA,jg as fB,Ch as fC,ow as fD,TP as fE,Aj as fF,Rj as fG,jj as fH,Mj as fI,Cj as fJ,oI as fK,Lj as fL,Dj as fM,Ar as fN,PP as fO,LP as fP,CP as fQ,xM as fR,RM as fS,fM as fT,el as fU,Jc as fV,Dn as fW,qt as fX,ui as fY,kD as fZ,ED as f_,FP as fa,zP as fb,gi as fc,At as fd,M_ as fe,sx as ff,HD as fg,yN as fh,Ml as fi,vN as fj,bg as fk,B1 as fl,Cl as fm,IP as fn,Od as fo,ew as fp,RP as fq,Pv as fr,t$ as fs,Wj as ft,Gj as fu,wP as fv,kP as fw,Hj as fx,Em as fy,iI as fz,Kc as g,gM as g$,Hl as g0,bC as g1,vC as g2,Gg as g3,SD as g4,Wl as g5,zM as g6,Su as g7,YM as g8,ZM as g9,hj as gA,bE as gB,ta as gC,fj as gD,kE as gE,aj as gF,XM as gG,sj as gH,_j as gI,QM as gJ,ij as gK,lj as gL,vj as gM,bj as gN,cj as gO,qM as gP,ej as gQ,tj as gR,nj as gS,rj as gT,oj as gU,gj as gV,Tv as gW,Cv as gX,Ov as gY,pu as gZ,JM as g_,VM as ga,KM as gb,jS as gc,Vk as gd,Gk as ge,Zk as gf,Cr as gg,WM as gh,HM as gi,NM as gj,CM as gk,OM as gl,MM as gm,PM as gn,Oh as go,UM as gp,K0 as gq,yj as gr,lk as gs,BM as gt,wE as gu,pj as gv,zh as gw,mj as gx,dj as gy,uj as gz,pp as h,a0 as h$,LM as h0,kS as h1,Th as h2,ph as h3,yM as h4,Md as h5,Ul as h6,TT as h7,x0 as h8,$M as h9,D$ as hA,P$ as hB,M$ as hC,L$ as hD,Nl as hE,X1 as hF,yP as hG,rc as hH,Oj as hI,o$ as hJ,s$ as hK,a$ as hL,nI as hM,i$ as hN,d$ as hO,_R as hP,u$ as hQ,Vw as hR,$$ as hS,rh as hT,Do as hU,hM as hV,y0 as hW,oh as hX,Qc as hY,eh as hZ,i0 as h_,vS as ha,FM as hb,GM as hc,DM as hd,ak as he,bM as hf,q0 as hg,wM as hh,kM as hi,EM as hj,SM as hk,IM as hl,jM as hm,wj as hn,IN as ho,Vj as hp,zj as hq,vI as hr,Yj as hs,Kj as ht,Zj as hu,Jj as hv,_M as hw,vM as hx,Xn as hy,N$ as hz,Vv as i,uM as i0,Ev as i1,dM as i2,iM as i3,cM as i4,cu as i5,sM as i6,oM as i7,lM as i8,lu as i9,aM as ia,$p as ib,mM as ic,pM as id,G$ as ie,Nj as ig,Bj as ih,Fj as ii,Uj as ij,H$ as ik,W$ as il,pv as im,Pd as io,qO as ip,n$ as iq,Zv as j,Yv as k,Jv as l,JO as m,u_ as n,J_ as o,gP as p,uN as q,Fw as r,w1 as s,Gw as t,D_ as u,rP as v,px as w,St as x,z$ as y,Y$ as z};
64
+ */function zo(){return zo=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},zo.apply(this,arguments)}const Tl=R.createContext(null),w1=R.createContext(null),dr=R.createContext(null),Ri=R.createContext(null),vn=R.createContext({outlet:null,matches:[],isDataRoute:!1}),hg=R.createContext(null);function fN(e,t){let{relative:n}=t===void 0?{}:t;Wr()||ze(!1);let{basename:r,navigator:o}=R.useContext(dr),{hash:s,pathname:a,search:c}=E1(e,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:Pn([r,a])),o.createHref({pathname:l,search:c,hash:s})}function Wr(){return R.useContext(Ri)!=null}function xi(){return Wr()||ze(!1),R.useContext(Ri).location}function mg(e){R.useContext(dr).static||R.useLayoutEffect(e)}function k1(){let{isDataRoute:e}=R.useContext(vn);return e?N1():S1()}function S1(){Wr()||ze(!1);let e=R.useContext(Tl),{basename:t,future:n,navigator:r}=R.useContext(dr),{matches:o}=R.useContext(vn),{pathname:s}=xi(),a=JSON.stringify(Rl(o,n.v7_relativeSplatPath)),c=R.useRef(!1);return mg(()=>{c.current=!0}),R.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=xl(d,JSON.parse(a),s,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:Pn([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,a,s,e])}function pN(){let{matches:e}=R.useContext(vn),t=e[e.length-1];return t?t.params:{}}function E1(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=R.useContext(dr),{matches:o}=R.useContext(vn),{pathname:s}=xi(),a=JSON.stringify(Rl(o,r.v7_relativeSplatPath));return R.useMemo(()=>xl(e,JSON.parse(a),s,n==="path"),[e,a,s,n])}function A1(e,t){return I1(e,t)}function I1(e,t,n,r){Wr()||ze(!1);let{navigator:o,static:s}=R.useContext(dr),{matches:a}=R.useContext(vn),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=xi(),f;if(t){var h;let p=typeof t=="string"?lr(t):t;d==="/"||(h=p.pathname)!=null&&h.startsWith(d)||ze(!1),f=p}else f=u;let m=f.pathname||"/",y=m;if(d!=="/"){let p=d.replace(/^\//,"").split("/");y="/"+m.replace(/^\//,"").split("/").slice(p.length).join("/")}let b=Xx(e,{pathname:y}),v=O1(b&&b.map(p=>Object.assign({},p,{params:Object.assign({},l,p.params),pathname:Pn([d,o.encodeLocation?o.encodeLocation(p.pathname).pathname:p.pathname]),pathnameBase:p.pathnameBase==="/"?d:Pn([d,o.encodeLocation?o.encodeLocation(p.pathnameBase).pathname:p.pathnameBase])})),a,n,r);return t&&v?R.createElement(Ri.Provider,{value:{location:zo({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:Cn.Pop}},v):v}function R1(){let e=$1(),t=v1(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,o={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return R.createElement(R.Fragment,null,R.createElement("h2",null,"Unexpected Application Error!"),R.createElement("h3",{style:{fontStyle:"italic"}},t),n?R.createElement("pre",{style:o},n):null,null)}const x1=R.createElement(R1,null);class T1 extends R.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?R.createElement(vn.Provider,{value:this.props.routeContext},R.createElement(hg.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function C1(e){let{routeContext:t,match:n,children:r}=e,o=R.useContext(Tl);return o&&o.static&&o.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(o.staticContext._deepestRenderedBoundaryId=n.route.id),R.createElement(vn.Provider,{value:t},r)}function O1(e,t,n,r){var o;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var s;if(!n)return null;if(n.errors)e=n.matches;else if((s=r)!=null&&s.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,c=(o=n)==null?void 0:o.errors;if(c!=null){let u=a.findIndex(f=>f.route.id&&c?.[f.route.id]!==void 0);u>=0||ze(!1),a=a.slice(0,Math.min(a.length,u+1))}let l=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u<a.length;u++){let f=a[u];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(d=u),f.route.id){let{loaderData:h,errors:m}=n,y=f.route.loader&&h[f.route.id]===void 0&&(!m||m[f.route.id]===void 0);if(f.route.lazy||y){l=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}return a.reduceRight((u,f,h)=>{let m,y=!1,b=null,v=null;n&&(m=c&&f.route.id?c[f.route.id]:void 0,b=f.route.errorElement||x1,l&&(d<0&&h===0?(D1("route-fallback"),y=!0,v=null):d===h&&(y=!0,v=f.route.hydrateFallbackElement||null)));let p=t.concat(a.slice(0,h+1)),A=()=>{let k;return m?k=b:y?k=v:f.route.Component?k=R.createElement(f.route.Component,null):f.route.element?k=f.route.element:k=u,R.createElement(C1,{match:f,routeContext:{outlet:u,matches:p,isDataRoute:n!=null},children:k})};return n&&(f.route.ErrorBoundary||f.route.errorElement||h===0)?R.createElement(T1,{location:n.location,revalidation:n.revalidation,component:b,error:m,children:A(),routeContext:{outlet:null,matches:p,isDataRoute:!0}}):A()},null)}var gg=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(gg||{}),_g=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}(_g||{});function P1(e){let t=R.useContext(Tl);return t||ze(!1),t}function M1(e){let t=R.useContext(w1);return t||ze(!1),t}function j1(e){let t=R.useContext(vn);return t||ze(!1),t}function bg(e){let t=j1(),n=t.matches[t.matches.length-1];return n.route.id||ze(!1),n.route.id}function $1(){var e;let t=R.useContext(hg),n=M1(),r=bg();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function N1(){let{router:e}=P1(gg.UseNavigateStable),t=bg(_g.UseNavigateStable),n=R.useRef(!1);return mg(()=>{n.current=!0}),R.useCallback(function(o,s){s===void 0&&(s={}),n.current&&(typeof o=="number"?e.navigate(o):e.navigate(o,zo({fromRouteId:t},s)))},[e,t])}const wf={};function D1(e,t,n){wf[e]||(wf[e]=!0)}function hN(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function mN(e){let{to:t,replace:n,state:r,relative:o}=e;Wr()||ze(!1);let{future:s,static:a}=R.useContext(dr),{matches:c}=R.useContext(vn),{pathname:l}=xi(),d=k1(),u=xl(t,Rl(c,s.v7_relativeSplatPath),l,o==="path"),f=JSON.stringify(u);return R.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:o}),[d,f,o,n,r]),null}function L1(e){ze(!1)}function gN(e){let{basename:t="/",children:n=null,location:r,navigationType:o=Cn.Pop,navigator:s,static:a=!1,future:c}=e;Wr()&&ze(!1);let l=t.replace(/^\/*/,"/"),d=R.useMemo(()=>({basename:l,navigator:s,static:a,future:zo({v7_relativeSplatPath:!1},c)}),[l,c,s,a]);typeof r=="string"&&(r=lr(r));let{pathname:u="/",search:f="",hash:h="",state:m=null,key:y="default"}=r,b=R.useMemo(()=>{let v=fg(u,l);return v==null?null:{location:{pathname:v,search:f,hash:h,state:m,key:y},navigationType:o}},[l,u,f,h,m,y,o]);return b==null?null:R.createElement(dr.Provider,{value:d},R.createElement(Ri.Provider,{children:n,value:b}))}function _N(e){let{children:t,location:n}=e;return A1(vc(t),n)}new Promise(()=>{});function vc(e,t){t===void 0&&(t=[]);let n=[];return R.Children.forEach(e,(r,o)=>{if(!R.isValidElement(r))return;let s=[...t,o];if(r.type===R.Fragment){n.push.apply(n,vc(r.props.children,s));return}r.type!==L1&&ze(!1),!r.props.index||!r.props.children||ze(!1);let a={id:r.props.id||s.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=vc(r.props.children,s)),n.push(a)}),n}const Ti=260,Cl=220,Ol=320,vg=56,Pl=480,bN=8,Ml=44,jl=400,yg=1200;function $l(e){return Math.max(0,Math.min(yg,e-Pl))}function yc(e){return $l(e)>=jl?"docked":"overlay"}const F1=48,U1=16;function vN(e,t){if(yc(e)==="docked")return{mode:"docked",width:Math.min(t,$l(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,jl),e-F1));return e-n>=U1?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function yN({capacity:e,min:t,max:n,drawn:r}){const o=e>=t;return o?{resizable:o,value:Math.min(Math.max(r,t),e),minWidth:t,maxWidth:Math.min(n,e)}:{resizable:o,value:r,minWidth:r,maxWidth:r}}function B1(e,t=Ti,n=Ml){return yc(e-wg(t)-n)==="overlay"&&yc(e-vg-n)==="docked"}function wg(e){return Number.isNaN(e)?Ti:Math.min(Ol,Math.max(Cl,e))}function H1(e,t=Ml){return Math.max(0,Math.min(Ol,e-Pl-t))}function wN(e,t,n=Ti,r=!1,o=Ml){const s=!t&&r&&B1(e,n,o),a=t||s,c=H1(e,o);return{mode:a?"strip":"docked",width:a?vg:Math.min(wg(n),c),collapsed:a,resizable:!a&&c>=Cl}}function kN(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const SN=e=>e?"⌘B":"Ctrl+B",W1="data-canvas-shortcuts",G1=`[${W1}]`,z1=e=>kg(e,G1),K1='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',EN=e=>kg(e,K1);function kg(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const AN=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&z1(e.target)?"new-file":null},Sg="small",V1=["small","medium","large"],Eg="before:absolute before:-inset-0.5 before:content-['']",Z1={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:Eg},medium:{px:28,className:"size-7",glyphClassName:"size-3.5",hitClassName:""},large:{px:36,className:"size-9",glyphClassName:"size-4",hitClassName:""}},Y1={small:{px:4,className:"mb-1"},medium:{px:6,className:"mb-1.5"},large:{px:8,className:"mb-2"}},IN={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:Eg,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 RN(e){for(const t of V1)if(e===t)return t;return Sg}function xN(e){return Z1[e].px+Y1[e].px}const Ag="delegating",Ss=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,ka=e=>Math.max(1,Math.floor(e)),J1=e=>e===Ag,Ig=e=>e.locality==="remote"&&e.link_down===!0||e.peer_reach==="not-attempted"||e.peer_reach==="unknown";function Nl(e){return Ig(e)?!1:typeof e.background_work=="boolean"?e.background_work:e.status?.code===Ag}const Q1=Intl.ListFormat;let Sa=null;const X1=e=>{const t=nn();return Sa?.tag!==t&&(Sa={tag:t,format:new Q1(t,{type:"conjunction",style:"narrow"})}),Sa.format.format(e)};function TN(e){if(Ig(e))return"";const t=Nl(e);if(!t&&typeof e.background_work=="boolean")return"";const n=!J1(e.status?.code),r=[];n&&Ss(e.subagents_running)&&r.push(_("ui.chat.sidebar.row.bg.subagents",{count:ka(e.subagents_running)})),t&&Ss(e.jobs_running)&&r.push(_("ui.chat.sidebar.row.bg.jobs",{count:ka(e.jobs_running)}));const o=[];if(r.length>0&&o.push(_("ui.chat.sidebar.row.bg.running",{items:X1(r)})),n&&Ss(e.subagents_queued)){const s=ka(e.subagents_queued);o.push(r.length>0?_("ui.chat.sidebar.row.bg.queued",{count:s}):_("ui.chat.sidebar.row.bg.subagents_queued",{count:s}))}return t&&o.length===0&&e.status?.code!=="waiting"&&Ss(e.waiting_on)&&o.push(_("ui.chat.sidebar.row.bg.waiting")),o.join(" · ")}const q1=new Set(["idle","recent"]);function CN(e,t){return t!==""&&q1.has(e.status?.code??"recent")&&Nl(e)}const eT=["active","created"],ON={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"},tT=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function Ci(e){return tT.has(e.status?.code??"")||Nl(e)}const nT=new Set(["approval","answer"]);function Rg(e){return nT.has(e.status?.code??"")}const rT=24*60*60*1e3,oT=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function Dl(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 sT="last_user_at";function iT(e){const t=e[sT],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 aT(e,t,n){if(Ci(e))return"running";const r=Dl(e,n);if(r===null)return"older";const o=oT(t);return r>=o?"today":r>=o-6*rT?"week":"older"}function PN(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const o of e)r[aT(o,t,n)].push(o);return r}function xg(e,t,n){const r=Dl(e,n);if(r===null)return null;const o=Math.floor(Math.max(0,t-r)/6e4);if(o<1)return{unit:"now",count:0};if(o<60)return{unit:"minute",count:o};const s=Math.floor(o/60);if(s<24)return{unit:"hour",count:s};const a=Math.floor(s/24);return a<7?{unit:"day",count:a}:a<365?{unit:"week",count:Math.floor(a/7)}:{unit:"year",count:Math.floor(a/365)}}function MN(e,t,n){const r=xg(e,t,n);return r?_("ui.chat.sidebar_view.relative_short",r):""}function jN(e,t,n){const r=xg(e,t,n);return r?n==="created"?_("ui.chat.sidebar_view.relative_created",r):_("ui.chat.sidebar_view.relative_active",r):""}const wc=["pinned","running","today","week","older","agents","teams"],$N={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 NN(e){return e==="agents"||e==="teams"}const Ko=8;function cT(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function DN(e,t){return{...e,[t]:(e[t]??Ko)+Ko}}function LN(e,t,n,r,o){const s=!(e[n]??r);return{expanded:{...e,[n]:s},caps:!s&&!o?cT(t,n):t}}function Tg(e){return`tag:${e}`}function Cg(e,t){return e[Tg(t)]===!1}function FN(e,t){const n=Tg(t);if(Cg(e,t)){const{[n]:r,...o}=e;return o}return{...e,[n]:!1}}function UN(e,t,n){return Cg(t,n)?[]:e}function BN(e,t,n,r){return(e||t!=="")&&(r>Ko||n.trim()!=="")}const HN="Collapse, then reopen, to restore the compact list";function WN(e){return(e??Ko)>Ko}const GN=e=>`section-grown-hint-${e}`,zN=e=>_("ui.chat.sidebar.catalogue.show_more",{hidden:e});function KN(e,t){return t==="agents"?_("ui.chat.sidebar.catalogue.show_more_agents",{count:e}):_("ui.chat.sidebar.catalogue.show_more_teams",{count:e})}function VN(e,t){return e.groupBy==="tag"&&!t?"section":e.groupBy}function ZN(e){return e.tagsEnabled||e.groupBy==="tag"}const wr={hidden:[],order:[...wc],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},lT=10,no=[25,50],dT=50,uT=500,fT=64,pT=2;function YN(e){return e.groupBy==="tag"?Math.max(e.loads,pT):e.loads}function jr(e){const t=Math.max(0,Math.floor(e));return t===0?lT:t<=no.length?no[t-1]:no[no.length-1]+(t-no.length)*dT}function JN(e,t){const n=jr(e+1)-jr(e),r=Math.max(0,Math.min(n,t));return _("ui.chat.sidebar.catalogue.show_more_chats",{add:r})}function QN(e,t,n){const r=jr(t+1)-jr(t),o=jr(t),s=Math.min(o+r,e.length);let a=0;for(let l=o;l<s;l+=1)Oi(e[l])&&(a+=1);const c=Math.max(0,s-o-a);return c>0?c:Math.max(0,Math.min(r,n))}function XN(e,t){if(!t)return null;const n=e.filter(r=>Oi(r));return n.length===0?null:{row:n.find(r=>Rg(r))??n[0],count:n.length}}function Oi(e){return Ci(e)}function hT(e){return Rg(e)?0:Ci(e)?1:2}function mT(e,t){return Ci(e)?iT(e):Dl(e,t)}function gT(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function qN(e,t,n){const r=e.map((o,s)=>({row:o,index:s,lane:t==="active-first"?hT(o):0,at:mT(o,n)}));return r.sort((o,s)=>o.lane-s.lane||gT(o.at,s.at)||o.index-s.index),r.map(o=>o.row)}function eD(e,t){const{limit:n,currentId:r,searching:o=!1}=t;if(o)return{rows:[...e],lifted:!1,remaining:0};const s=[];let a=Math.max(0,n);for(const d of e){if(a>0){s.push(d),a-=1;continue}Oi(d)&&s.push(d)}const c=Math.max(0,e.length-s.length);if(!r)return{rows:s,lifted:!1,remaining:c};const l=e.find(d=>d.session_id===r)??null;return l===null||s.includes(l)?{rows:s,lifted:!1,remaining:c}:{rows:[l,...s],lifted:!0,remaining:c}}function tD(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=jr(t.loads),r=[];let o=n;for(const l of e){if(Oi(l)){r.push(l);continue}o>0&&(r.push(l),o-=1)}const s=t.currentId,a=s==null?null:e.find(l=>l.session_id===s)??null,c=a!==null&&!r.includes(a);return{rows:c&&a!==null?[a,...r]:r,lifted:c,hidden:e.length-r.length-(c?1:0),held:e.length}}function nD(e){if(e.add<=0)return null;const t=_("ui.chat.sidebar.catalogue.show_more_chats",{add:e.add});if(e.drawn>=e.total)return{label:t,aria:t};const n=`${e.drawn} of ${e.total}`;return{label:`${t} · ${n}`,aria:`${t} · ${n}`}}const _T="mt-4",bT="mt-2";function rD(e){return e?_T:bT}function oD(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function sD(e,t){if(t==="section"||t==="tag")return null;if(t==="flat")return[{key:"all",label:"",rows:[...e]}];const n=new Map;for(const s of e){const a=s.binding?.team||s.binding?.agent||"",c=a||"ungrouped",l=n.get(c)??{key:c,label:a||_("ui.chat.sidebar_view.ungrouped"),rows:[]};l.rows.push(s),n.set(c,l)}const r=[...n.values()],o=r.findIndex(s=>s.key==="ungrouped");return o>0&&r.push(...r.splice(o,1)),r}function vT(e,t){return!e.hidden.includes(t)}function Og(e){return e.order.filter(t=>vT(e,t))}function iD(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function aD(e,t,n){const r=Og(e),o=r.indexOf(t),s=r[o+n];if(o<0||s===void 0)return e;const a=e.order.indexOf(t),c=e.order.indexOf(s),l=[...e.order];return l[a]=s,l[c]=t,{...e,order:l}}const yT=["running","today","week","older"];function kf(e){return yT.includes(e)}function cD(e,t,n,r){if(!kf(t)||r&&!r(t))return!1;const o=Og(e),s=o.indexOf(t);if(s<0)return!1;const a=o[s+n];return a===void 0||!kf(a)?!1:r?r(a):!0}const wT=["section","tag","agent","flat"],kT=["active-first","recent"];function lD(e){if(typeof e!="object"||e===null)return wr;const t=e,n=new Set(wc),r=[];if(Array.isArray(t.order))for(const h of t.order)typeof h=="string"&&n.has(h)&&(r.includes(h)||r.push(h));for(const h of wc)r.includes(h)||r.push(h);const o=[];if(Array.isArray(t.hidden))for(const h of t.hidden)typeof h=="string"&&n.has(h)&&(o.includes(h)||o.push(h));const s=wT.includes(t.groupBy)?t.groupBy:wr.groupBy,a=eT.includes(t.basis)?t.basis:wr.basis,c=kT.includes(t.orderBy)?t.orderBy:wr.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(uT,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>=fT)break;d.push(h)}}const u=[],f=new Set;if(Array.isArray(t.pins))for(const h of t.pins)typeof h=="string"&&h.length!==0&&(f.has(h)||(f.add(h),u.push(h)));return{hidden:o,order:r,groupBy:s,tagsEnabled:typeof t.tagsEnabled=="boolean"?t.tagsEnabled:!1,autoTagForks:typeof t.autoTagForks=="boolean"?t.autoTagForks:wr.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const Pg={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},ST=["recent","name","kind","modified","created","size"],ET=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function Ll(e){const t=e&&typeof e=="object"?e:{};return{sort:ST.includes(t.sort??"")?t.sort:Pg.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=>[Vo,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>ET.includes(n)))]:[]}}const Vo="Attachments";function dD(e,t){const n=r=>{switch(t.sort){case"name":return r.row.name;case"kind":return`${r.row.kind}\0${r.row.name}`;case"modified":return r.modified;case"created":return r.created;case"size":return r.row.document.sizeBytes??null;default:return r.mentioned}};return[...e].sort((r,o)=>{const s=n(r),a=n(o);if(s===null||a===null)return s===a?0:s===null?1:-1;const c=typeof s=="string"&&typeof a=="string"?s.localeCompare(a,void 0,{numeric:!0}):Number(s)-Number(a);return(t.order==="asc"?c:-c)||r.mentioned-o.mentioned})}const AT=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 uD(e,t,n,r,o=[]){const s=e.filter(l=>l.highlighted),a=e.filter(l=>!l.highlighted),c=[];if(o.length&&c.push({id:Vo,label:_("ui.canvas.files.attachments"),items:o,open:n||!r.has(Vo),highlights:!1}),s.length&&c.push({id:"Highlights",label:_("ui.canvas.finder_layout.highlights"),items:s,open:n||!r.has("Highlights"),highlights:!0}),s.length&&a.length&&(c.push({id:"Working files",label:_("ui.canvas.finder_layout.working_files"),items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return c;if(!t.group)a.length&&c.push({id:"Files",label:_("ui.canvas.finder_layout.files"),items:a,open:!0,highlights:!1});else for(const l of["Images","Videos","Sounds","Documents","Spreadsheets","Other"]){const d=a.filter(u=>AT(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const IT=32,fD=4,Mg=32,jg=18;function pD(e){return e.height-Mg-(e.kind==="tiles"&&e.section.id===Vo?jg:0)}function hD(e,t,n){const r=[],o=new Map,s=Math.max(136,t-16),a=Math.max(1,Math.floor((s+4)/140));let c=0;const l=(d,u,f,h,m=1)=>{h.forEach((y,b)=>o.set(y.row.document.id,{band:r.length,column:b})),r.push({section:d,kind:u,height:f,top:c,items:h,cols:m}),c+=f};for(const d of e)if(l(d,"header",IT,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(d.id===Vo){const u=d.items.filter(y=>y.row.media!=="image"),f=d.items.filter(y=>y.row.media==="image");for(const y of u)l(d,"compact",36,[y]);const h=(s-4*(a-1))/a,m=Math.round((h-8)*3/4)+Mg+jg;for(let y=0;y<f.length;y+=a)l(d,"tiles",m,f.slice(y,y+a),a)}else if(n&&d.id==="Images"){const u=(s-4*(a-1))/a,f=Math.round((u-8)*3/4)+32;for(let h=0;h<d.items.length;h+=a)l(d,"tiles",f,d.items.slice(h,h+a),a)}else if(n&&d.id==="Videos")for(const u of d.items)l(d,"video",Math.min(Math.round((s-8)*9/16),280)+32,[u]);else if(n&&d.id==="Sounds")for(const u of d.items)l(d,"audio",80,[u]);else for(const u of d.items)l(d,"compact",36,[u]);return{bands:r,height:c,columns:a,positions:o}}function mD(e,t,n,r){const o=Math.max(600,n*.75);let s=0,a=e.bands.length;for(;s<a;){const d=s+a>>>1,u=e.bands[d];u.top+u.height<t-o?s=d+1:a=d}const c=new Set;for(let d=s;d<e.bands.length&&e.bands[d].top<=t+n+o;d++)c.add(d);const l=r?e.positions.get(r):null;return l&&c.add(l.band),[...c].sort((d,u)=>d-u)}function gD(e,t,n,r){const o=e.positions.get(t);if(!o)return null;const s=e.bands[o.band],a=e.bands.filter(u=>u.section.id===s.section.id&&u.items.length);if(n==="Home")return a[0]?.items[0]?.row.document.id??null;if(n==="End")return a.at(-1)?.items.at(-1)?.row.document.id??null;if(n==="ArrowLeft"||n==="ArrowRight")return s.items[o.column+(n==="ArrowLeft"?-1:1)]?.row.document.id??null;const c=n==="ArrowUp"||n==="PageUp"?-1:1,l=s.top+(n.startsWith("Page")?r*c:c);let d=o.band+c;for(;d>=0&&d<e.bands.length;d+=c){const u=e.bands[d];if(u.items.length&&!(n.startsWith("Page")&&(c>0?u.top<l:u.top>l)))return u.items[Math.min(o.column,u.items.length-1)].row.document.id}if(n.startsWith("Page")){const u=e.bands.filter(h=>h.items.length),f=c<0?u[0]:u.at(-1);return f?.items[c<0?0:f.items.length-1]?.row.document.id??null}return null}const RT="both",$g="by-turn",xT=[{value:"by-turn"},{value:"by-response"}];function _D(e){for(const t of xT)if(e===t.value)return t.value;return $g}function bD(e){return e==="by-response"?_("ui.settings.appearance.transcript_display_mode_setting.by_response"):_("ui.settings.appearance.transcript_display_mode_setting.by_turn")}const vD="primary+alt+shift+space",TT=/^f([1-9]|1[0-9]|2[0-4])$/;function CT(e){return TT.test(e)}function OT(e,t){const n=PT(e,t);return t==="mac"?n.join(""):n.join("+")}function PT(e,t){const r=t==="mac"?{primary:"⌘",meta:"⌘",ctrl:"⌃",alt:"⌥",shift:"⇧"}:{primary:"Ctrl",meta:t==="win"?"Win":"Super",ctrl:"Ctrl",alt:"Alt",shift:"Shift"},o={space:"Space",backspace:"Backspace",delete:"Delete",insert:"Insert",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown",up:"Up",down:"Down",left:"Left",right:"Right"};return e.split("+").map(s=>s.trim().toLowerCase()).filter(s=>s.length>0).map(s=>s in r?r[s]:s in o?o[s]:CT(s)||s.length===1?s.toUpperCase():s)}const Pi=[{id:"panel.console",get label(){return _("ui.settings.shortcuts.action.open_console")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return _("ui.settings.shortcuts.action.open_canvas")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return _("ui.settings.shortcuts.action.open_run_details")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return _("ui.settings.shortcuts.action.open_asks")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return _("ui.settings.shortcuts.action.open_browser")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return _("ui.settings.shortcuts.action.open_code_review")},get category(){return _("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],MT=new Map(Pi.map(e=>[e.id,e])),jT=e=>MT.get(e),$T=new Set(["primary+0","primary+r","primary+shift+r","primary+t","primary+shift+t","primary+l",...[1,2,3,4,5,6,7,8,9].map(e=>`primary+${e}`)]);class NT extends Map{copy;constructor(t){super(),this.copy=new Map(t)}get(t){return this.copy.get(t)?.()}has(t){return this.copy.has(t)}get size(){return this.copy.size}*entries(){for(const[t,n]of this.copy)yield[t,n()]}*keys(){yield*this.copy.keys()}*values(){for(const t of this.copy.values())yield t()}forEach(t,n){for(const[r,o]of this)t.call(n,o,r,this)}[Symbol.iterator](){return this.entries()}}const Fl=new NT([["primary+p",()=>_("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>_("ui.settings.shortcuts.reserved.palette_commands")],["primary+k",()=>_("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>_("ui.settings.shortcuts.reserved.new_chat")],["primary+b",()=>_("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>_("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>_("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>_("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>_("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>_("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>_("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>_("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>_("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>_("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>_("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>_("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>_("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>_("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>_("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>_("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>_("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>_("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>_("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>_("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>_("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>_("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>_("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>_("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>_("ui.settings.shortcuts.reserved.browser_last_tab"):()=>_("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>_("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>_("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>_("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>_("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>_("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>_("ui.settings.shortcuts.reserved.close")],["primary+m",()=>_("ui.settings.shortcuts.reserved.minimise")]]),DT=["primary","alt","shift"],LT={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},FT=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),UT=e=>FT.has(e)||/^[a-z0-9]$/.test(e);function Ul(e){if(typeof e!="string")return null;const t=e.toLowerCase().split("+").map(s=>s.trim()).filter(s=>s.length>0);if(t.length===0)return null;const n=t[t.length-1];if(!UT(n))return null;const r=new Set;for(const s of t.slice(0,-1)){const a=LT[s];if(a===void 0)return null;r.add(a)}return[...DT.filter(s=>r.has(s)),n].join("+")}const Ng=e=>e.split("+").includes("primary");function Mi(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!Fl.has(n)?n:jT(e)?.defaultChord??null}function yD(e){const t=new Map;for(const n of Pi){const r=Mi(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const BT=e=>e==="mac"?_("ui.settings.shortcuts.capture.needs_modifier_mac"):_("ui.settings.shortcuts.capture.needs_modifier");function HT(e,t,n,r="linux",o=new Map){const s=e===null?null:Ul(e);if(s===null)return _("ui.settings.shortcuts.capture.unbindable");if(!Ng(s))return BT(r);const a=Fl.get(s);if(a!==void 0)return a;const c=o.get(s);if(c!==void 0)return _("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of Pi)if(l.id!==t&&Mi(l.id,n)===s)return _("ui.settings.shortcuts.capture.already_assigned",{label:l.label});return null}function WT(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const o of Pi){const s=t[o.id];if(s===null){r[o.id]=null;continue}const a=typeof s=="string"?Ul(s):null,c=a!==null&&$T.has(a),l=a!==null&&Ng(a)&&(c||!Fl.has(a)&&!n.has(a))?a:null;l!==null&&(r[o.id]=l);const d=Mi(o.id,r);d!==null&&n.add(d)}return r}function wD(e,t,n){const r=Mi(e,t);return r===null?null:Dg(r,n)}function Dg(e,t){return OT(e,t)}function kD(e,t){const n=e.split("+"),r=n[n.length-1],o=n.slice(0,-1).map(s=>s==="primary"?t==="mac"?"Meta":"Control":s==="shift"?"Shift":s==="alt"?"Alt":s);return{glyph:Dg(e,t),aria:[...o,r.length===1?r.toUpperCase():r].join("+")}}const Sf=e=>{for(const t of[e.role,...e.variants])if(!d_.includes(t))throw new Error(`Unknown accent role: ${t}`);return Object.freeze({...e,variants:Object.freeze(e.variants)})},Lg=Object.freeze([Sf({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"}),Sf({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"})]),SD=e=>Lg.some(t=>t.role===e||t.variants.includes(e)),je={strongText:7,text:4.5,nonText:3},Ef=new Set(["inkDisabled"]),Ge=["canvas","surface","elevated","sunken"],Fg=[["ink",je.strongText],["inkMuted",5.5],["inkDim",5]],fn=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Vt={dark:{canvasMin:9,canvasMax:15,elevatedMax:22},light:{canvasMax:94,sunkenMin:80}},Rn={canvasSurface:[2.5,5],surfaceElevated:[2,6],canvasSunken:[1.5,6]},GT=2,zT=1.03,Bl=8,ai=2,Af=.8,If=3,Rf=2,xf=4,kc=2.5,Tf=4,Cf=2.5,Of=2,Pf=2,KT=[{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:Ge,fill:"accent",border:"accent",ink:"onAccent"},{name:"primary button (hover)",on:Ge,fill:"accentHover",border:"accentHover",ink:"onAccent"},{name:"primary button (pressed)",on:Ge,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:Ge,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:Ge,fill:"accentWash",border:null,ink:"inkMuted",edge:!1},{name:"input field",on:Ge,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:Ge,fill:"surface",border:"borderControl",ink:"ink"},{name:"browser file-transfer row (refused)",on:Ge,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:Ge,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}],VT=[{name:"context wheel arc against its track",a:["info","warning","danger"],b:"sunken",floor:je.nonText}],ZT=[{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:Ge,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"}],YT=[{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}],JT=["borderControl","accent","successBorder","warningBorder","dangerBorder","infoBorder"],QT=["accent","success","warning","danger","info"],XT=[{fg:"surface",on:"accent",floor:je.text,name:"the console terminal's cursor ink on its own cursor (9.1)"}],qT=[],eC=[{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"}],kr=15,Sr=8,tC=[{theme:"catppuccinMocha",a:"accentAlt",b:"info",floor:kr,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:kr,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:kr,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:kr,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:kr,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:Sr,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:Sr,got:0,why:"`info` IS `accent` (`#00EFFF`), the palette's single cyan"},{theme:"obsidian",a:"info",b:"accent",floor:Sr,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:Sr,got:0,why:"`info` IS `accent` (`#91B7E9`), the palette's single steel blue"},{theme:"githubLight",a:"info",b:"accent",floor:Sr,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"}],nC=[],rC=[],oC=["mode",...Ge,"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"],Es=["success","warning","danger","info"],sC=["success","warning","danger","info","ink"],Rr=8,ro="tokenCommand",As=Rr,iC=["surface","elevated","messageSurface"],aC=[{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."}],cn=15,Zo=15,wo=Rr,at=2,Mf=4,cC=.75,jf=.12,$f=.1,lC=[["surface","canvas"],["surface","elevated"],["elevated","canvas"]],dC=4,uC=2,fC=2,Ea=1,ci=2,Aa=2,Nf=.5,pC=1.5,hC=1.5,Ug=5,li=2.5,Bg=.5,di=5,Sc=4,Ec=24,Df=12,mC=.45,Lf=.75,gC=.25,pn=2,Hg=2,_C=[{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"}],bC=[{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"}],Ac=10,Is="surface",Ff=2,Uf=1.15,vC=({composed:e=!1,capturePairs:t=!1}={})=>{const n={assertions:0,failures:0,composed:e},r=[],o=(I,g)=>e?g>=I-.01:Math.abs(I-g)<.01,s=(I,g,w)=>e?g>=I-w:Math.abs(I-g)<=w,a=new Set,c=(I,g,w,S)=>{const x=eC.find(N=>N.theme===I&&N.role===g&&N.ground===w&&o(N.got,S));return x&&a.add(x),x},l=new Set,d=(I,g,w,S)=>{const x=tC.find(N=>N.theme===I&&N.a===g&&N.b===w&&o(N.got,S));return x&&l.add(x),x},u=new Set,f=new Set,h=new Set,m=(I,g,w)=>`${I} on ${g} in ${w}`,y=[],b=I=>{n.failures++,y.push(`FAIL ${I}`)},v=new Set,p=(I,g,w,S)=>{const x=qT.find(N=>N.theme===I&&N.fg===g&&N.bg===w&&o(N.got,S));return x&&v.add(x),x};return Object.assign(n,{readings:r,pinMatches:o,ledgerHolds:s,log:y,fail:b,exceptionSeen:v,perceptibleSeen:a,pairPinSeen:l,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:h,controlEdgeKey:m,pinClaims:new Set,findException:p,findPerceptibleException:c,findPairPin:d,assertPair:(I,g,w,S,x,N)=>{const J=g[w],M=g[S];if(!W(J)||!W(M))return;n.assertions++;const P=oe(J,M);if(t&&r.push({foreground:w,background:S,value:P,floor:x}),P>=x)return;const z=L(P);p(I,w,S,z)||b(`${I}: ${N} — ${w} ${J} on ${S} ${M} = ${z}:1, need ${x}:1`)},assertIdentityPair:(I,g,w,S,x,N)=>{const J=g[w],M=g[S];if(!W(J)||!W(M))return;n.assertions++;const P=L(de(J,M));if(P>=x)return;const z=d(I,w,S,P);if(z){z.floor!==x&&b(`${I}: \`${w}\`/\`${S}\` is pinned at floor ${z.floor} but this assertion asks for ${x} — a pin records the bound it was granted under, so the pin and the floor have to be raised together`);return}b(`${I}: ${N} — \`${w}\` ${J} and \`${S}\` ${M} are ΔE00 ${P} apart (need ${x}) — two roles a reader has to tell apart at this site cannot be one colour at two weights; move the palette value, or pin the palette in \`PAIR_PINS\` with the constraint that refuses it`)},floorUnreachablePin:(I,g)=>_C.find(S=>S.id===I&&S.role===g)??null,shortfallPin:(I,g,w)=>bC.find(x=>x.id===I&&x.role===g&&x.bound===w)??null}),n},yC=(e,t)=>{const{fail:n,assertPair:r,assertIdentityPair:o,findException:s,findPerceptibleException:a,floorUnreachablePin:c,shortfallPin:l,pinClaims:d,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:h,controlEdgeKey:m,pinMatches:y,ledgerHolds:b}=e;for(const{id:v,palette:p}of[t]){for(const g of oC)e.assertions++,g in p||n(`${v}: missing required role \`${g}\``);for(const[g,w]of Fg)if(!Ef.has(g))for(const S of fn)r(v,p,g,S,w,"body ink");for(let g=0;g<Ge.length;g++)for(let w=g+1;w<Ge.length;w++){const S=p[Ge[g]],x=p[Ge[w]];!W(S)||!W(x)||(e.assertions++,oe(S,x)<1.03&&n(`${v}: grounds \`${Ge[g]}\` ${S} and \`${Ge[w]}\` ${x} are indistinguishable (${L(oe(S,x))}:1) — elevation is a lightness step here, so they must differ`))}const A=[{role:"rowHover",castFloor:g=>Math.max(li,Bg*g),castCeiling:g=>Math.max(g,li),stepFloor:pC,stepCeiling:null},{role:"rowSelected",castFloor:g=>Math.max(di,g),castCeiling:g=>Math.min(Math.max(g+Sc,di),Ec),stepFloor:hC,stepCeiling:Ug}];for(const g of A){const w=g.role,S=p[w];if(!W(S))continue;const[x,N,J]=ie(S),[M,P,z]=ie(p.surface),[,Z,ge]=ie(p.accent),K=Math.hypot(Z,ge),ve=Math.hypot(P,z),pe=Math.hypot(N,J),ye=g.castFloor(ve),ft=g.castCeiling(ve),Be=ve<pn;e.assertions++;const qe=ve>=pn?{name:"the panel's",hue:Math.atan2(z,P)}:K>=Hg?{name:"`accent`'s",hue:Math.atan2(ge,Z)}:{name:"the panel's",hue:Math.atan2(z,P)},fe=Math.atan2(J,N),Ie=Math.abs(((fe-qe.hue)*180/Math.PI+540)%360-180);pe>=pn&&Ie>Df&&n(`${v}: \`${w}\` ${S} sits ${L(Ie)} degrees off ${qe.name} hue (the limit is ${Df}) — a row state has to be the colour of the backdrop it is a state of, and the values this round replaced took the \`accent\`'s hue instead, which is more than 45 degrees off the panel on 25 of the 59 palettes and is the off-colour the operator reported. Take the hue from ${qe.name} and re-author the value at it`),e.assertions++,ye>ft+1e-9?(d.add(`${v}:${w}:floor`),e.assertions++,c(v,w)||n(`${v}: \`${w}\` ${S} carries C* ${L(pe)}, and its cast floor ${L(ye)} is ABOVE its ceiling ${L(ft)} — the panel's own cast is louder than this role is allowed to be, so the value has to sit at the ceiling and \`${v}\`'s \`${w}\` has to be in ROW_STATE_FLOOR_UNREACHABLE naming the constraint that refuses the floor (the flat cap, the rise, or the role's absolute term)`),e.assertions++,pe<ft-Lf&&n(`${v}: \`${w}\` ${S} carries C* ${L(pe)} where its cast floor ${L(ye)} is above its ceiling ${L(ft)} — the floor cannot be held, but the CEILING is reachable and is what the ledger row promises this value sits at`)):pe<ye-mC&&n(`${v}: \`${w}\` ${S} carries C* ${L(pe)}, under the cast floor ${L(ye)} — 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++,pe>ft+Lf&&n(`${v}: \`${w}\` ${S} carries C* ${L(pe)}, past the ${L(ft)} 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 ${Sc} above it, and no more`}, and the flat cap is ${Ec}. Search the chroma back toward the panel and let the step and the pair's cast rank carry what the fill no longer can`),e.assertions++;const Rt=x-M,He=p.mode==="dark"?Rt:-Rt;if(He<g.stepFloor-1e-9&&n(`${v}: \`${w}\` ${S} sits ${L(Math.abs(Rt))} \`L*\` ${p.mode==="dark"?"above":"below"} \`surface\` ${p.surface}, so the step is ${p.mode==="dark"?"LIGHTER":"DARKER"}-by-${L(He)} where the floor is ${g.stepFloor} \`L*\` in the mode's raised direction — ΔE00 is a budget a chroma-only step can spend while moving the wrong way in lightness, and the three palettes that did exactly that were the same report answered twice`),g.stepCeiling!==null&&(e.assertions++,He>g.stepCeiling+gC+1e-9&&n(`${v}: \`${w}\` ${S} sits ${L(He)} \`L*\` from \`surface\`, past the ${g.stepCeiling} \`L*\` ceiling — every L* the row rises is ink headroom spent on the caps drawn inside it, so the step is taken as far as the inks allow and no further`)),w==="rowSelected"&&W(p.rowHover)){const[Pe,it,xt]=ie(p.rowHover),Tt=p.mode==="dark"?Pe-M:M-Pe,Gr=Math.hypot(it,xt);if(e.assertions++,He<Tt+Ea-1e-9){const ur=l(v,"rowSelected","rank");d.add(`${v}:rowSelected:rank`),e.assertions++,ur?b(ur.measured,He-Tt,.05)||n(`${v}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${ur.measured} and the pair now ranks ${L(He-Tt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${v}: \`rowSelected\` ${S} is ${L(He)} \`L*\` from \`surface\` where \`rowHover\` ${p.rowHover} is ${L(Tt)} — the selection has to be at least ${Ea} \`L*\` further out than the hover, or a reader scanning sees one mark at two strengths rather than two states. A palette that cannot reach it has its whole legal step consumed by the ink floors, and that is a ledger row rather than a relaxed floor`)}else!e.composed&&l(v,"rowSelected","rank")&&n(`${v}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — the pair ranks ${L(He-Tt)} \`L*\`, clear of the ${Ea} the row claims it misses. Remove the row`);e.assertions++,pe<Gr+ci-1e-9&&n(`${v}: \`rowSelected\` ${S} carries C* ${L(pe)} where \`rowHover\` ${p.rowHover} carries ${L(Gr)} — the selection has to carry at least ${ci} 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++,Tt<Nf*He-1e-9&&n(`${v}: \`rowHover\` ${p.rowHover} takes ${L(Tt)} \`L*\` of the ${L(He)} the selection takes (${Math.round(Tt/He*100)}%), under the ${Math.round(Nf*100)}% this file requires — the operator asked for MORE of the brightening than the shipped 30%, and an absolute hover floor cannot state that on a fleet whose budgets differ by 2.5x`)}e.assertions++;const pt=de(S,p.surface);if(pt<at-1e-9){const Pe=l(v,w,"band");d.add(`${v}:${w}:band`),e.assertions++,Pe?b(Pe.measured,pt,.05)||n(`${v}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Pe.measured} and the palette now measures ${L(pt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${v}: \`${w}\` ${S} is ΔE00 ${L(pt)} from \`surface\` ${p.surface} (the field floor is ${at}) — below this the mark is not findable while scanning, which is the operator's report restated. The band this role used to be held to was 4.0 and is WITHDRAWN because a backdrop-faithful fill cannot reach it on lightness; this floor is what is left, and a palette that misses even it needs a ledger row with the floor that refuses it`)}else!e.composed&&l(v,w,"band")&&n(`${v}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${L(pt)} from \`surface\`, clear of the ${at} the row claims it misses. Remove the row`);e.assertions++;const _e=de(S,p.accentWash);if(!Be&&_e<Aa){const Pe=l(v,w,"wash");d.add(`${v}:${w}:wash`),e.assertions++,Pe?b(Pe.measured,_e,.05)||n(`${v}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Pe.measured} and the palette now measures ${L(_e)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${v}: \`${w}\` ${S} is ΔE00 ${L(_e)} from \`accentWash\` ${p.accentWash} (need ${Aa}) — 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&&!Be&&l(v,w,"wash")&&n(`${v}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${L(_e)} from \`accentWash\`, clear of the ${Aa} the row claims it misses. Remove the row`)}if(W(p.rowHover)&&W(p.rowSelected)){e.assertions++;const g=de(p.rowSelected,p.rowHover),w=fC;g<w-1e-9&&n(`${v}: \`rowHover\` ${p.rowHover} and \`rowSelected\` ${p.rowSelected} are ΔE00 ${L(g)} apart (need ${w}) — the reader sees two marks and cannot rank them. This was the second half of the operator's report: on \`neon\` the shipped pair sat 1.80 ΔE apart while each was ~6.2 ΔE off the panel. The ranking is the fill's now, so a palette that misses this is missing because the two fills are the SAME MARK — give the selection more step or more cast than the hover`)}if(W(p.sunken)&&W(p.rowHover)&&W(p.rowSelected)&&W(p.borderControl))for(const g of["rowHover","rowSelected"]){e.assertions++;const w=de(p.sunken,p[g]),S=oe(p.borderControl,p[g]);w<at&&S<je.nonText&&n(`${v}: the agents sidebar's avatar plate has no perceivable edge against \`${g}\` — its \`sunken\` fill ${p.sunken} is ΔE00 ${L(w)} from it (need ${at}) and the plate's \`borderControl\` edge ${p.borderControl} is ${L(S)}:1 against that same fill (need ${je.nonText}:1), so the row's own ${g==="rowHover"?"hover":"selection"} turns the avatar into a disc of the row's fill. Give the plate an edge the row's state cannot overrun, or a fill that state cannot land on`)}if(typeof p.scrim=="string"&&W(p.ink)){const g=p.scrim.match(/rgb\((\d+)\s+(\d+)\s+(\d+)\s*\/\s*([\d.]+)\)/);if(g){const[w,S,x,N]=g.slice(1).map(Number);for(const J of fn){if(!W(p[J]))continue;const M=[1,3,5].map(Z=>Number.parseInt(p[J].slice(Z,Z+2),16)),P=`#${[w,S,x].map((Z,ge)=>Math.round(Z*N+M[ge]*(1-N)).toString(16).padStart(2,"0")).join("")}`;e.assertions++;const z=oe(p.ink,P);z<je.nonText&&n(`${v}: the lightbox's current-tile ring has no perceivable edge over \`${J}\` — \`ink\` is ${L(z)}:1 against the scrim composited over it (need ${je.nonText}:1). The scrim dims whatever is open under it, so the ring's role has to clear every ground the overlay can open over`)}}}for(const g of JT)for(const w of Ge)r(v,p,g,w,je.nonText,"structural edge");const k=[...Ge,"accentWash","messageSurface"];for(const g of QT)for(const w of k)r(v,p,g,w,je.text,"colour as text");r(v,p,"warning","elevated",je.text,"the picker's partial-listing note"),r(v,p,"danger","elevated",je.text,"danger as text on a dialog's ground"),r(v,p,"warning","rowSelected",je.text,"integration status text on a deep-linked row"),r(v,p,"accent","warningWash",je.text,"model-access band links on the warning wash"),r(v,p,"warning","rowHover",je.text,"the partial delivery word on the hovered row's ground"),r(v,p,"dangerBorder","elevated",je.nonText,"the danger control's only edge on a dialog's ground");for(const g of KT)for(const w of g.on){const S=p[w],x=g.fill?p[g.fill]:S,N=p[g.ink],J=g.border?p[g.border]:null;if(!W(S)||!W(x)||!W(N))continue;e.assertions++;const M=oe(N,x);if(M<je.text&&!Ef.has(g.ink)&&!s(v,g.ink,g.fill??w,M)&&n(`${v}: ${g.name} on ${w} — ink ${g.ink} ${N} on fill ${x} = ${M}:1, need ${je.text}:1`),g.edge!==!1){e.assertions++;const P=oe(x,S),z=W(J)?oe(J,S):0,Z=Math.max(P,z);if(Z<je.nonText){const ge=rC.find(K=>K.control===g.name&&K.ground===w&&K.theme===v&&y(K.got,L(Z)));ge?h.add(m(ge.control,ge.ground,ge.theme)):n(`${v}: ${g.name} on ${w} has no perceivable edge — fill ${P}:1, border ${z}:1, need one at ${je.nonText}:1`)}}}for(const g of XT)r(v,p,g.fg,g.on,g.floor,g.name);for(const g of ZT)for(const w of g.on)r(v,p,g.fg,w,g.floor??je.nonText,g.name);for(const g of VT){const w=p[g.b];if(W(w))for(const S of g.a){const x=p[S];if(!W(x))continue;e.assertions++;const N=oe(x,w);N<g.floor&&!s(v,S,g.b,N)&&n(`${v}: ${g.name} — ${S} ${x} against ${g.b} ${w} = ${N}:1, need ${g.floor}:1`)}}for(const g of YT){const w=p[g.role];if(!W(w))continue;for(const P of g.on){if(!W(p[P]))continue;e.assertions++;const z=de(w,p[P]);z<g.minDeltaE&&!a(v,g.role,P,L(z))&&n(`${v}: ${g.name} — ${g.role} ${w} on ${P} ${p[P]} is ΔE00 ${L(z)}, need ${g.minDeltaE} to be seen at all`)}if(!g.pairedWith||!g.against)continue;const S=p[g.pairedWith],x=p[g.against];if(!W(S)||!W(x))continue;e.assertions++;const N=oe(w,x),J=oe(S,x),M=Math.max(N/J,J/N);M>g.maxWeightChange&&n(`${v}: ${g.name} — ${g.role} is ${L(M)}x the weight of ${g.pairedWith} against ${g.against}; one component must not change weight by more than ${g.maxWeightChange}x between states`)}for(let g=0;g<Es.length;g++)for(let w=g+1;w<Es.length;w++){const[S,x]=[Es[g],Es[w]];if(!W(p[S])||!W(p[x]))continue;e.assertions++;const N=de(p[S],p[x]);N<cn&&n(`${v}: \`${S}\` ${p[S]} and \`${x}\` ${p[x]} are too close to tell apart (ΔE00 ${L(N)}, need ${cn}) — a semantic a reader cannot distinguish from another semantic is not a semantic`)}if(W(p.accentAlt)){if(W(p.accent)){e.assertions++;const x=de(p.accentAlt,p.accent);x<cn&&n(`${v}: the second accent \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(x)} from \`accent\` ${p.accent} (need ${cn}) — 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 x of["success","warning","danger"]){if(!W(p[x]))continue;e.assertions++;const N=de(p.accentAlt,p[x]);N<cn&&n(`${v}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(N)} from \`${x}\` ${p[x]} (need ${cn}) — a decorative mark a reader can mistake for "${x==="danger"?"something broke":x}" costs them something real, so the palette moves the hue rather than the assertion`)}if(W(p.info)){e.assertions++;const x=de(p.accentAlt,p.info);x<Rr&&n(`${v}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(x)} from \`info\` ${p.info} (need ${Rr}) — \`info\` is the family the port mapped the TUI's \`signal\` onto, so the floor here is the reduced one and not ${cn}; below it the two take the same name`)}const[,g,w]=ie(p.accentAlt),S=Math.hypot(g,w);e.assertions++,S<Zo&&n(`${v}: \`accentAlt\` ${p.accentAlt} is C* ${L(S)} (need ${Zo}) — 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 x of["canvas","surface","sunken"])r(v,p,"accentAlt",x,je.text,"second accent as text");r(v,p,"accentAlt","elevated",je.text,"second accent as text on a row's state ground")}if(o(v,p,"accentAlt","info",kr,"the tool row's two category inks"),o(v,p,"info","accent",Sr,"the settled read ink against the liveness ink"),W(p.accentAltWash)&&W(p.accentWash)){e.assertions++;const g=de(p.accentAltWash,p.accentWash);g<at&&n(`${v}: \`accentAltWash\` ${p.accentAltWash} is ΔE00 ${L(g)} from \`accentWash\` ${p.accentWash} (need ${at}) — the two washes sit adjacent in mermaid's categorical ramp, so a step the reader cannot see is not a step`)}for(const g of sC){if(!W(p[g])||!W(p.inkDim))continue;e.assertions++;const w=de(p[g],p.inkDim);w<Rr&&n(`${v}: syntax \`${g}\` ${p[g]} sits at ΔE00 ${L(w)} from comment \`${p.inkDim}\` (need ${Rr}) — a token the eye cannot separate from the comment beside it is not highlighted`)}if(W(p[ro])&&W(p.ink)){const g=aC.find(w=>w.theme===v);for(const w of iC){if(!W(p[w]))continue;e.assertions++;const S=oe(p[ro],p[w]);S<4.5&&n(`${v}: the command token \`tokenCommand\` ${p[ro]} reads ${L(S)}:1 on \`${w}\` (need 4.5) - the token is text a user typed (the composer's leading /word, or the sent \`$skill\` mention), not decoration`)}for(const w of["ink","accent","success"]){if(!W(p[w]))continue;e.assertions++;const S=de(p[ro],p[w]);if(!!g?.against.includes(w)){y(g.got,S)||n(`${v}: COMMAND_TOKEN_PINNED records ${g.got} for \`command\`/\`${w}\` but it now measures ${L(S)} - re-measure and update the pin (${g.why})`);continue}S<As&&n(`${v}: the command token \`tokenCommand\` ${p[ro]} sits at ΔE00 ${L(S)} from \`${w}\` ${p[w]} (need ${As}) - the composer paints this run in the same box as that ink, so a reader cannot tell which is which`)}if(W(p.success)){e.assertions++;const w=de(p.success,p.ink);w<As&&n(`${v}: the roster NAME's ink \`success\` ${p.success} sits at ΔE00 ${L(w)} from prose \`ink\` ${p.ink} (need ${As}) - a resolved name that reads as prose is not a run`)}}if(W(p.inkMuted)&&W(p.inkDim)){e.assertions++,u.add(v);const g=de(p.inkMuted,p.inkDim),w=nC.find(S=>S.theme===v);w&&f.add(w),g<wo?w?y(w.got,g)||n(`${v}: INK_STEP_PINNED records ${w.got} but \`inkMuted\`/\`inkDim\` now measure ${L(g)} - re-measure and update the pin, so the recorded number stays the one in the palette`):n(`${v}: the control ink \`inkMuted\` ${p.inkMuted} sits at ΔE00 ${L(g)} from the readout ink \`inkDim\` ${p.inkDim} (need ${wo}) - a chip that opens cannot be told from a reading that does not`):w&&!e.composed&&n(`${v}: the ink step is pinned at ${w.got} but now measures ${L(g)}, clearing the ${wo} floor - delete the pin rather than leaving dead weight in the contract`)}for(const[g,w,S=at]of[["canvas","surface"],["surface","elevated"],["elevated","sunken"],["accent","accentHover"],["accentHover","accentActive"],["accent","accentActive"],["surface","sunken"],["canvas","elevated",dC]]){if(!W(p[g])||!W(p[w]))continue;e.assertions++;const x=de(p[g],p[w]);x<S&&n(`${v}: adjacent \`${g}\` and \`${w}\` are ΔE00 ${L(x)} apart (need ${S}) — a step the eye cannot see is not a step`)}{const g=ie(p.canvas)[0],w=ie(p.surface)[0],S=ie(p.elevated)[0],x=ie(p.sunken)[0],N=p.mode==="dark";e.composed||(e.assertions++,N&&(g<Vt.dark.canvasMin||g>Vt.dark.canvasMax)&&n(`${v}: dark \`canvas\` ${p.canvas} sits at L* ${L(g)} — the band is [${Vt.dark.canvasMin}, ${Vt.dark.canvasMax}] in L*. Below the floor the three ink weights and the three ladder steps stop fitting above each other without one of them breaking its own floor; above the ceiling the canvas is no longer the darker tone the operator asked for (2026-11-03), and a palette above it was not re-lit by the band's proportional map`),e.assertions++,N&&S>Vt.dark.elevatedMax&&n(`${v}: dark \`elevated\` ${p.elevated} sits at L* ${L(S)} — the ceiling is L* ${Vt.dark.elevatedMax}, because at L* 34 an \`inkDim\` at its floor needs L* 85 and the ink/hover distinction disappears into the top of the ramp`),e.assertions++,!N&&g>Vt.light.canvasMax&&n(`${v}: light \`canvas\` ${p.canvas} sits at L* ${L(g)} — the ceiling is L* ${Vt.light.canvasMax}. \`elevated\` at L* 100 is the end of sRGB's ramp and the minimum canvas-to-elevated spread is 2.5 + 2.5 L*, so a canvas above 95 has no room for both steps; 94 leaves 1 L* for 8-bit rounding`),e.assertions++,!N&&x<Vt.light.sunkenMin&&n(`${v}: light \`sunken\` ${p.sunken} sits at L* ${L(x)} — the floor is L* ${Vt.light.sunkenMin}. A light theme's recessed ground is the darkest plane in it, so it is the cap for every ink there and the keycap's ground on every selected row`));for(const[J,M,P,[z,Z],ge]of[["canvas -> surface","canvas","surface",Rn.canvasSurface,w-g],["surface -> elevated","surface","elevated",Rn.surfaceElevated,S-w],["canvas -> sunken","canvas","sunken",Rn.canvasSunken,g-x]])if(e.assertions++,(ge<z-1e-9||ge>Z+1e-9)&&n(`${v}: the ${J} step is ${L(ge)} L*, outside [${z}, ${Z}] — the bounds are both ends of the same budget: below the floor the two grounds merge, and above the ceiling the step eats the room the ink ladder needs`),r(v,p,M,P,zT,`${J} step`),M==="canvas"&&P==="sunken"||M==="surface"&&P==="elevated"){e.assertions++;const K=de(p[M],p[P]),ve=M==="canvas"?GT:uC;K<ve&&n(M==="canvas"?`${v}: \`canvas\` and \`sunken\` are ΔE00 ${L(K)} apart (need ${ve}) — a well nobody can see is not a well, and both blocks that paint one are read inside a trace that sits on the canvas`:`${v}: \`surface\` ${p.surface} and \`elevated\` ${p.elevated} are ΔE00 ${L(K)} apart (need ${ve}) — the hover rung is the ground a hover, a menu and a dialog are all painted on, so it cannot sit closer to the panel than this and still report the pointer; it is also the ground the current row has to outrank, so a rung at this floor is what the row/hover ordering is measured against. Place it at the lowest \`L*\` that clears this and no lower - the row's own rank against the hover is asserted in the row-state loop below, so a rung placed here is a rung the two row fills have to fit above`)}}r(v,p,"ink","canvas",Bl,"the transcript's body ink");for(const g of fn){if(!W(p.inkDisabled)||!W(p.inkDim)||!W(p[g]))continue;e.assertions++;const w=oe(p.inkDisabled,p[g]),S=oe(p.inkDim,p[g]);w>Af*S+1e-9&&n(`${v}: \`inkDisabled\` on ${g} measures ${L(w)}:1 against \`inkDim\`'s ${L(S)}:1 — a factor of ${L(w/S)}, over the ${Af} ceiling. A disabled control that meets the ink floors does not read as disabled`)}for(const[g,w]of[["inkDim","inkMuted"],["inkMuted","ink"]]){if(!W(p[g])||!W(p[w]))continue;e.assertions++;const S=de(p[g],p[w]);S<ai&&n(`${v}: \`${w}\` and \`${g}\` are ΔE00 ${L(S)} apart (need ${ai}) — the three weights are a ladder, and a rung the eye cannot see is not a rung`)}{const g=de(p.sunken,p.elevated);e.assertions++,g<If&&n(`${v}: the palette/picker active row (\`sunken\` ${p.sunken}) is ΔE00 ${L(g)} from the dialog ground it is painted on (\`elevated\` ${p.elevated}), need ${If} — a selection is a state the reader has to find while scanning, not a surface they read, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ie(p.sunken)[0]-ie(p.elevated)[0]);w<Rf&&n(`${v}: the palette/picker active row sits ${L(w)} L* from \`elevated\`, under the ${Rf} L* floor — ΔE00 is a budget a chroma-only step can spend while the mark vanishes in a greyscale render, so the lightness half is asserted too`)}{if(p.messageSurface===void 0)continue;if(!W(p.messageSurface)){n(`${v}: the user message block's fill \`messageSurface\` ${JSON.stringify(p.messageSurface)} is present but not a flat hex colour, so the role's floor would be silently unmeasured - a malformed value must not switch a floor off`);continue}if(!W(p.canvas))continue;const g=de(p.messageSurface,p.canvas);e.assertions++,g<xf&&n(`${v}: the user message block's fill \`messageSurface\` ${p.messageSurface} is ΔE00 ${L(g)} from \`canvas\` ${p.canvas} (need ${xf}) — the fill IS the block's boundary, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ie(p.messageSurface)[0]-ie(p.canvas)[0]);w<kc&&n(`${v}: the user message block's fill sits ${L(w)} L* from \`canvas\`, under the ${kc} L* floor — ΔE00 is a budget a chroma-only step can spend while the mark vanishes in a greyscale render, so the lightness half is asserted too`)}{if(p.mediaSurface===void 0)continue;if(!W(p.mediaSurface)){n(`${v}: the media tile's fill \`mediaSurface\` ${JSON.stringify(p.mediaSurface)} is present but not a flat hex colour, so the role's floor would be silently unmeasured - a malformed value must not switch a floor off`);continue}if(!W(p.canvas))continue;const g=de(p.mediaSurface,p.canvas);e.assertions++,g<Tf&&n(`${v}: the media tile's fill \`mediaSurface\` ${p.mediaSurface} is ΔE00 ${L(g)} from \`canvas\` ${p.canvas} (need ${Tf}) — the fill IS the borderless tile's extent, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ie(p.mediaSurface)[0]-ie(p.canvas)[0]);w<Cf&&n(`${v}: the media tile's fill sits ${L(w)} L* from \`canvas\`, under the ${Cf} L* floor — ΔE00 is a budget a chroma-only step can spend while the fill vanishes in a greyscale render, so the lightness half is asserted too`)}for(const g of Ge){if(!W(p.accentWash)||!W(p[g]))continue;e.assertions++;const w=de(p.accentWash,p[g]);w<Of&&n(`${v}: the accent wash on ${g} is ΔE00 ${L(w)} (need ${Of}) — a hover tint the reader cannot see is a hover state the pointer cannot report, and this pair reads 1.00-1.24:1, so no ratio assertion in this file can see it`)}for(const g of["canvas","surface","elevated","accentWash"]){if(!W(p.sunken)||!W(p[g]))continue;e.assertions++;const w=de(p.sunken,p[g]);w<Pf&&n(`${v}: the keycap's ground \`sunken\` ${p.sunken} is ΔE00 ${L(w)} from ${g} ${p[g]} (need ${Pf}) — the cap annotates the row the reader has just selected, so its ground has to survive being painted on that row`)}if(W(p.chartBarHover)&&W(p.accent)&&W(p[Is])){e.assertions++;const g=de(p.chartBarHover,p.accent);g<Ac&&n(`${v}: \`chartBarHover\` ${p.chartBarHover} is ΔE00 ${L(g)} from \`accent\` ${p.accent}, need ${Ac} — a mark the reader has to find among its SIBLINGS is compared with them, not with itself across two states`),e.assertions++;const w=oe(p.chartBarHover,p[Is]),S=oe(p.accent,p[Is]);w<S&&n(`${v}: \`chartBarHover\` is ${L(w)}:1 on ${Is} where \`accent\` is ${L(S)}:1 — the hovered mark must not recede toward the ground it is drawn on`)}for(const g of Ge){if(!W(p.hairline)||!W(p[g]))continue;e.assertions++;const w=de(p.hairline,p[g]);w<Mf&&n(`${v}: \`hairline\` on \`${g}\` is ΔE00 ${L(w)} (need ${Mf}) — a 1px line has no area to integrate over, so a step that reads between two fields disappears in a rule`);const S=oe(p.hairline,p[g]);e.assertions++,S<Uf&&n(`${v}: \`hairline\` on \`${g}\` is ${L(S)}:1 (need ${Uf}) — its ΔE00 is carried in chroma, which a 1px line does not survive`),e.assertions++,S>Ff&&n(`${v}: \`hairline\` on \`${g}\` is ${L(S)}:1 (max ${Ff}) — past this it is drawing a border, and the system already has one of those`)}for(const[g,w]of lC){if(!W(p.hairline)||!W(p[g])||!W(p[w]))continue;const S=ya(p.hairline,p[g],cC);e.assertions++;const x=de(S,p[g]);x<at&&n(`${v}: the panel seam over \`${g}\` is ΔE00 ${L(x)} from that ground (need ${at}) — the seam is half the boundary, and half a boundary the reader cannot see is a panel edge that disappears`),e.assertions++;const N=de(S,p[w]);N<at&&n(`${v}: the panel seam over \`${g}\` is ΔE00 ${L(N)} from \`${w}\` (need ${at}) — the seam has to read from the plane it faces as well as the one it sits on`)}const T=ya(p.accent,p.surface,jf);for(const[g,w,S]of[["inkMuted",je.text,"washed row metadata ink"],["ink",je.text,"washed row body ink"]]){const x=p[g];if(!W(x))continue;e.assertions++;const N=L(oe(x,T));N>=w||n(`${v}: ${S} — ${g} ${x} on the arrival band ${T} (accent ${jf} over surface) = ${N}:1, need ${w}:1`)}for(const g of["canvas","surface","elevated","accentWash"]){const w=ya(p.accent,p[g],$f);for(const[S,x,N]of[["inkMuted",je.text,"loading pill label"]]){const J=p[S];if(!W(J))continue;e.assertions++;const M=L(oe(J,w));M>=x||n(`${v}: ${N} — ${S} ${J} on the loading pill ${w} (accent ${$f} over ${g}) = ${M}:1, need ${x}:1`)}}const F=oe(T,p.surface),C=oe(p.rowHover,p.surface),I=oe(p.rowSelected,p.surface);e.assertions+=2,F<=C&&n(`${v}: the arrival band is ${L(F)}:1 over the pane and the row hover is ${L(C)}:1 — the mark the reader was TOLD about cannot be drawn more quietly than one their pointer rests on`),F<=I&&n(`${v}: the arrival band is ${L(F)}:1 over the pane and the selected row is ${L(I)}:1 — the arrival must outrank the row the reader is already on, or the landing reads as a selection`)}},wC=Object.freeze({soft:-100,gentle:-50,standard:0,strong:50,high:100}),kC=Object.freeze({dark:Object.freeze({high:5,soft:20}),light:Object.freeze({high:97,soft:89})}),SC=["canvas","surface","elevated","sunken","messageSurface","mediaSurface","rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash","hairline","hairlineStrong","inkDisabled"],EC=new Set(["rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash"]),$s=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Pt=$s.slice(0,4),oo=[...Pt,"accentWash","messageSurface"],Ia={ink:[$s,7],inkMuted:[$s,5.5],inkDim:[$s,5],borderControl:[Pt,3],accent:[[...oo,"warningWash"],4.5],accentHover:[Pt,4.5],accentActive:[Pt,4.5],tokenCommand:[["surface","elevated","messageSurface"],4.5],accentAlt:[Pt,4.5],success:[oo,4.5],warning:[[...oo,"rowSelected","rowHover"],4.5],danger:[oo,4.5],info:[oo,4.5],successBorder:[Pt,3],warningBorder:[Pt,3],dangerBorder:[Pt,3],infoBorder:[Pt,3],chartBarHover:[["surface"],3]},Mt=.05,Bf=.3,Hf=4.1,AC=.06,IC=/^#[0-9A-Fa-f]{6}$/,ot=e=>typeof e=="string"&&IC.test(e),Bt=e=>e.slice(0,7).toUpperCase(),lt=(e,t,n)=>{const r=Math.max(0,Math.min(100,e));for(let o=1;o>=0;o-=.02){const s=ii([r,t*o,n*o]);if(s)return s}return ii([r,0,0])},rr=(e,t,n)=>Math.min(...n.filter(r=>ot(e[r])).map(r=>oe(t,e[r]))),Ic=(e,t,n,r,o=()=>!0)=>{const s=e[t];if(!ot(s)||rr(e,s,n)>=r+Mt&&o(s))return s;const[a,c,l]=ie(s),d=e.mode==="dark"?1:-1;for(let u=.25;u<=100;u+=.25){const f=lt(a+d*u,c,l);if(rr(e,f,n)>=r+Mt&&o(f))return f}return s},Hl=(e,t)=>{const n=t.filter(ot).map(Bt),r=n.find(o=>oe(o,e)>=4.5);return r||[...n].sort((o,s)=>oe(s,e)-oe(o,e))[0]},Rs=e=>1+.015*(e-50)**2/Math.sqrt(20+(e-50)**2),or=e=>{const[,t,n]=ie(e);return Math.hypot(t,n)},Wf=(e,t)=>{const[n,r,o]=ie(e),s=Math.hypot(r,o);return s<1e-6?e:lt(n,r/s*t,o/s*t)},RC=e=>{if(!ot(e.rowHover)||!ot(e.rowSelected))return;CC(e);const t=or(e.surface),n=Math.max(li,Bg*t),r=Math.max(t,li),o=Math.max(di,t),s=Math.min(Math.max(t+Sc,di),Ec),a=(f,h,m)=>Math.min(Math.max(f,h),m),c=or(e.rowHover),l=or(e.rowSelected);if(c>=n&&c<=r&&l>=o&&l<=s&&l>=c+ci)return;const d=a(c,n+.1,r-.1),u=a(Math.max(l,d+ci+.2),o+.1,s-.1);e.rowHover=Wf(e.rowHover,d),e.rowSelected=Wf(e.rowSelected,u)},xC=6,TC=e=>{const[,t,n]=ie(e);return Math.atan2(n,t)},CC=e=>{const n=or(e.surface)>=pn?e.surface:or(e.accent)>=Hg?e.accent:e.surface,r=TC(n);for(const o of["rowHover","rowSelected"]){const[s,a,c]=ie(e[o]),l=Math.hypot(a,c);l<pn||Math.abs(((Math.atan2(c,a)-r)*180/Math.PI+540)%360-180)<=xC||(e[o]=lt(s,l*Math.cos(r),l*Math.sin(r)))}},OC=e=>{const t=e.mode==="dark"?1:-1,n=(r,o,s,a,c)=>{const l=e[r];if(!ot(l))return;const d=m=>rr(e,m,o)>=s+Mt&&(!a||de(m,e[a])>=c+Mt)&&(r!=="ink"||oe(m,e.canvas)>=Bl+Mt);if(d(l))return;const[u,f,h]=ie(l);for(let m=.25;m<=100;m+=.25){const y=lt(u+t*m,f,h);if(d(y)){e[r]=y;return}}};n("inkDim",fn,Ns("inkDim"),null,0),n("inkMuted",fn,Ns("inkMuted"),"inkDim",wo),n("ink",fn,Ns("ink"),"inkMuted",ai)},Ns=e=>Fg.find(([t])=>t===e)[1],PC=.15,Wg=.12,MC=(e,t,n)=>{if(!ot(e.ink)||!ot(e.canvas))return;const r=Math.abs(n)/100,o=e.mode==="dark"?1:-1;if(n>0){const[l,d,u]=ie(e.ink),f=t*(1+PC*r);if(oe(e.ink,e.canvas)>=f)return;for(let h=.25;h<=100;h+=.25){const m=l+o*h;if(m<0||m>100)break;const y=lt(m,d,u);if(e.ink=y,oe(y,e.canvas)>=f)return}return}const s=t*(1-Wg*r),a=["ink","inkMuted","inkDim"].filter(l=>ot(e[l])),c=l=>a.every(d=>rr(e,l[d],fn)>=Ns(d)+Mt)&&oe(l.ink,e.canvas)>=Bl&&(!l.inkMuted||de(l.ink,l.inkMuted)>=ai+Mt)&&(!l.inkMuted||!l.inkDim||de(l.inkMuted,l.inkDim)>=wo+Mt);for(const l of[a,a.slice(0,2),a.slice(0,1)]){const d=Object.fromEntries(l.map(u=>[u,ie(e[u])]));for(let u=.25;u<=60;u+=.25){if(oe(e.ink,e.canvas)<=s)return;const f={...e};for(const h of l){const[m,y,b]=d[h];f[h]=lt(m-o*u,y,b)}if(!c(f))break;for(const h of l)e[h]=f[h]}}},xs=(e,t,n,r,o=()=>!0)=>{const s=e[t];if(!ot(s)||!n.split(",").every(f=>ot(e[f])))return;const a=f=>n.split(",").every(h=>de(f,e[h])>=r+Mt)&&o(f);if(a(s))return;const[c,l,d]=ie(s),u=e.mode==="dark"?1:-1;for(const f of[u,-u])for(let h=.25;h<=40;h+=.25){const m=lt(c+f*h,l,d);if(a(m)){e[t]=m;return}}},Gg=(e,t,{spread:n=1,narrow:r=!1,ease:o=AC,travel:s=1}={})=>{if(t===0)return e;const a=t>0?"high":"soft",c=Math.abs(t)/100,l={...e},d=K=>ie(Bt(e[K])),u=d("canvas")[0],f=kC[e.mode][a],h=SC.filter(K=>ot(e[K])),m=a==="high"==(e.mode==="light")?1:-1;let y=Math.max(0,(f-u)*m)*m*c*s,b=u+y;const v=a==="soft"?1-.4*c:1,p=Rs(b)/Rs(u),A=(a==="soft"?p:Math.max(1,p))*n,k=Object.fromEntries(h.map(K=>[K,b+(d(K)[0]-u)*A])),T=e.mode==="dark"?1:-1,F=(K,[,ve],pe)=>{const ye=(d(K)[0]-u)*pe,ft=(k[K]-b)*pe,Be=Math.max(ye,ve-.15);ft>Be&&(k[K]=b+pe*Be)};F("surface",Rn.canvasSurface,T),F("sunken",Rn.canvasSunken,-T);{const K=(d("elevated")[0]-d("surface")[0])*T,ve=(k.elevated-k.surface)*T,pe=Math.max(K,Rn.surfaceElevated[1]-.15);ve>pe&&(k.elevated=k.surface+T*pe)}const C=d("surface")[0],I=e.mode==="dark"?1:-1,g=(d("rowSelected")[0]-C)*I,w=(d("rowHover")[0]-C)*I,S=g>0?Math.min(A,Ug/g):A,x=a==="soft"?S:Math.max(1,S);if(k.rowSelected=k.surface+I*g*x,k.rowHover=k.surface+I*w*x,e.mode==="light"&&a==="high"){const K=u+y,ve=Object.keys(k).filter(ye=>d(ye)[0]>u),pe=Math.max(0,...ve.map(ye=>d(ye)[0]-u));if(pe>0){const ye=_e=>{const Pe=Math.min(1,(100-Bf-_e)/pe),it={canvas:lt(_e,...d("canvas").slice(1))};for(const xt of ve)it[xt]=lt(_e+(d(xt)[0]-u)*Pe,...d(xt).slice(1));return it},ft=[["canvas","surface",at],["surface","elevated",at],["canvas","elevated",Hf],["canvas","messageSurface",Hf]].filter(([_e,Pe])=>(_e==="canvas"||ve.includes(_e))&&ve.includes(Pe)),Be=[["canvas","surface",Rn.canvasSurface[0]],["surface","elevated",Rn.surfaceElevated[0]],["canvas","messageSurface",kc]].filter(([_e,Pe])=>(_e==="canvas"||ve.includes(_e))&&ve.includes(Pe)),qe=(_e,Pe,it)=>it+.02,fe=_e=>ft.every(([Pe,it,xt])=>de(_e[Pe],_e[it])>=qe(Pe,it,xt))&&Be.every(([Pe,it,xt])=>ie(_e[it])[0]-ie(_e[Pe])[0]>=xt+.15);let Ie=K;for(;Ie>u&&!fe(ye(Ie));)Ie=Math.max(u,Ie-.25);const Rt=Ie<=u?1:Math.min(1,(100-Bf-Ie)/pe),He=Math.max(1,Rs(Ie)/Rs(u))*n,pt={rowHover:k.rowHover-k.surface,rowSelected:k.rowSelected-k.surface};for(const _e of Object.keys(k))k[_e]=ve.includes(_e)?Ie+(d(_e)[0]-u)*Rt:Ie+(k[_e]-K)*(He/A);for(const _e of["rowHover","rowSelected"])_e in k&&Number.isFinite(pt[_e])&&(k[_e]=k.surface+pt[_e]);b=Ie,y=Ie-u}}if(a==="soft"&&r){const K=fe=>e.mode==="dark"?fe>b:fe<b,ve=fe=>fe>8?((fe+16)/116)**3:Math.max(0,fe)/903.3,pe=(fe,Ie)=>{const[Rt,He]=[ve(fe),ve(Ie)];return(Math.max(Rt,He)+.05)/(Math.min(Rt,He)+.05)},ye=fn.filter(fe=>fe in k&&K(k[fe])),Be=Math.max(1,...fn.filter(fe=>fe in k&&(e.mode==="dark"?d(fe)[0]>u:d(fe)[0]<u)).map(fe=>pe(u,d(fe)[0])))*(1-o*c),qe=fe=>Math.max(1,...ye.map(Ie=>pe(b,b+(k[Ie]-b)*fe)));if(ye.length>0&&qe(1)>Be){let fe=1;for(;fe>.3&&qe(fe)>Be;)fe-=.01;for(const Ie of Object.keys(k))K(k[Ie])&&(k[Ie]=b+(k[Ie]-b)*fe)}}const N=Math.min(...Object.values(k)),J=Math.max(...Object.values(k)),M=N<.5?.5-N:J>100?100-J:0,P=or(Bt(e.surface)),z=P>=pn?Math.max(v,Math.min(1,(pn+.4)/P)):v;for(const K of h){const[,ve,pe]=d(K),ye=EC.has(K)?1:K==="surface"?z:v;l[K]=lt(k[K]+M,ve*ye,pe*ye)}RC(l),y=b+M-u;for(const K of Object.keys(Ia))ot(e[K])&&(l[K]=Bt(e[K]));OC(l),MC(l,oe(Bt(e.ink),Bt(e.canvas)),t);const Z=ie(l.accent)[0];l.accent=Ic(l,"accent",...Ia.accent);const ge=ie(l.accent)[0]-Z;for(const K of["accentHover","accentActive"]){if(!ot(l[K])||ge===0)continue;const[ve,pe,ye]=ie(l[K]);l[K]=lt(ve+ge,pe,ye)}for(const[K,[ve,pe]]of Object.entries(Ia))K.startsWith("ink")||K==="accent"||(l[K]=Ic(l,K,ve,pe));return xs(l,"accentHover","accent",at,K=>rr(l,K,Pt)>=4.5+Mt),xs(l,"accentActive","accent,accentHover",at,K=>rr(l,K,Pt)>=4.5+Mt),xs(l,"accentAlt","accent",cn,K=>rr(l,K,Pt)>=4.5+Mt&&or(K)>=Zo),xs(l,"chartBarHover","accent",Ac,K=>oe(K,l.surface)>=oe(l.accent,l.surface)),l.onAccent=Hl(l.accent,[e.onAccent,l.ink,l.canvas,"#FFFFFF","#000000"]),l},ui=(e,t="custom")=>{const n=vC({composed:!0});return yC(n,{id:t,palette:e}),n.log},Ds=(e,t)=>{const n=Hl(e.accent,[t.onAccent,e.ink,e.canvas,"#FFFFFF","#000000"]);return n===e.onAccent?e:{...e,onAccent:n}},Gf=new Set(["mode","overlayShadow","scrim","onAccent"]),jC=["rowHover","rowSelected","accentWash","surface"],$C=/\b[a-z][A-Za-z]+\b/g,NC=(e,t)=>{const n=new Map;for(const[o,s]of Object.entries(e))!Gf.has(o)&&ot(s)&&n.set(s.toUpperCase(),o);const r=new Set;for(const o of t){if(o.includes("ROW_STATE_MEASURED_SHORTFALL"))for(const s of jC)r.add(s);for(const[s]of o.matchAll($C))s in e&&!Gf.has(s)&&ot(e[s])&&r.add(s);for(const[s]of o.matchAll(DC)){const a=n.get(s.toUpperCase());a&&r.add(a)}}return[...r]},DC=/#[0-9A-Fa-f]{6}\b/g,LC=/(?:= |ΔE00 )(\d+(?:\.\d+)?)(?::1)?[\s\S]*?need (\d+(?:\.\d+)?)/,FC=e=>{let t=0;for(const n of e){const r=n.match(LC);if(!r){t+=1;continue}const o=Number(r[1]),s=Number(r[2]);t+=s>0?Math.min(1,Math.max(0,(s-o)/s)):1}return t},zf=e=>e.length*1e3+FC(e),UC=[.5,-.5,1,-1,2,-2,4,-4,7,-7,11,-11],BC=[.7,.85,1.15,1.35],HC=60,zg=(e,t,n=e,{pinned:r=[],maxEvaluations:o=Number.POSITIVE_INFINITY,lightnessOnly:s=!1}={})=>{const a=new Set(r),c=h=>a.has("onAccent")?h:Ds(h,n);let l=0,d=c(e),u=ui(d,t),f=zf(u);for(let h=0;h<HC&&u.length>0;h++){let m=null;for(const y of NC(d,u)){if(a.has(y))continue;const[b,v,p]=ie(d[y]),A=[...UC.map(k=>lt(b+k,v,p)),...s?[]:BC.map(k=>lt(b,v*k,p*k))];for(const k of A){if(k===d[y])continue;if(++l>o)return{palette:d,findings:u};const T=c({...d,[y]:k}),F=ui(T,t),C=zf(F);C<(m?m.score:f)-1e-9&&(m={next:T,findings:F,score:C})}}if(!m)break;d=m.next,u=m.findings,f=m.score}return{palette:d,findings:u}},WC=5,GC=[1,1.15],zC=[{spread:1,narrow:!0},{spread:1,narrow:!0,ease:0},...GC.map(e=>({spread:e})),{spread:1,travel:.5,soft:!0},{spread:1,travel:0,soft:!0}],Kf=.015,KC=(e,t,n)=>{const r=oe(Bt(e.ink),Bt(e.canvas)),o=oe(t.ink,t.canvas),s=ie(Bt(e.canvas))[0],a=ie(t.canvas)[0],c=n>0==(e.mode==="light")?1:-1;return n>0?o>=r-Kf&&(a-s)*c>=-.05:o<=r+Kf},VC=(e,t,n,r)=>{const s=oe(Bt(t.ink),Bt(t.canvas))*(1-Wg*(Math.abs(n)/100)),a=e.mode==="dark"?-1:1,c=["ink","inkMuted","inkDim"].filter(d=>ot(e[d]));let l=e;for(const d of[c,c.slice(0,2),c.slice(0,1)]){const u=Object.fromEntries(d.map(f=>[f,ie(l[f])]));for(let f=.25;f<=20;f+=.25){if(oe(l.ink,l.canvas)<=s)return l;const h={...l};for(const m of d){const[y,b,v]=u[m];h[m]=lt(y+a*f,b,v)}if(ui(Ds(h,t),r).length>0)break;l=Ds(h,t)}}for(let d=0;d<6&&oe(l.ink,l.canvas)>s;d++){let u=null;for(const f of[0,1,2])for(const h of[1,-1]){const y=Number.parseInt(l.ink.slice(1+2*f,3+2*f),16)+h;if(y<0||y>255)continue;const b=`#${l.ink.slice(1,1+2*f)}${y.toString(16).padStart(2,"0").toUpperCase()}${l.ink.slice(3+2*f)}`,v=oe(b,l.canvas);if(v>=oe(l.ink,l.canvas))continue;const p=Ds({...l,ink:b},t);ui(p,r).length>0||(!u||v>u.r)&&(u={r:v,next:p})}if(!u)break;l=u.next}return l},ZC=(e,t,{id:n="custom"}={})=>{if(!Number.isInteger(t)||t<-100||t>100)throw new RangeError(`contrast must be an integer in -100..100, got ${t}`);if(t===0)return{palette:e,effectiveContrast:0};const r=Math.sign(t);for(let o=t;o!==0;o-=r*Math.min(WC,Math.abs(o)))for(const s of zC){if((s.narrow||s.soft)&&o>0)continue;const a=Gg(e,o,s),c=zg(a,n,e);if(o<0&&c.findings.length===0&&(c.palette=VC(c.palette,e,o,n)),c.findings.length===0&&KC(e,c.palette,o))return{palette:c.palette,effectiveContrast:o}}return{palette:e,effectiveContrast:0}},Vn=/^#[0-9A-Fa-f]{6}$/,YC=/^#[0-9A-Fa-f]{3}$/,_t=e=>{if(typeof e!="string")return null;let t=e.trim();return t.startsWith("#")||(t=`#${t}`),YC.test(t)&&(t=`#${[...t.slice(1)].map(n=>n+n).join("")}`),Vn.test(t)?t.toUpperCase():null},JC=["accentHover","accentActive","accentWash","chartBarHover"],Ft=e=>{const[t,n,r]=ie(e);return[t,Math.hypot(n,r),Math.atan2(r,n)]},QC=e=>Ft(e)[1],fi=(e,t,n)=>lt(e,Math.max(0,t)*Math.cos(n),Math.max(0,t)*Math.sin(n)),XC=4,qC=(e,t,n)=>{const[r,o,s]=Ft(e),[a,c,l]=Ft(t),[d,u,f]=Ft(n);return o<XC?fi(d+(a-r),c,f):fi(d+(a-r),u*(c/o),f+(l-s))},eO=(e,t,n)=>{if(!e||e.kind==="theme")return null;if(e.kind==="theme-alt")return _t(t.accentAlt);if(e.kind==="palette"){const r=typeof n=="function"?n(e.id):null;return _t(r)}return e.kind==="custom"?_t(e.hex):null},tO=(e,t,{authored:n=e,id:r="custom",paletteAccent:o,preserveSecondary:s=!1}={})=>{const a=eO(t,n,o);if(!a)return{palette:e,applied:!1,adjusted:0,requested:a};const c={...e,accent:a};for(const h of JC)!Vn.test(n[h]??"")||!Vn.test(n.accent??"")||(c[h]=qC(n.accent,n[h],a));if(Vn.test(e.accentWash??"")&&Vn.test(n.accentWash??"")){const h=Ft(e.accentWash)[0],[,m,y]=Ft(c.accentWash);c.accentWash=fi(h,Math.max(m,Ft(n.accentWash)[1]),y)}if(QC(c.surface)<pn){const h=Ft(c.accent)[2];for(const m of["rowHover","rowSelected"]){if(!Vn.test(c[m]??""))continue;const[y,b]=Ft(c[m]);b>=pn&&(c[m]=fi(y,b,h))}}!s&&t.kind==="theme-alt"?Ft(n.accent)[1]>=Zo&&(c.accentAlt=_t(n.accent)):!s&&de(c.accent,c.accentAlt)<cn&&Ft(n.accent)[1]>=Zo&&(c.accentAlt=_t(n.accent));const l=ie(c.accent)[0];c.accent=Ic(c,"accent",nO,4.5,h=>de(h,c.ink)>=3);const d=ie(c.accent)[0]-l;if(d!==0)for(const h of["accentHover","accentActive","chartBarHover"]){if(!Vn.test(c[h]??""))continue;const[m,y,b]=ie(c[h]);c[h]=lt(m+d,y,b)}c.onAccent=Hl(c.accent,[n.onAccent,c.ink,c.canvas,"#FFFFFF","#000000"]);const u=zg(c,r,n);return s&&Lg.filter(h=>h.storage==="overrides").flatMap(h=>[h.role,...h.variants]).some(h=>u.palette[h]!==e[h])||u.findings.length>0||de(u.palette.accent,u.palette.ink)<3?{palette:e,applied:!1,adjusted:0,requested:a}:{palette:u.palette,applied:!0,adjusted:de(a,u.palette.accent),requested:a}},nO=["canvas","surface","elevated","sunken","accentWash","messageSurface","warningWash"],Vf=["dark","light"],rO=12,ED=50,AD="custom-themes-storage",oO=60,Kg=Object.freeze({dark:0,light:0}),xn=Object.freeze({kind:"theme"}),Vg=Object.freeze({dark:xn,light:xn}),Rc=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(-100,Math.min(100,Math.round(e))),Zg=e=>!e||typeof e!="object"?Kg:{dark:Rc(e.dark),light:Rc(e.light)},xc=(e,t=()=>!0)=>{if(!e||typeof e!="object")return xn;switch(e.kind){case"theme":return xn;case"theme-alt":return{kind:"theme-alt"};case"palette":return typeof e.id=="string"&&t(e.id)?{kind:"palette",id:e.id}:xn;case"custom":{const n=_t(e.hex);return n?{kind:"custom",hex:n}:xn}default:return xn}},Yg=(e,t)=>!e||typeof e!="object"?Vg:{dark:xc(e.dark,t),light:xc(e.light,t)},Ur=e=>{if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=_t(n);if(r&&!t.includes(r)&&t.push(r),t.length===rO)break}return t},sO=(e,t)=>{const n=_t(t);return Ur(n?[n,...Array.isArray(e)?e:[]]:e)},iO=/^custom-[a-z0-9]{1,30}$/,Wl=e=>typeof e=="string"&&iO.test(e)?e:null,ID=(e,{isThemeName:t,isRole:n})=>{if(!e||typeof e!="object"||e.format!=="local-operator-theme"||e.version!==1)return null;const r=Wl(e.id);if(!r||!jc(r)||typeof e.base!="string"||!t(e.base))return null;const o=typeof e.name=="string"&&e.name.trim()?e.name.trim().slice(0,oO):null;if(!o)return null;const s=a=>{const c={};if(!a||typeof a!="object")return c;for(const[l,d]of Object.entries(a)){if(!n(l))continue;const u=_t(d);u&&$c(u)&&(c[l]=u)}return c};return{format:"local-operator-theme",version:1,id:r,name:o,base:e.base,seeds:s(e.seeds),overrides:s(e.overrides),updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:0}},Qt=Object.freeze(Object.entries(wC).sort(([,e],[,t])=>e-t).map(([e,t])=>Object.freeze({name:e,value:t}))),Zf=5,aO=8,cO=e=>Math.max(-100,Math.min(100,e)),RD=(e,{snap:t=!0}={})=>{if(!Number.isFinite(e))return 0;const n=cO(Math.round(e/Zf)*Zf);if(!t)return n;for(const{value:r}of Qt)if(Math.abs(e-r)<=aO)return r;return n},lO=e=>Qt.find(t=>t.value===e)?.name??null,xD=e=>{let t=Qt[2];for(const n of Qt){const r=Math.abs(n.value-e),o=Math.abs(t.value-e);(r<o||r===o&&Math.abs(n.value)<Math.abs(t.value))&&(t=n)}return t.name},TD=e=>{if(lO(e))return null;for(let t=1;t<Qt.length;t++)if(e<Qt[t].value)return[Qt[t-1].name,Qt[t].name];return null},CD=(e,t)=>{const r=(t>0?Qt:[...Qt].reverse()).find(o=>t>0?o.value>e:o.value<e);return r?r.value:e},dO=[[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"]],Gl=8,zl=e=>{const[t,n,r]=ie(e),o=Math.atan2(r,n)*180/Math.PI;return{L:t,C:Math.hypot(n,r),h:o<0?o+360:o}},OD=e=>{const{C:t,h:n}=zl(e);if(t<Gl)return"neutral";for(const[r,o]of dO)if(n<r)return o;return"pink"},PD=(e,t,n)=>{const r=e.find(l=>l.id===n)?.palette.accent,o=e.filter(l=>l.palette.mode===t&&l.id!==n&&typeof l.palette.accent=="string"&&l.palette.accent.toUpperCase()!==r?.toUpperCase()),s=new Map;let a=null;for(const l of o){const{C:d,h:u}=zl(l.palette.accent);if(d<Gl){(!a||d<a.C)&&(a={...l,C:d});continue}const f=Math.floor(u/36),h=Math.abs(u-(f*36+18)),m=s.get(f);(!m||h<m.off||h===m.off&&l.id<m.id)&&s.set(f,{...l,off:h})}const c=[...s.entries()].sort(([l],[d])=>l-d).map(([,l])=>({id:l.id,hex:l.palette.accent.toUpperCase()}));return a&&c.push({id:a.id,hex:a.palette.accent.toUpperCase()}),c},MD=(e,t)=>{const n=new Set,r=[];for(const s of e){if(s.palette.mode!==t)continue;const a=String(s.palette.accent).toUpperCase();n.has(a)||(n.add(a),r.push({id:s.id,hex:a}))}const o=s=>{const{C:a,h:c}=zl(s);return a<Gl?1e3:c};return r.sort((s,a)=>o(s.hex)-o(a.hex))},uO=40,Ls=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return{};const n={};for(const r of Array.isArray(t)?t:[]){const o=e[r];if(typeof o!="string")continue;const s=[...o].map(a=>{const c=a.codePointAt(0)??0;return c<32||c===127?" ":a}).join("").replace(/\s+/g," ").trim().slice(0,uO);s&&(n[r]=s)}return n},jD=Object.freeze({strip:"lo-preview",chip:e=>`lo-preview-${e}`}),$D=(e,t,n=null)=>{const r=[];for(const{id:o,contrast:s}of t){if(!jc(o))continue;const a=s===0?e:Gg(e,s),c=n?{...a,...n}:a;Object.entries(c).every(([d,u])=>d==="mode"||$c(u))&&r.push(rp(o,c))}return r.join(`
65
+ `)},ND=e=>{const[t,n,r]=ie(e),o=Math.atan2(r,n)*180/Math.PI;return{l:t,c:Math.hypot(n,r),h:o<0?o+360:o}},DD=({l:e,c:t,h:n})=>{const r=Math.max(0,Math.min(100,e)),o=n*Math.PI/180;for(let s=Math.max(0,t);s>=0;s-=1){const a=ii([r,s*Math.cos(o),s*Math.sin(o)]);if(a)return a}return ii([r,0,0])??"#000000"},LD=e=>{const t=oe("#FFFFFF",e),n=oe("#000000",e);return t>=n?{ink:"#FFFFFF",ratio:t}:{ink:"#000000",ratio:n}},FD=Object.freeze(["accent","accentHover","accentActive","accentWash","onAccent","chartBarHover","accentAlt","accentAltWash"]),Yf=64,Tc=["canvas","run","browser","console","code"],fO={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function Jg(e){return typeof e=="string"&&Tc.includes(e)}function Kl(e){return e.startsWith("draft:")}function ns(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function Vl(e){return e.length>Yf?e.slice(e.length-Yf):e}function Qg(e,t,n){return Vl([...e.filter(([r])=>r!==t),[t,n]])}function pO(e,t,n){return ns(e,t)!==n?e:e.filter(([r])=>r!==t)}function hO(e,t){return ns(e,t)===void 0?e:e.filter(([n])=>n!==t)}function mO(e,t,n){const r=ns(e,t);return r===void 0?e:Vl([...e.filter(([o])=>o!==t&&o!==n),[n,r]])}const Jf=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function Qf(e,t,n){if(n||typeof t!="string")return Jf;const r=ns(e,t);return r===void 0?Jf:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function gO(e){if(!Array.isArray(e))return[];const t=new Map;for(const n of e){if(!Array.isArray(n)||n.length!==2)continue;const[r,o]=n;typeof r!="string"||r===""||Kl(r)||Jg(o)&&(t.delete(r),t.set(r,o))}return Vl([...t.entries()])}function UD(e){const t=new Set(Object.keys(e.forgotten));for(const[n,r]of Object.entries(e.archiveFacts))r?.archived===!0&&r.answered===!0&&t.add(n);return t}function Xf(e){return fO[e]}const _O={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},rs=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,ji=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,bO=e=>{const t=rs(e);return t===null||t==="ask"?null:_O[t]},An=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:Qg(e.rightSlotMemory,n,t)}},so=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=pO(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},vO=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=hO(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},yO=Object.freeze({mounted:!1,session:!1}),Xg=Object.freeze([]);function BD(e,t){const n=rs(t);if(n===null||!ji(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=io(jl,t.rightSlotWidth);break;case"run":r=io(ep,t.rightSlotWidth);break;case"browser":r=io(AO,t.rightSlotWidth);break;case"console":r=io(IO,t.rightSlotWidth);break;case"code":r=io(ep,t.rightSlotWidth);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,$l(e)):Math.min(r,Math.max(0,e-Pl))}function io(e,t){return Math.min(yg,Math.max(e,t||wO))}function HD(e){const t=rs(e);return t!==null&&ji(t,e)}function WD(e){const t=rs(e);return t!==null&&ji(t,e)?t:null}function GD(e){const t=rs(e);return(t==="canvas"||t==="ask")&&ji(t,e)}const wO=640,qf=Ti,kO=20,SO=4,EO=20,ep=320,AO=480,IO=480,RO=5e3,zD=(e,t)=>e.some(n=>n.surface===t),KD=(e,t=Date.now())=>e.some(n=>t-n.at<RO),xO=[],TO=5,CO=["chatMeasureWidth"],VD=Qo()(_i((e,t)=>({finderFiles:Pg,setFinderFiles:n=>e({finderFiles:Ll({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:$g,agentAvatarSize:Sg,themeName:a_,contrast:Kg,accent:Vg,customAccents:[],customAccentNames:{},customThemeId:null,setContrast:(n,r)=>e(o=>({contrast:{...o.contrast,[n]:Rc(r)}})),setAccent:(n,r)=>e(o=>({accent:{...o.accent,[n]:xc(r,Pc)}})),addCustomAccent:(n,r)=>e(o=>{const s=sO(o.customAccents,n),a=_t(n),c=Ls(o.customAccentNames,s);return!r||!a?{customAccents:s,customAccentNames:c}:{customAccents:s,customAccentNames:c,accent:{...o.accent,[r]:{kind:"custom",hex:a}}}}),removeCustomAccent:n=>e(r=>{const o=_t(n),s={...r.accent};for(const c of Vf){const l=s[c];l.kind==="custom"&&l.hex===o&&(s[c]=xn)}const a={...r.customAccentNames};return o&&delete a[o],{customAccents:r.customAccents.filter(c=>c!==o),customAccentNames:a,accent:s}}),renameCustomAccent:(n,r)=>e(o=>{const s=_t(n);return!s||!o.customAccents.includes(s)?{}:{customAccentNames:Ls({...o.customAccentNames,[s]:r},o.customAccents)}}),replaceCustomAccent:(n,r)=>e(o=>{const s=_t(n),a=_t(r);if(!s||!a||s===a)return{};if(o.customAccents.indexOf(s)<0)return{};const l=o.customAccents.filter(h=>h!==a);l.splice(l.indexOf(s),1,a);const d=Ur(l),u={...o.customAccentNames};u[s]!==void 0&&u[a]===void 0&&(u[a]=u[s]),delete u[s];const f={...o.accent};for(const h of Vf){const m=f[h];m.kind==="custom"&&m.hex===s&&(f[h]={kind:"custom",hex:a})}return{customAccents:d,customAccentNames:Ls(u,d),accent:f}}),rightSlotWidth:0,chatSidebarWidth:qf,chatSidebarRegions:RT,chatSidebarView:wr,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:Xg,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:yO,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:xO,isCreateAgentDialogOpen:!1,mentionRecents:null,profileRecents:{agent:[],team:[]},conversationRecents:[],shortcutBindings:{},openCreateAgentDialog:()=>{e({isCreateAgentDialogOpen:!0})},closeCreateAgentDialog:()=>{e({isCreateAgentDialogOpen:!1})},openCommandPalette:()=>{e({isCommandPaletteOpen:!0})},closeCommandPalette:()=>{e({isCommandPaletteOpen:!1,commandPaletteQuery:""})},toggleCommandPalette:(n="")=>{e(r=>({isCommandPaletteOpen:!r.isCommandPaletteOpen,commandPaletteQuery:r.isCommandPaletteOpen?r.commandPaletteQuery:n}))},setCommandPaletteQuery:n=>{e({commandPaletteQuery:n})},toggleSidebar:()=>{e(n=>({isSidebarCollapsed:!n.isSidebarCollapsed}))},setSidebarOverflowExpanded:n=>{e({sidebarOverflowExpanded:n})},setSidebarCollapsed:n=>{e({isSidebarCollapsed:n})},setShowAgentReasoning:n=>{e({showAgentReasoning:n})},setTranscriptDisplayMode:n=>{e({transcriptDisplayMode:n})},setAgentAvatarSize:n=>{e({agentAvatarSize:n})},setTheme:n=>{e({themeName:n,customThemeId:null})},setCanvasOpen:n=>{e(r=>n?{...An("isCanvasOpen"),...Wn(r,"canvas")}:{isCanvasOpen:!1,...so(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...An("isRunPanelOpen"),...Wn(r,"run")}:{isRunPanelOpen:!1,...so(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...An("isBrowserPaneOpen"),...Wn(r,"browser")}:{isBrowserPaneOpen:!1,...so(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...An("isConsolePaneOpen"),...Wn(r,"console")}:{isConsolePaneOpen:!1,...so(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...An("isCodeReviewPaneOpen"),...Wn(r,"code")}:{isCodeReviewPaneOpen:!1,...so(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...An("isCodeReviewPaneOpen"),...Wn(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,o)=>{e(s=>{const a=typeof s.rightSlotKey=="string";if(n)return{...An("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:a?null:bO(s),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?o?.dismissSlot?{...c,...vO(s)}:{...c,...Qf(s.rightSlotMemory,s.rightSlotKey,!1)}:s.rightSlotKey===null?o?.dismissSlot?{...c,rightSlotLegacySeed:null}:c:o?.dismissSlot?{...c,rightSlotLegacySeed:null}:{...c,...s.askDrawerEvictedPane===null?null:{[s.askDrawerEvictedPane]:!0}}})},requestAskOpen:(n,r="menu")=>{e({askOpenIntent:{scope:n,via:r}})},clearAskOpenIntent:n=>{e(r=>r.askOpenIntent?.scope===n?{askOpenIntent:null}:{})},setConsoleActiveSurface:n=>{e({consoleActiveSurface:n})},requestConsoleOpen:n=>{e({consoleOpenIntent:n})},clearConsoleOpenIntent:n=>{e(r=>r.consoleOpenIntent===n?{consoleOpenIntent:null}:{})},setConsoleLiveSurface:(n,r)=>{e(o=>{if(n===null||r<=0)return o.consoleLiveSurface===null?{}:{consoleLiveSurface:null};const s=o.consoleLiveSurface;return s?.sessionId===n&&s.count===r?{}:{consoleLiveSurface:{sessionId:n,count:r}}})},markConsoleUnseen:(n,r)=>{e(o=>o.consoleUnseen.some(s=>s.surface===r)?{}:{consoleUnseen:[...o.consoleUnseen,{sessionId:n,surface:r,at:Date.now()}]})},clearConsoleUnseen:n=>{const r=Array.isArray(n)?n:[n];e(o=>{const s=o.consoleUnseen.filter(a=>!r.includes(a.surface));return s.length===o.consoleUnseen.length?{}:{consoleUnseen:s}})},setRightSlotWidth:n=>{e({rightSlotWidth:n})},restoreDefaultRightSlotWidth:()=>{e({rightSlotWidth:0})},bindRightSlotKey:(n,r)=>{e(o=>{let s=o.rightSlotMemory,a=o.rightSlotLegacySeed;const c=r?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(s=mO(s,c,n)),n===null||(Kl(n)?a=null:a!==null&&ns(s,n)===void 0&&(s=Qg(s,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:s,rightSlotLegacySeed:a,...Qf(s,n,o.isAskDrawerOpen)}})},setRightSlotRoute:n=>{const r=t().rightSlotRoute;r.mounted===n.mounted&&r.session===n.session||e({rightSlotRoute:{...n}})},setShortcutBinding:(n,r,o)=>{if(r===null){e(a=>{const c={...a.shortcutBindings};return delete c[n],{shortcutBindings:c}});return}const s=Ul(r);s!==null&&HT(s,n,t().shortcutBindings,"linux",o)===null&&e(a=>({shortcutBindings:{...a.shortcutBindings,[n]:s}}))},clearShortcutBinding:n=>{e(r=>({shortcutBindings:{...r.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(r=>({...An("isRunPanelOpen"),...Wn(r,"run"),runPanelReveal:{section:n,nonce:(r.runPanelReveal?.nonce??0)+1}}))},clearRunPanelReveal:n=>{e(r=>r.runPanelReveal?.nonce===n?{runPanelReveal:null}:{})},setChatSidebarWidth:n=>{e({chatSidebarWidth:Math.min(Ol,Math.max(Cl,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:qf})},rememberMention:(n,r)=>{e(o=>{const s=o.mentionRecents,a=s?.cwd===n?s.paths:[],c=[r,...a.filter(l=>l!==r)].slice(0,kO);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(o=>({profileRecents:{...o.profileRecents,[n]:OO(o.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const o=jO(r.conversationRecents),s=PO(o,n);return s.length===o.length&&s.every((a,c)=>a===o[c])?r:{conversationRecents:s}})}}),{name:"ui-preferences-storage",version:TO,migrate:LO,partialize:$O,merge:DO}));function OO(e,t){return[t,...e.filter(n=>n!==t)].slice(0,SO)}function PO(e,t){return[t,...e.filter(n=>n!==t)].slice(0,EO)}const MO=[];function jO(e){return Array.isArray(e)?e:MO}function $O(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:r,consoleLiveSurface:o,askOpenIntent:s,isAskDrawerOpen:a,askDrawerScope:c,askDrawerEvictedPane:l,rightSlotRoute:d,isCanvasOpen:u,isRunPanelOpen:f,isBrowserPaneOpen:h,isConsolePaneOpen:m,isCodeReviewPaneOpen:y,rightSlotKey:b,...v}=e;return{...v,rightSlotMemory:NO(e.rightSlotMemory)}}function NO(e){return(e??Xg).filter(([t])=>!Kl(t))}function DO(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:o,isBrowserPaneOpen:s,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:Ll(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:gO(n.rightSlotMemory),rightSlotLegacySeed:Jg(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:WT(n.shortcutBindings),contrast:Zg(n.contrast),accent:Yg(n.accent,Pc),customAccents:Ur(n.customAccents),customAccentNames:Ls(n.customAccentNames,Ur(n.customAccents)),customThemeId:Wl(n.customThemeId)}}function LO(e,t){const n={...e??{}};if(t<1&&FO(n),t<2)for(const r of CO)delete n[r];if(t<3){let r=null;for(const o of Tc)if(n[Xf(o)]===!0){r=o;break}r!==null&&(n.rightSlotLegacySeed=r);for(const o of Tc)delete n[Xf(o)]}return t<4&&(n.finderFiles=Ll(n.finderFiles)),t<5&&(n.contrast=Zg(n.contrast),n.accent=Yg(n.accent,Pc),n.customAccents=Ur(n.customAccents),n.customThemeId=Wl(n.customThemeId)),n}function FO(e){const t=[["canvasWidth",800],["runPanelWidth",420],["browserPanelWidth",640],["consolePanelWidth",796]];let n=0;for(const[r,o]of t){const s=e[r];if(typeof s=="number"&&s>0&&s!==o){n=s;break}}for(const[r]of t)delete e[r];e.rightSlotWidth=n}const Cc=e=>e.replace(/\\/g,"/"),ZD=()=>window.location.hash?Cc(window.location.hash.substring(1)):Cc(window.location.pathname),YD=(e,t)=>{if(t!==null&&(e===t||e.startsWith(`${t}/`)||e.startsWith(`${t}\\`))){const r=e.substring(t.length);return r.startsWith("/")||r.startsWith("\\")||r===""?`~${r.replace(/\\/g,"/")}`:`~/${r.replace(/\\/g,"/")}`}return e==="~"?"~":e.replace(/\\/g,"/")},JD=(e,t)=>{if(e.length<=t)return e;const n=e.split("/"),r=n[n.length-1]??"";if(r.length+1>=t)return`…${r.slice(-39)}`;const o=n[0]==="~"||n[0]==="",s=o?n.slice(0,2):n.slice(0,1),a=n.slice(s.length),c=y=>{const b=t-y.length-(y?3:2);let v=[];for(let p=a.length-1;p>=0;p-=1){const A=[a[p],...v];if(A.join("/").length>b)break;v=A}return v},l=(y,b)=>y?`${y}/…/${b.join("/")}`:`…/${b.join("/")}`,d=s.join("/"),u=c(d);if(u.length>0)return u.length===a.length?e:l(d,u);const f=o?n[0]:"",h=c(f);if(h.length>0)return l(f,h);const m=t-(f?`${f}/…/`.length:2);return m>0?l(f,[r.slice(-m)]):"…"},QD=(e,t)=>Cc(e).includes(t),Oc=e=>{const t=JSON.stringify(Object.keys(e).sort().map(r=>[r,e[r]]));let n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n.toString(36).padStart(7,"0").slice(-8)},UO=(e,{contrast:t=0,accent:n={kind:"theme"},id:r,paletteAccent:o,preserveSecondary:s=!1}={})=>{const a=!n||n.kind==="theme";if(t===0&&a)return{identity:!0,palette:e,id:r,effectiveContrast:0,requestedContrast:0,accentApplied:!0,accentAdjusted:0};const c=ZC(e,t,{id:r});let l=c.palette,d=!0,u=0;if(!a){const f=tO(l,n,{authored:e,id:r,paletteAccent:o,preserveSecondary:s});l=f.palette,d=f.applied,u=f.adjusted}return l===e?{identity:!0,palette:e,id:r,effectiveContrast:0,requestedContrast:t,accentApplied:d,accentAdjusted:u}:{identity:!1,palette:l,id:`lo-${Oc(l)}`,effectiveContrast:c.effectiveContrast,requestedContrast:t,accentApplied:d,accentAdjusted:u}},tp="lo-composed-theme",BO=4,Gn=new Map,HO=(e,t)=>{const n=Gn.get(e);if(n)return Gn.delete(e),Gn.set(e,n),n;const r=c_(t);if(Gn.set(e,r),Gn.size>BO){const o=Gn.keys().next().value;o!==void 0&&Gn.delete(o)}return r},WO=e=>Mc(e)?.palette.accent,GO=16,_r=new Map,zO=(e,t,n)=>{const r=np(e.themeName),o=Mc(r.id);if(!o)throw new Error(`no palette for theme ${r.id}`);const s=t??o.palette,a=s.mode,c=n??r.id,l=e.contrast[a]??0,d=e.accent[a],u=JSON.stringify([r.id,n??null,t?Oc(t):null,l,d??null]);let f=_r.get(u);if(f?_r.delete(u):f=UO(s,{contrast:l,accent:d,id:c,preserveSecondary:t!==void 0,paletteAccent:WO}),_r.set(u,f),_r.size>GO){const m=_r.keys().next().value;m!==void 0&&_r.delete(m)}if(f.identity&&!n)return{...f,id:r.id,muiTheme:r.theme};const h=`lo-${Oc(f.palette)}`;return{...f,id:h,identity:!1,muiTheme:HO(h,f.palette)}},KO=(e,t)=>jc(e)&&Object.entries(t).every(([n,r])=>n==="mode"||$c(r))&&(t.mode==="dark"||t.mode==="light"),XD=(e,t=document,n,r,o=s=>zO(s,n,r))=>{let s=o(e);if(!s.identity&&!KO(s.id,s.palette)){console.error(`[theme] refused to publish composed theme ${JSON.stringify(s.id).slice(0,60)}: an id or value is outside the CSS grammar; showing the built-in theme`);const l=np(e.themeName),d=Mc(l.id);if(!d)throw new Error(`no palette for theme ${l.id}`);s={identity:!0,palette:d.palette,id:l.id,effectiveContrast:0,requestedContrast:s.requestedContrast,accentApplied:!1,accentAdjusted:0,muiTheme:l.theme}}const a=t.documentElement,c=t.getElementById(tp);if(s.identity)c?.remove();else{const l=c??t.createElement("style");l.id=tp,l.textContent=rp(s.id,s.palette),c||t.head.appendChild(l)}return Yx(t,s.identity?null:s.palette),a.dataset.theme=s.id,a.classList.toggle("dark",s.palette.mode==="dark"),s},qD=e=>({themeName:e.themeName,customThemeId:e.customThemeId??null,contrast:e.contrast,accent:e.accent}),eL=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{x$ as $,qR as A,QR as B,XD as C,vD as D,qD as E,VD as F,ct as G,PT as H,eL as I,zO as J,Qo as K,uP as L,i as M,Kp as N,Te as O,zd as P,OR as Q,PR as R,gt as S,T$ as T,Wm as U,Nm as V,E$ as W,I$ as X,Dm as Y,A$ as Z,w$ as _,eM as a,_t as a$,S$ as a0,R$ as a1,mN as a2,GP as a3,ZD as a4,aa as a5,Aj as a6,HP as a7,WP as a8,Ym as a9,bP as aA,Fp as aB,Cc as aC,$0 as aD,dP as aE,IM as aF,hP as aG,bv as aH,pP as aI,mP as aJ,qO as aK,cp as aL,Li as aM,Hc as aN,pv as aO,fv as aP,oI as aQ,vR as aR,Rj as aS,Tj as aT,Cj as aU,Em as aV,RN as aW,V1 as aX,IN as aY,Z1 as aZ,Y1 as a_,q$ as aa,eN as ab,xi as ac,EN as ad,jO as ae,bn as af,st as ag,Hr as ah,Ic as ai,JO as aj,Nw as ak,p$ as al,t$ as am,yP as an,XO as ao,Ue as ap,Ba as aq,_i as ar,Xv as as,mo as at,XP as au,zP as av,cy as aw,ly as ax,Qd as ay,vP as az,ZP as b,mn as b$,rO as b0,OD as b1,LD as b2,uO as b3,lN as b4,lO as b5,xD as b6,Qt as b7,jD as b8,Zf as b9,Y_ as bA,yd as bB,Z_ as bC,K_ as bD,cN as bE,_x as bF,X$ as bG,B$ as bH,QD as bI,lP as bJ,cP as bK,aP as bL,iP as bM,fP as bN,Sv as bO,Lt as bP,vo as bQ,Wp as bR,Fv as bS,Fw as bT,QP as bU,NP as bV,JP as bW,YP as bX,WD as bY,wD as bZ,Xj as b_,RD as ba,TD as bb,CD as bc,PD as bd,MD as be,$D as bf,FD as bg,tS as bh,lx as bi,qP as bj,Lg as bk,UO as bl,ND as bm,SD as bn,xT as bo,_D as bp,Yo as bq,rt as br,sp as bs,$_ as bt,F_ as bu,H_ as bv,V_ as bw,G_ as bx,z_ as by,vd as bz,Qi as c,WN as c$,xd as c0,Gc as c1,vy as c2,mi as c3,Pp as c4,TR as c5,k$ as c6,ae as c7,y$ as c8,yr as c9,VN as cA,ZN as cB,vT as cC,kf as cD,NN as cE,iD as cF,aD as cG,cD as cH,$N as cI,Jm as cJ,aN as cK,lD as cL,YN as cM,qN as cN,eD as cO,JN as cP,QN as cQ,wr as cR,PN as cS,Og as cT,BN as cU,oD as cV,Ko as cW,rD as cX,sD as cY,jr as cZ,ff as c_,dc as ca,uc as cb,b$ as cc,v$ as cd,h$ as ce,m$ as cf,g$ as cg,kD as ch,KD as ci,RO as cj,zD as ck,Up as cl,DP as cm,TP as cn,Hp as co,Rw as cp,xv as cq,y_ as cr,Tv as cs,Dl as ct,PP as cu,lf as cv,LP as cw,cx,$$ as cy,YD as cz,Je as d,sN as d$,HN as d0,GN as d1,KN as d2,zN as d3,DN as d4,tD as d5,nD as d6,TN as d7,CN as d8,C$ as d9,bD as dA,sP as dB,uI as dC,oM as dD,HD as dE,yc as dF,yO as dG,io as dH,BD as dI,vN as dJ,yN as dK,bN as dL,jl as dM,$l as dN,$P as dO,jP as dP,AO as dQ,yg as dR,IO as dS,ep as dT,Pl as dU,Sj as dV,Ej as dW,rN as dX,nN as dY,oN as dZ,iN as d_,P$ as da,MN as db,O$ as dc,Ci as dd,jN as de,tN as df,Cg as dg,XN as dh,FN as di,UN as dj,LN as dk,ON as dl,dD as dm,uD as dn,hD as dp,mD as dq,IT as dr,fD as ds,Ts as dt,Vo as du,pD as dv,gD as dw,gP as dx,AN as dy,JD as dz,tM as e,W_ as e$,r0 as e0,es as e1,VP as e2,Z$ as e3,mp as e4,Ai as e5,qj as e6,Mj as e7,l$ as e8,d$ as e9,Fl as eA,o$ as eB,Ah as eC,Zs as eD,CM as eE,Ln as eF,nr as eG,Iv as eH,yD as eI,La as eJ,SN as eK,_N as eL,L1 as eM,wg as eN,nM as eO,rM as eP,x_ as eQ,OT as eR,rP as eS,Kl as eT,UD as eU,gd as eV,nP as eW,tP as eX,xa as eY,ko as eZ,P_ as e_,Vm as ea,nx as eb,Ei as ec,Y$ as ed,J$ as ee,H0 as ef,e$ as eg,Nj as eh,U$ as ei,cR as ej,YR as ek,Km as el,VR as em,of as en,H$ as eo,z1 as ep,V$ as eq,_$ as er,EP as es,IP as et,AP as eu,BP as ev,Pi as ew,Mi as ex,Dg as ey,HT as ez,Dw as f,ID as f$,J_ as f0,KS as f1,dN as f2,dr as f3,fg as f4,fN as f5,E1 as f6,lg as f7,uN as f8,hN as f9,aI as fA,Xh as fB,$g as fC,Oh as fD,sw as fE,CP as fF,Ij as fG,xj as fH,$j as fI,jj as fJ,Oj as fK,sI as fL,Fj as fM,Lj as fN,Ar as fO,MP as fP,FP as fQ,OP as fR,TM as fS,xM as fT,pM as fU,tl as fV,Qc as fW,Dn as fX,qt as fY,ui as fZ,ED as f_,gN as fa,UP as fb,KP as fc,gi as fd,At as fe,j_ as ff,ix as fg,GD as fh,kN as fi,Ml as fj,wN as fk,vg as fl,H1 as fm,Cl as fn,RP as fo,Pd as fp,tw as fq,xP as fr,Mv as fs,n$ as ft,Gj as fu,zj as fv,kP as fw,SP as fx,Wj as fy,Am as fz,Vc as g,QM as g$,DD as g0,Hl as g1,vC as g2,yC as g3,zg as g4,AD as g5,Wl as g6,KM as g7,Eu as g8,JM as g9,fj as gA,mj as gB,vE as gC,na as gD,pj as gE,SE as gF,cj as gG,qM as gH,ij as gI,bj as gJ,XM as gK,aj as gL,dj as gM,yj as gN,vj as gO,lj as gP,ej as gQ,tj as gR,nj as gS,rj as gT,oj as gU,sj as gV,_j as gW,Cv as gX,Ov as gY,Pv as gZ,hu as g_,YM as ga,ZM as gb,VM as gc,$S as gd,Zk as ge,zk as gf,Yk as gg,Cr as gh,GM as gi,WM as gj,DM as gk,OM as gl,PM as gm,jM as gn,MM as go,Ph as gp,BM as gq,V0 as gr,wj as gs,dk as gt,HM as gu,kE as gv,hj as gw,Kh as gx,gj as gy,uj as gz,hp as h,a0 as h$,_M as h0,FM as h1,SS as h2,Ch as h3,hh as h4,wM as h5,jd as h6,Ul as h7,CT as h8,T0 as h9,D$ as hA,L$ as hB,M$ as hC,j$ as hD,F$ as hE,Nl as hF,q1 as hG,wP as hH,oc as hI,Pj as hJ,s$ as hK,i$ as hL,c$ as hM,rI as hN,a$ as hO,u$ as hP,bR as hQ,f$ as hR,Zw as hS,N$ as hT,oh as hU,Do as hV,mM as hW,w0 as hX,sh as hY,Xc as hZ,th as h_,NM as ha,yS as hb,UM as hc,zM as hd,LM as he,ck as hf,vM as hg,ek as hh,kM as hi,SM as hj,AM as hk,EM as hl,RM as hm,$M as hn,kj as ho,xN as hp,Zj as hq,Kj as hr,yI as hs,Jj as ht,Vj as hu,Yj as hv,Qj as hw,bM as hx,yM as hy,Xn as hz,Zv as i,c0 as i0,fM as i1,Av as i2,uM as i3,aM as i4,lM as i5,lu as i6,iM as i7,sM as i8,dM as i9,du as ia,cM as ib,Np as ic,gM as id,hM as ie,z$ as ig,Dj as ih,Hj as ii,Uj as ij,Bj as ik,W$ as il,G$ as im,hv as io,Md as ip,eP as iq,r$ as ir,Yv as j,Jv as k,Qv as l,QO as m,f_ as n,Q_ as o,_P as p,pN as q,Uw as r,k1 as s,zw as t,L_ as u,oP as v,hx as w,St as x,K$ as y,Q$ as z};