local-operator-ui 0.57.3 → 0.57.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/out/main/index.js +1044 -63
  2. package/out/preload/index.js +102 -21
  3. package/out/renderer/assets/{_basePickBy-BeAzmqgq.js → _basePickBy-D2upKftS.js} +1 -1
  4. package/out/renderer/assets/{_baseUniq-Clx9gdFs.js → _baseUniq-BGD19KIN.js} +1 -1
  5. package/out/renderer/assets/{agent-details-page-BMztNR89.js → agent-details-page-OPyFw_dI.js} +1 -1
  6. package/out/renderer/assets/{agent-hub-page-quUNNwcr.js → agent-hub-page-B3V1y16n.js} +1 -1
  7. package/out/renderer/assets/{agents-page-BTYHgMAf.js → agents-page-CowgZsSO.js} +3 -3
  8. package/out/renderer/assets/appearance-DO4VPBSi.js +65 -0
  9. package/out/renderer/assets/{approvalsOverlay-BxwEca1y.js → approvalsOverlay-CBPXn0ct.js} +1 -1
  10. package/out/renderer/assets/{arc-BOZHzyJm.js → arc-Cv6N9gTJ.js} +1 -1
  11. package/out/renderer/assets/{architectureDiagram-IEHRJDOE-CpE8Siol.js → architectureDiagram-IEHRJDOE-DHtB5fE0.js} +1 -1
  12. package/out/renderer/assets/{avatar-cropper-BWJE7j7A.js → avatar-cropper-Bjo9zUPg.js} +1 -1
  13. package/out/renderer/assets/{blockDiagram-JOT3LUYC-D4LTtQ_H.js → blockDiagram-JOT3LUYC-4WEK73Je.js} +1 -1
  14. package/out/renderer/assets/{book-open-fa_DaJBq.js → book-open-CmfjhXrg.js} +1 -1
  15. package/out/renderer/assets/browser-page-2S7sbehs.js +1 -0
  16. package/out/renderer/assets/{browser-webauthn-prompt-VC7pNm9O.js → browser-webauthn-prompt-D8Tgtg83.js} +1 -1
  17. package/out/renderer/assets/{c4Diagram-VJAJSXHY-DRtUDXOF.js → c4Diagram-VJAJSXHY-kaGHtOK6.js} +1 -1
  18. package/out/renderer/assets/channel-DRHru1K8.js +1 -0
  19. package/out/renderer/assets/{chunk-4BMEZGHF-Cw4VudrA.js → chunk-4BMEZGHF-CpC8J2AT.js} +1 -1
  20. package/out/renderer/assets/{chunk-A2AXSNBT-0JOiKMb-.js → chunk-A2AXSNBT-DKmX4atq.js} +1 -1
  21. package/out/renderer/assets/{chunk-AEK57VVT-CAKCg9DA.js → chunk-AEK57VVT-Dtej3BD4.js} +1 -1
  22. package/out/renderer/assets/{chunk-D6G4REZN-CFZ2DTGX.js → chunk-D6G4REZN-DUXxF-pw.js} +1 -1
  23. package/out/renderer/assets/{chunk-RZ5BOZE2-CupwUHva.js → chunk-RZ5BOZE2-DeeJjU3w.js} +1 -1
  24. package/out/renderer/assets/{chunk-XZIHB7SX-B1vcbFku.js → chunk-XZIHB7SX-D4R6kzHb.js} +1 -1
  25. package/out/renderer/assets/classDiagram-GIVACNV2-Cs0VSRpc.js +1 -0
  26. package/out/renderer/assets/classDiagram-v2-COTLJTTW-Cs0VSRpc.js +1 -0
  27. package/out/renderer/assets/clone-_NlCUljT.js +1 -0
  28. package/out/renderer/assets/{console-mirror-IB35kNI8.js → console-mirror-Bp3thuUi.js} +1 -1
  29. package/out/renderer/assets/{consoleCapture-D4G96kDb.js → consoleCapture-BJR8BDEY.js} +1 -1
  30. package/out/renderer/assets/{conversation-input-sync-DlorrZ6B.js → conversation-input-sync-FnnZiNnd.js} +4 -4
  31. package/out/renderer/assets/{dagre-OKDRZEBW-CunvCCGM.js → dagre-OKDRZEBW-DDY_IkmM.js} +1 -1
  32. package/out/renderer/assets/{diagram-SSKATNLV-DlpXMePq.js → diagram-SSKATNLV-D7AGoSSj.js} +1 -1
  33. package/out/renderer/assets/{diagram-VNBRO52H-CtgMK6MT.js → diagram-VNBRO52H-CcgAGaBN.js} +1 -1
  34. package/out/renderer/assets/{erDiagram-Q7BY3M3F-C-QNezLB.js → erDiagram-Q7BY3M3F-LEYxek3-.js} +1 -1
  35. package/out/renderer/assets/{error-boundary-C1x5W-AX.js → error-boundary-BsWceBKP.js} +1 -1
  36. package/out/renderer/assets/{flowDiagram-4HSFHLVR-DjwRYw0E.js → flowDiagram-4HSFHLVR-CQLUaH8T.js} +1 -1
  37. package/out/renderer/assets/{ganttDiagram-APWFNJXF-Tb5F1KXD.js → ganttDiagram-APWFNJXF-Ole27PT-.js} +1 -1
  38. package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-BokP9Y1T.js → gitGraphDiagram-7IBYFJ6S-BNYa___9.js} +1 -1
  39. package/out/renderer/assets/{graph-DEHYXN6b.js → graph-Bibb0aeq.js} +1 -1
  40. package/out/renderer/assets/{heart-DqMMtrJ1.js → heart-Cix0tXFr.js} +1 -1
  41. package/out/renderer/assets/index-BKLUTBo0.css +1 -0
  42. package/out/renderer/assets/index-BKh47kLl.js +857 -0
  43. package/out/renderer/assets/{index-D7fnBkIK.js → index-C9UzsV82.js} +1 -1
  44. package/out/renderer/assets/{index-CJ8BPUHQ.js → index-CMJfInon.js} +1 -1
  45. package/out/renderer/assets/{index-BWQzFq0n.js → index-D0qlrLIs.js} +10 -10
  46. package/out/renderer/assets/infoDiagram-PH2N3AL5-BXhry1Gr.js +2 -0
  47. package/out/renderer/assets/{inline-error-boundary-ChbTvdIh.js → inline-error-boundary-Ba_FWBMT.js} +1 -1
  48. package/out/renderer/assets/{installer-Bplg-bpo.js → installer-bmE_RNOZ.js} +1 -1
  49. package/out/renderer/assets/{journeyDiagram-U35MCT3I-BfXoBW-2.js → journeyDiagram-U35MCT3I-DI32aDKT.js} +1 -1
  50. package/out/renderer/assets/{kanban-definition-NDS4AKOZ-BeT3LOJG.js → kanban-definition-NDS4AKOZ-CZ-ELIdr.js} +1 -1
  51. package/out/renderer/assets/{layout-B71SsWep.js → layout-Dza9PMRJ.js} +1 -1
  52. package/out/renderer/assets/{legacy-agents-page-BaSX_kru.js → legacy-agents-page-CPFGYWOZ.js} +1 -1
  53. package/out/renderer/assets/{library-page-BwmVBhNJ.js → library-page-DiaLon0b.js} +3 -3
  54. package/out/renderer/assets/{log-in-C4tjIXzF.js → log-in-Bd6fDqyJ.js} +1 -1
  55. package/out/renderer/assets/{mermaid.core-D7wfsRjY.js → mermaid.core-BcJdc-X6.js} +5 -5
  56. package/out/renderer/assets/{mesh-page-DbC0RmVo.js → mesh-page-7T5BtRTh.js} +1 -1
  57. package/out/renderer/assets/{messages-B7aIuFuF.js → messages-BYDbMAVA.js} +10 -10
  58. package/out/renderer/assets/{mindmap-definition-ALO5MXBD-BPTOzHuL.js → mindmap-definition-ALO5MXBD-D2CXGzTD.js} +1 -1
  59. package/out/renderer/assets/{mini-DXMqE-0u.js → mini-CJlFVLUZ.js} +1 -1
  60. package/out/renderer/assets/{notebook-pen-CQdB2BC5.js → notebook-pen-D05OGtSm.js} +1 -1
  61. package/out/renderer/assets/{notifications-page-C9PU2typ.js → notifications-page-BjrfZb8l.js} +1 -1
  62. package/out/renderer/assets/{org-access-Fw38H9fZ.js → org-access-B9_h9w7n.js} +1 -1
  63. package/out/renderer/assets/{org-surface-gate-CKBjFWJL.js → org-surface-gate-sm4xQvjq.js} +1 -1
  64. package/out/renderer/assets/{page-header-CAW9G_fb.js → page-header-DXwYxMB-.js} +1 -1
  65. package/out/renderer/assets/{pieDiagram-IB7DONF6-C0JN0KMq.js → pieDiagram-IB7DONF6-DUG4cv-v.js} +1 -1
  66. package/out/renderer/assets/{projects-page-D9F4QotN.js → projects-page-DlCYJUiP.js} +1 -1
  67. package/out/renderer/assets/{publication-validation-DygSOQkj.js → publication-validation-Bn7rmCS6.js} +1 -1
  68. package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-BRgjFQlM.js → quadrantDiagram-7GDLP6J5-DaYms9_B.js} +1 -1
  69. package/out/renderer/assets/{radar-MK3ICKWK-VE0niGVF.js → radar-MK3ICKWK-B97TgRmB.js} +1 -1
  70. package/out/renderer/assets/{radient-auth-buttons-CXMLVkUO.js → radient-auth-buttons-CEfTJcvg.js} +1 -1
  71. package/out/renderer/assets/{requirementDiagram-KVF5MWMF-DkwJBmMi.js → requirementDiagram-KVF5MWMF-DgyICZXf.js} +1 -1
  72. package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-DFv3zh8B.js → sankeyDiagram-QLVOVGJD-DHgZL_Zc.js} +1 -1
  73. package/out/renderer/assets/{schedules-page-aTbxrD_M.js → schedules-page-CNdkudlY.js} +1 -1
  74. package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-BXcr3er8.js → sequenceDiagram-X6HHIX6F-pU2H-s2W.js} +1 -1
  75. package/out/renderer/assets/settings-page-B9GORgXK.js +319 -0
  76. package/out/renderer/assets/{smartart-CWBh1X_F.js → smartart-gFtvTNRW.js} +1 -1
  77. package/out/renderer/assets/{stateDiagram-DGXRK772-Cw08neDd.js → stateDiagram-DGXRK772-HwW2OpHh.js} +1 -1
  78. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-BwCPC1S5.js +1 -0
  79. package/out/renderer/assets/{team-bridge-page-BHAdGSZS.js → team-bridge-page-ChcIcnje.js} +17 -17
  80. package/out/renderer/assets/{timeline-definition-BDJGKUSR-B-ZFBehC.js → timeline-definition-BDJGKUSR-CPNzpTN8.js} +1 -1
  81. package/out/renderer/assets/{use-default-on-banner-C8DUslhy.js → use-default-on-banner-CuXTqN3l.js} +1 -1
  82. package/out/renderer/assets/{use-download-agent-mutation-DMGaSxDK.js → use-download-agent-mutation-BCbr9wLe.js} +1 -1
  83. package/out/renderer/assets/{xychartDiagram-VJFVF3MP-BGB8PPzY.js → xychartDiagram-VJFVF3MP-TZFrKw4j.js} +1 -1
  84. package/out/renderer/browser-approvals-overlay.html +2 -2
  85. package/out/renderer/console-capture.html +6 -6
  86. package/out/renderer/index.html +8 -8
  87. package/out/renderer/installer.html +5 -5
  88. package/out/renderer/mini.html +7 -7
  89. package/package.json +1 -1
  90. package/out/renderer/assets/appearance-DCqlsN7S.js +0 -65
  91. package/out/renderer/assets/browser-page-AgwdXhLM.js +0 -1
  92. package/out/renderer/assets/channel-DMQl-cpj.js +0 -1
  93. package/out/renderer/assets/classDiagram-GIVACNV2-DJsxDWD8.js +0 -1
  94. package/out/renderer/assets/classDiagram-v2-COTLJTTW-DJsxDWD8.js +0 -1
  95. package/out/renderer/assets/clone-B9GxWhWi.js +0 -1
  96. package/out/renderer/assets/index-BnqyWEPM.css +0 -1
  97. package/out/renderer/assets/index-Buuz619t.js +0 -852
  98. package/out/renderer/assets/infoDiagram-PH2N3AL5-bdAhVGkO.js +0 -2
  99. package/out/renderer/assets/settings-page-DWZ3Mguh.js +0 -319
  100. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-BtazAv7-.js +0 -1
@@ -1,65 +0,0 @@
1
- import{r as x,j as U_,b as Sd,D as B_,l as Vc,m as Ep,n as Zc,o as H_}from"./index-BWQzFq0n.js";import{c as sn,t as g,a as W_}from"./messages-B7aIuFuF.js";import{P as G_,i as Yc,a as Xc,p as Ip}from"./roles-D1pcbxAx.js";const Ed=new Map,Id=new Map,Ad=new Map,Rd=new Map;function Jc(e){return e===void 0?"":JSON.stringify(e)}function Qc(e,t){const n=`${e}\0${Jc(t)}`;let r=Ed.get(n);return r===void 0&&(r=new Intl.DateTimeFormat(e,t),Ed.set(n,r)),r}function z_(e,t){const n=`${e}\0${Jc(t)}`;let r=Id.get(n);return r===void 0&&(r=new Intl.NumberFormat(e,t),Id.set(n,r)),r}function pM(e,t,n){return Qc(n??sn(),t).format(e)}const hM={year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"};function mM(e,t,n){return Qc(n??sn(),t).format(e)}function K_(e,t,n){return Qc(n??sn(),t).format(e)}function V_(e,t,n){return z_(n??sn(),t).format(e)}function gM(e,t,n,r){const o=r??sn(),i=`${o}\0${Jc(n)}`;let a=Ad.get(i);return a===void 0&&(a=new Intl.RelativeTimeFormat(o,n),Ad.set(i,a)),a.format(e,t)}const Z_={B:"byte",KB:"kilobyte",MB:"megabyte",GB:"gigabyte",TB:"terabyte",PB:"petabyte"},xd=new Map,Td=new Map;function Y_(e){return e.split("-")[0]?.toLowerCase()==="en"}function X_(e,t){if(e==="KiB"||e==="MiB"||e==="GiB"||Y_(t))return e;const n=`${t}\0${e}`;let r=xd.get(n);if(r===void 0){r=e;try{r=new Intl.NumberFormat(t,{style:"unit",unit:Z_[e],unitDisplay:"narrow"}).formatToParts(1).find(i=>i.type==="unit")?.value??e}catch{}xd.set(n,r)}return r}function J_(e){let t=Td.get(e);if(t===void 0){t=" ";try{t=new Intl.NumberFormat(e,{style:"unit",unit:"kilobyte",unitDisplay:"short"}).formatToParts(1).find(r=>r.type==="literal")?.value??" "}catch{}Td.set(e,t)}return t}function wo(e,t,n,r){const o=sn();return`${V_(e,{useGrouping:!1,...n},o)}${J_(o)}${X_(t,o)}`}function Ni(e,t){const n=sn();let r=Rd.get(n);return r===void 0&&(r=new Intl.ListFormat(n,{type:"conjunction",style:"narrow"}),Rd.set(n,r)),r.format(e)}const Q_={zh:";",ja:";",ur:"؛ ",ar:"؛ "};function _M(e,t){const n=sn().split("-")[0]?.toLowerCase();return e.join(Q_[n??""]??"; ")}var ni=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},ir=typeof window>"u"||"Deno"in globalThis;function Tt(){}function q_(e,t){return typeof e=="function"?e(t):e}function Fa(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ap(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Pr(e,t){return typeof e=="function"?e(t):e}function Ht(e,t){return typeof e=="function"?e(t):e}function Cd(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==qc(a,t.options))return!1}else if(!xo(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||i&&!i(t))}function Od(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Ro(t.options.mutationKey)!==Ro(i))return!1}else if(!xo(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function qc(e,t){return(t?.queryKeyHashFn||Ro)(e)}function Ro(e){return JSON.stringify(e,(t,n)=>Ba(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function xo(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>xo(e[n],t[n])):!1}function Rp(e,t){if(e===t)return e;const n=Pd(e)&&Pd(t);if(n||Ba(e)&&Ba(t)){const r=n?e:Object.keys(e),o=r.length,i=n?t:Object.keys(t),a=i.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:i[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=Rp(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return o===a&&l===o?e:c}return t}function Ua(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function Pd(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ba(e){if(!Md(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Md(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Md(e){return Object.prototype.toString.call(e)==="[object Object]"}function eb(e){return new Promise(t=>{setTimeout(t,e)})}function Ha(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Rp(e,t):t}function tb(e){return e}function nb(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function rb(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var el=Symbol();function xp(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===el?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var ob=class extends ni{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!ir&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#t!==e&&(this.#t=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},tl=new ob,ib=class extends ni{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!ir&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(this.setOnline.bind(this))}setOnline(e){this.#t!==e&&(this.#t=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#t}},Vi=new ib;function Wa(){let e,t;const n=new Promise((o,i)=>{e=o,t=i});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 sb(e){return Math.min(1e3*2**e,3e4)}function Tp(e){return(e??"online")==="online"?Vi.isOnline():!0}var Cp=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Zs(e){return e instanceof Cp}function Op(e){let t=!1,n=0,r=!1,o;const i=Wa(),a=v=>{r||(h(new Cp(v)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>tl.isFocused()&&(e.networkMode==="always"||Vi.isOnline())&&e.canRun(),u=()=>Tp(e.networkMode)&&e.canRun(),f=v=>{r||(r=!0,e.onSuccess?.(v),o?.(),i.resolve(v))},h=v=>{r||(r=!0,e.onError?.(v),o?.(),i.reject(v))},_=()=>new Promise(v=>{o=b=>{(r||d())&&v(b)},e.onPause?.()}).then(()=>{o=void 0,r||e.onContinue?.()}),y=()=>{if(r)return;let v;const b=n===0?e.initialPromise:void 0;try{v=b??e.fn()}catch(p){v=Promise.reject(p)}Promise.resolve(v).then(f).catch(p=>{if(r)return;const A=e.retry??(ir?0:3),k=e.retryDelay??sb,M=typeof k=="function"?k(n,p):k,P=A===!0||typeof A=="number"&&n<A||typeof A=="function"&&A(n,p);if(t||!P){h(p);return}n++,e.onFail?.(n,p),eb(M).then(()=>d()?void 0:_()).then(()=>{t?h(p):y()})})};return{promise:i,cancel:a,continue:()=>(o?.(),i),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?y():_().then(y),i)}}var ab=e=>setTimeout(e,0);function cb(){let e=[],t=0,n=c=>{c()},r=c=>{c()},o=ab;const i=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)=>{i(()=>{c(...l)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{o=c}}}var ot=cb(),Pp=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Fa(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ir?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},lb=class extends Pp{#t;#e;#n;#r;#o;#a;#s;constructor(e){super(),this.#s=!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=db(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=Ha(this.state.data,e,this.options);return this.#i({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#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=>Ht(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===el||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(e=0){return this.state.isInvalidated||this.state.data===void 0||!Ap(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#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.#s?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.#i({type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#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.#s=!0,n.signal)})},o=()=>{const c=xp(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(l),this.#s=!1,this.options.persister?this.options.persister(c,l,this):c(l)},i={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:o};r(i),this.options.behavior?.onFetch(i,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==i.fetchOptions?.meta)&&this.#i({type:"fetch",meta:i.fetchOptions?.meta});const a=c=>{Zs(c)&&c.silent||this.#i({type:"error",error:c}),Zs(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#o=Op({initialPromise:t?.initialPromise,fn:i.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){a(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){a(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:a,onFail:(c,l)=>{this.#i({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:i.options.retry,retryDelay:i.options.retryDelay,networkMode:i.options.networkMode,canRun:()=>!0}),this.#o.start()}#i(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Mp(n.data,this.options),fetchMeta:e.meta??null};case"success":return{...n,data:e.data,dataUpdateCount:n.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const r=e.error;return Zs(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 Mp(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Tp(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function db(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,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 ub=class extends ni{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,o=t.queryHash??qc(r,t);let i=this.get(o);return i||(i=new lb({client:e,queryKey:r,queryHash:o,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(i)),i}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){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=>Cd(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Cd(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()})})}},fb=class extends Pp{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||pb(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#e.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#e.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#e.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(e){this.#n=Op({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(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 pb(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var hb=class extends ni{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#e=new Map,this.#n=0}#t;#e;#n;build(e,t,n){const r=new fb({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=pi(e);if(typeof t=="string"){const n=this.#e.get(t);n?n.push(e):this.#e.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#t.delete(e)){const t=pi(e);if(typeof t=="string"){const n=this.#e.get(t);if(n)if(n.length>1){const 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=pi(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=pi(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=>Od(t,n))}findAll(e={}){return this.getAll().filter(t=>Od(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 pi(e){return e.options.scope?.id}function jd(e){return{onFetch:(t,n)=>{const r=t.options,o=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},h=xp(t.options,t.fetchOptions),_=async(y,v,b)=>{if(u)return Promise.reject();if(v==null&&y.pages.length)return Promise.resolve(y);const p={client:t.client,queryKey:t.queryKey,pageParam:v,direction:b?"backward":"forward",meta:t.options.meta};f(p);const A=await h(p),{maxPages:k}=t.options,M=b?rb:nb;return{pages:M(y.pages,A,k),pageParams:M(y.pageParams,v,k)}};if(o&&i.length){const y=o==="backward",v=y?jp:Ga,b={pages:i,pageParams:a},p=v(r,b);c=await _(b,p,y)}else{const y=e??i.length;do{const v=l===0?a[0]??r.initialPageParam:Ga(r,c);if(l>0&&v==null)break;c=await _(c,v),l++}while(l<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function Ga(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function jp(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function bM(e,t){return t?Ga(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:jp(e,t)!=null}var mb=class{#t;#e;#n;#r;#o;#a;#s;#i;constructor(e={}){this.#t=e.queryCache||new ub,this.#e=e.mutationCache||new hb,this.#n=e.defaultOptions||{},this.#r=new Map,this.#o=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#s=tl.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#i=Vi.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#s?.(),this.#s=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#t.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Pr(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}),i=this.#t.get(r.queryHash)?.state.data,a=q_(t,i);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 i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Tt)),o.state.fetchStatus==="paused"?Promise.resolve():i}));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(Pr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Tt).catch(Tt)}fetchInfiniteQuery(e){return e.behavior=jd(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Tt).catch(Tt)}ensureInfiniteQueryData(e){return e.behavior=jd(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Vi.isOnline()?this.#e.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#t}getMutationCache(){return this.#e}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(Ro(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{xo(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#o.set(Ro(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(r=>{xo(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=qc(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===el&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#t.clear(),this.#e.clear()}},gb=class extends ni{constructor(e,t){super(),this.options=t,this.#t=e,this.#i=null,this.#s=Wa(),this.options.experimental_prefetchInRender||this.#s.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#r=void 0;#o;#a;#s;#i;#m;#f;#p;#l;#d;#c;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),$d(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return za(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return za(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#y(),this.#w(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,n=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ht(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#k(),this.#e.setOptions(this.options),t._defaulted&&!Ua(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&Dd(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||Ht(this.options.enabled,this.#e)!==Ht(t.enabled,this.#e)||Pr(this.options.staleTime,this.#e)!==Pr(t.staleTime,this.#e))&&this.#g();const o=this.#_();r&&(this.#e!==n||Ht(this.options.enabled,this.#e)!==Ht(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 bb(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=Pr(this.options.staleTime,this.#e);if(ir||this.#r.isStale||!Fa(e))return;const n=Ap(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,!(ir||Ht(this.options.enabled,this.#e)===!1||!Fa(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||tl.isFocused())&&this.#u()},this.#c))}#v(){this.#g(),this.#b(this.#_())}#y(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){this.#d&&(clearInterval(this.#d),this.#d=void 0)}createResult(e,t){const n=this.#e,r=this.options,o=this.#r,i=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 m=this.hasListeners(),w=!m&&$d(e,t),S=m&&Dd(e,n,t,r);(w||S)&&(u={...u,...Mp(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:_,errorUpdatedAt:y,status:v}=u;h=u.data;let b=!1;if(t.placeholderData!==void 0&&h===void 0&&v==="pending"){let m;o?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(m=o.data,b=!0):m=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,m!==void 0&&(v="success",h=Ha(o?.data,m,t),f=!0)}if(t.select&&h!==void 0&&!b)if(o&&h===i?.data&&t.select===this.#m)h=this.#f;else try{this.#m=t.select,h=t.select(h),h=Ha(o?.data,h,t),this.#f=h,this.#i=null}catch(m){this.#i=m}this.#i&&(_=this.#i,h=this.#f,y=Date.now(),v="error");const p=u.fetchStatus==="fetching",A=v==="pending",k=v==="error",M=A&&p,P=h!==void 0,R={status:v,fetchStatus:u.fetchStatus,isPending:A,isSuccess:v==="success",isError:k,isInitialLoading:M,isLoading:M,data:h,dataUpdatedAt:u.dataUpdatedAt,error:_,errorUpdatedAt:y,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:p,isRefetching:p&&!A,isLoadingError:k&&!P,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:k&&P,isStale:nl(e,t),refetch:this.refetch,promise:this.#s};if(this.options.experimental_prefetchInRender){const m=T=>{R.status==="error"?T.reject(R.error):R.data!==void 0&&T.resolve(R.data)},w=()=>{const T=this.#s=R.promise=Wa();m(T)},S=this.#s;switch(S.status){case"pending":e.queryHash===n.queryHash&&m(S);break;case"fulfilled":(R.status==="error"||R.data!==S.value)&&w();break;case"rejected":(R.status!=="error"||R.error!==S.reason)&&w();break}}return R}updateResult(){const e=this.#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),Ua(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 i=new Set(o??this.#h);return this.options.throwOnError&&i.add("error"),Object.keys(this.#r).some(a=>{const c=a;return this.#r[c]!==e[c]&&i.has(c)})};this.#S({listeners:n()})}#k(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#S(e){ot.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function _b(e,t){return Ht(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function $d(e,t){return _b(e,t)||e.state.data!==void 0&&za(e,t,t.refetchOnMount)}function za(e,t,n){if(Ht(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&nl(e,t)}return!1}function Dd(e,t,n,r){return(e!==t||Ht(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&nl(e,n)}function nl(e,t){return Ht(t.enabled,e)!==!1&&e.isStaleByTime(Pr(t.staleTime,e))}function bb(e,t){return!Ua(e.getCurrentResult(),t)}var rl=x.createContext(void 0),vb=e=>{const t=x.useContext(rl);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},yM=({client:e,children:t})=>(x.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),U_.jsx(rl.Provider,{value:e,children:t})),$p=x.createContext(!1),yb=()=>x.useContext($p);$p.Provider;function wb(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var kb=x.createContext(wb()),Sb=()=>x.useContext(kb);function Eb(e,t){return typeof e=="function"?e(...t):!!e}function Nd(){}var Ib=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},Ab=e=>{x.useEffect(()=>{e.clearReset()},[e])},Rb=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(o&&e.data===void 0||Eb(n,[e.error,r])),xb=e=>{const t=e.staleTime;e.suspense&&(e.staleTime=typeof t=="function"?(...n)=>Math.max(t(...n),1e3):Math.max(t??1e3,1e3),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3)))},Tb=(e,t)=>e.isLoading&&e.isFetching&&!t,Cb=(e,t)=>e?.suspense&&t.isPending,Ld=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Ob(e,t,n){const r=vb(n),o=yb(),i=Sb(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=o?"isRestoring":"optimistic",xb(a),Ib(a,i),Ab(i);const c=!r.getQueryCache().get(a.queryHash),[l]=x.useState(()=>new t(r,a)),d=l.getOptimisticResult(a),u=!o&&e.subscribed!==!1;if(x.useSyncExternalStore(x.useCallback(f=>{const h=u?l.subscribe(ot.batchCalls(f)):Nd;return l.updateResult(),h},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),x.useEffect(()=>{l.setOptions(a)},[a,l]),Cb(a,d))throw Ld(a,l,i);if(Rb({result:d,errorResetBoundary:i,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw d.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!ir&&Tb(d,o)&&(c?Ld(a,l,i):r.getQueryCache().get(a.queryHash)?.promise)?.catch(Nd).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function Dp(e,t){return Ob(e,gb,t)}const Pb=()=>{const e=x.useContext(rl)??null,t=x.useMemo(()=>new mb({defaultOptions:{queries:{enabled:!1,retry:!1,gcTime:0}}}),[]);return x.useEffect(()=>{if(!e)return()=>t.clear()},[e,t]),x.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function wM(e){return e!=="detached"&&e!=="wedged"}function Np(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function kM(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=Np(e.pairing?.cause??null);switch(e.state){case"wedged":return{title:"A Local Operator server is running on this machine and this app is not attached to it.",detail:n,retry:r};case"detached":return e.reconnecting?{title:r?"Not connected to a Local Operator server. If one is still running, the app reconnects to it on its own.":"Not connected to a Local Operator server.",detail:n,retry:r}:{title:r?"The Local Operator server stopped. The app keeps looking for one and attaches to it when it appears.":"Not connected to a Local Operator server. The app keeps looking for one.",detail:n,retry:r};default:return null}}var ve;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const a of o)i[a]=a;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(const c of i)a[c]=o[c];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);return i},e.find=(o,i)=>{for(const a of o)if(i(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,i=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(ve||(ve={}));var Ka;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ka||(Ka={}));const B=ve.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),un=e=>{switch(typeof e){case"undefined":return B.undefined;case"string":return B.string;case"number":return isNaN(e)?B.nan:B.number;case"boolean":return B.boolean;case"function":return B.function;case"bigint":return B.bigint;case"symbol":return B.symbol;case"object":return Array.isArray(e)?B.array:e===null?B.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?B.promise:typeof Map<"u"&&e instanceof Map?B.map:typeof Set<"u"&&e instanceof Set?B.set:typeof Date<"u"&&e instanceof Date?B.date:B.object;default:return B.unknown}},j=ve.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Mb=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class kt extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=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(i){return i.message},r={_errors:[]},o=i=>{for(const a of i.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 kt))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ve.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},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()}}kt.create=e=>new kt(e);const Br=(e,t)=>{let n;switch(e.code){case j.invalid_type:e.received===B.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case j.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ve.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:n=`Unrecognized key(s) in object: ${ve.joinValues(e.keys,", ")}`;break;case j.invalid_union:n="Invalid input";break;case j.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ve.joinValues(e.options)}`;break;case j.invalid_enum_value:n=`Invalid enum value. Expected ${ve.joinValues(e.options)}, received '${e.received}'`;break;case j.invalid_arguments:n="Invalid function arguments";break;case j.invalid_return_type:n="Invalid function return type";break;case j.invalid_date:n="Invalid date";break;case j.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:ve.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case j.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case j.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case j.custom:n="Invalid input";break;case j.invalid_intersection_types:n="Intersection results could not be merged";break;case j.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case j.not_finite:n="Number must be finite";break;default:n=t.defaultError,ve.assertNever(e)}return{message:n}};let Lp=Br;function jb(e){Lp=e}function Zi(){return Lp}const Yi=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],a={...o,path:i};if(o.message!==void 0)return{...o,path:i,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:i,message:c}},$b=[];function L(e,t){const n=Zi(),r=Yi({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Br?void 0:Br].filter(o=>!!o)});e.common.issues.push(r)}class ut{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return ee;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 i=await o.key,a=await o.value;r.push({key:i,value:a})}return ut.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:a}=o;if(i.status==="aborted"||a.status==="aborted")return ee;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[i.value]=a.value)}return{status:t.value,value:r}}}const ee=Object.freeze({status:"aborted"}),Rr=e=>({status:"dirty",value:e}),ft=e=>({status:"valid",value:e}),Va=e=>e.status==="aborted",Za=e=>e.status==="dirty",sr=e=>e.status==="valid",To=e=>typeof Promise<"u"&&e instanceof Promise;function Xi(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 Fp(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 ho,mo;class rn{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 Fd=(e,t)=>{if(sr(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new kt(e.common.issues);return this._error=n,this._error}}};function ce(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error: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 ue{get description(){return this._def.description}_getType(t){return un(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:un(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ut,ctx:{common:t.parent.common,data:t.data,parsedType:un(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(To(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:un(t)},i=this._parseSync({data:t,path:o.path,parent:o});return Fd(o,i)}"~validate"(t){var n,r;const o={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:un(t)};if(!this["~standard"].async)try{const i=this._parseSync({data:t,path:[],parent:o});return sr(i)?{value:i.value}:{issues:o.common.issues}}catch(i){!((r=(n=i?.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(i=>sr(i)?{value:i.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:un(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(To(o)?o:Promise.resolve(o));return Fd(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const a=t(o),c=()=>i.addIssue({code:j.custom,...r(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Vt({schema:this,typeName:q.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return tn.create(this,this._def)}nullable(){return $n.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zt.create(this)}promise(){return Wr.create(this,this._def)}or(t){return Mo.create([this,t],this._def)}and(t){return jo.create(this,t,this._def)}transform(t){return new Vt({...ce(this._def),schema:this,typeName:q.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Fo({...ce(this._def),innerType:this,defaultValue:n,typeName:q.ZodDefault})}brand(){return new ol({typeName:q.ZodBranded,type:this,...ce(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Uo({...ce(this._def),innerType:this,catchValue:n,typeName:q.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return ri.create(this,t)}readonly(){return Bo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Db=/^c[^\s-]{8,}$/i,Nb=/^[0-9a-z]+$/,Lb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fb=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ub=/^[a-z0-9_-]{21}$/i,Bb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Hb=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Wb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Gb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ys;const zb=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Kb=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Vb=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Zb=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Yb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Xb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Up="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Jb=new RegExp(`^${Up}$`);function Bp(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function Qb(e){return new RegExp(`^${Bp(e)}$`)}function Hp(e){let t=`${Up}T${Bp(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function qb(e,t){return!!((t==="v4"||!t)&&zb.test(e)||(t==="v6"||!t)&&Vb.test(e))}function ev(e,t){if(!Bb.test(e))return!1;try{const[n]=e.split("."),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 tv(e,t){return!!((t==="v4"||!t)&&Kb.test(e)||(t==="v6"||!t)&&Zb.test(e))}class Gt extends ue{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==B.string){const i=this._getOrReturnCtx(t);return L(i,{code:j.invalid_type,expected:B.string,received:i.parsedType}),ee}const r=new ut;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(o=this._getOrReturnCtx(t,o),L(o,{code:j.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")t.data.length>i.value&&(o=this._getOrReturnCtx(t,o),L(o,{code:j.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const a=t.data.length>i.value,c=t.data.length<i.value;(a||c)&&(o=this._getOrReturnCtx(t,o),a?L(o,{code:j.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&L(o,{code:j.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Wb.test(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{validation:"email",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ys||(Ys=new RegExp(Gb,"u")),Ys.test(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{validation:"emoji",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Fb.test(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{validation:"uuid",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Ub.test(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{validation:"nanoid",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Db.test(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{validation:"cuid",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Nb.test(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{validation:"cuid2",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Lb.test(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{validation:"ulid",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),L(o,{validation:"url",code:j.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{validation:"regex",code:j.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(t,o),L(o,{code:j.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(o=this._getOrReturnCtx(t,o),L(o,{code:j.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(o=this._getOrReturnCtx(t,o),L(o,{code:j.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Hp(i).test(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{code:j.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Jb.test(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{code:j.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Qb(i).test(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{code:j.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Hb.test(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{validation:"duration",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?qb(t.data,i.version)||(o=this._getOrReturnCtx(t,o),L(o,{validation:"ip",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?ev(t.data,i.alg)||(o=this._getOrReturnCtx(t,o),L(o,{validation:"jwt",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?tv(t.data,i.version)||(o=this._getOrReturnCtx(t,o),L(o,{validation:"cidr",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Yb.test(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{validation:"base64",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Xb.test(t.data)||(o=this._getOrReturnCtx(t,o),L(o,{validation:"base64url",code:j.invalid_string,message:i.message}),r.dirty()):ve.assertNever(i);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:j.invalid_string,...K.errToObj(r)})}_addCheck(t){return new Gt({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...K.errToObj(t)})}url(t){return this._addCheck({kind:"url",...K.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...K.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...K.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...K.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...K.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...K.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...K.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...K.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...K.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...K.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...K.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...K.errToObj(t)})}datetime(t){var n,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 Gt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Gt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Gt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}Gt.create=e=>{var t;return new Gt({checks:[],typeName:q.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};function nv(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),a=parseInt(t.toFixed(o).replace(".",""));return i%a/Math.pow(10,o)}class Pn extends ue{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==B.number){const i=this._getOrReturnCtx(t);return L(i,{code:j.invalid_type,expected:B.number,received:i.parsedType}),ee}let r;const o=new ut;for(const i of this._def.checks)i.kind==="int"?ve.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{code:j.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),L(r,{code:j.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),L(r,{code:j.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?nv(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),L(r,{code:j.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),L(r,{code:j.not_finite,message:i.message}),o.dirty()):ve.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,K.toString(n))}gt(t,n){return this.setLimit("min",t,!1,K.toString(n))}lte(t,n){return this.setLimit("max",t,!0,K.toString(n))}lt(t,n){return this.setLimit("max",t,!1,K.toString(n))}setLimit(t,n,r,o){return new Pn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new Pn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:K.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:K.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:K.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:K.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:K.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:K.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:K.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:K.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:K.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&ve.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}}Pn.create=e=>new Pn({checks:[],typeName:q.ZodNumber,coerce:e?.coerce||!1,...ce(e)});class Mn extends ue{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==B.bigint)return this._getInvalidInput(t);let r;const o=new ut;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),L(r,{code:j.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),L(r,{code:j.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),L(r,{code:j.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):ve.assertNever(i);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return L(n,{code:j.invalid_type,expected:B.bigint,received:n.parsedType}),ee}gte(t,n){return this.setLimit("min",t,!0,K.toString(n))}gt(t,n){return this.setLimit("min",t,!1,K.toString(n))}lte(t,n){return this.setLimit("max",t,!0,K.toString(n))}lt(t,n){return this.setLimit("max",t,!1,K.toString(n))}setLimit(t,n,r,o){return new Mn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new Mn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:K.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:K.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:K.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:K.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:K.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}Mn.create=e=>{var t;return new Mn({checks:[],typeName:q.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};class Co extends ue{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==B.boolean){const r=this._getOrReturnCtx(t);return L(r,{code:j.invalid_type,expected:B.boolean,received:r.parsedType}),ee}return ft(t.data)}}Co.create=e=>new Co({typeName:q.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});class ar extends ue{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==B.date){const i=this._getOrReturnCtx(t);return L(i,{code:j.invalid_type,expected:B.date,received:i.parsedType}),ee}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return L(i,{code:j.invalid_date}),ee}const r=new ut;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(o=this._getOrReturnCtx(t,o),L(o,{code:j.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(o=this._getOrReturnCtx(t,o),L(o,{code:j.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ve.assertNever(i);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,...ce(e)});class Ji extends ue{_parse(t){if(this._getType(t)!==B.symbol){const r=this._getOrReturnCtx(t);return L(r,{code:j.invalid_type,expected:B.symbol,received:r.parsedType}),ee}return ft(t.data)}}Ji.create=e=>new Ji({typeName:q.ZodSymbol,...ce(e)});class Oo extends ue{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return L(r,{code:j.invalid_type,expected:B.undefined,received:r.parsedType}),ee}return ft(t.data)}}Oo.create=e=>new Oo({typeName:q.ZodUndefined,...ce(e)});class Po extends ue{_parse(t){if(this._getType(t)!==B.null){const r=this._getOrReturnCtx(t);return L(r,{code:j.invalid_type,expected:B.null,received:r.parsedType}),ee}return ft(t.data)}}Po.create=e=>new Po({typeName:q.ZodNull,...ce(e)});class Hr extends ue{constructor(){super(...arguments),this._any=!0}_parse(t){return ft(t.data)}}Hr.create=e=>new Hr({typeName:q.ZodAny,...ce(e)});class Jn extends ue{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ft(t.data)}}Jn.create=e=>new Jn({typeName:q.ZodUnknown,...ce(e)});class gn extends ue{_parse(t){const n=this._getOrReturnCtx(t);return L(n,{code:j.invalid_type,expected:B.never,received:n.parsedType}),ee}}gn.create=e=>new gn({typeName:q.ZodNever,...ce(e)});class Qi extends ue{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return L(r,{code:j.invalid_type,expected:B.void,received:r.parsedType}),ee}return ft(t.data)}}Qi.create=e=>new Qi({typeName:q.ZodVoid,...ce(e)});class zt extends ue{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==B.array)return L(n,{code:j.invalid_type,expected:B.array,received:n.parsedType}),ee;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,c=n.data.length<o.exactLength.value;(a||c)&&(L(n,{code:a?j.too_big:j.too_small,minimum:c?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(L(n,{code:j.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(L(n,{code:j.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>o.type._parseAsync(new rn(n,a,n.path,c)))).then(a=>ut.mergeArray(r,a));const i=[...n.data].map((a,c)=>o.type._parseSync(new rn(n,a,n.path,c)));return ut.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new zt({...this._def,minLength:{value:t,message:K.toString(n)}})}max(t,n){return new zt({...this._def,maxLength:{value:t,message:K.toString(n)}})}length(t,n){return new zt({...this._def,exactLength:{value:t,message:K.toString(n)}})}nonempty(t){return this.min(1,t)}}zt.create=(e,t)=>new zt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:q.ZodArray,...ce(t)});function wr(e){if(e instanceof He){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=tn.create(wr(r))}return new He({...e._def,shape:()=>t})}else return e instanceof zt?new zt({...e._def,type:wr(e.element)}):e instanceof tn?tn.create(wr(e.unwrap())):e instanceof $n?$n.create(wr(e.unwrap())):e instanceof on?on.create(e.items.map(t=>wr(t))):e}class He extends ue{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=ve.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==B.object){const d=this._getOrReturnCtx(t);return L(d,{code:j.invalid_type,expected:B.object,received:d.parsedType}),ee}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof gn&&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=i[d],f=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new rn(o,f,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof gn){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(d==="strict")c.length>0&&(L(o,{code:j.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const u of c){const f=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new rn(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=>ut.mergeObjectSync(r,d)):ut.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return K.errToObj,new He({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,a,c;const l=(a=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.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 He({...this._def,unknownKeys:"strip"})}passthrough(){return new He({...this._def,unknownKeys:"passthrough"})}extend(t){return new He({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new He({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:q.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new He({...this._def,catchall:t})}pick(t){const n={};return ve.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new He({...this._def,shape:()=>n})}omit(t){const n={};return ve.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new He({...this._def,shape:()=>n})}deepPartial(){return wr(this)}partial(t){const n={};return ve.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new He({...this._def,shape:()=>n})}required(t){const n={};return ve.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof tn;)i=i._def.innerType;n[r]=i}}),new He({...this._def,shape:()=>n})}keyof(){return Wp(ve.objectKeys(this.shape))}}He.create=(e,t)=>new He({shape:()=>e,unknownKeys:"strip",catchall:gn.create(),typeName:q.ZodObject,...ce(t)});He.strictCreate=(e,t)=>new He({shape:()=>e,unknownKeys:"strict",catchall:gn.create(),typeName:q.ZodObject,...ce(t)});He.lazycreate=(e,t)=>new He({shape:e,unknownKeys:"strip",catchall:gn.create(),typeName:q.ZodObject,...ce(t)});class Mo extends ue{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const c of i)if(c.result.status==="valid")return c.result;for(const c of i)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const a=i.map(c=>new kt(c.ctx.common.issues));return L(n,{code:j.invalid_union,unionErrors:a}),ee}if(n.common.async)return Promise.all(r.map(async i=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let i;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"&&!i&&(i={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const c=a.map(l=>new kt(l));return L(n,{code:j.invalid_union,unionErrors:c}),ee}}get options(){return this._def.options}}Mo.create=(e,t)=>new Mo({options:e,typeName:q.ZodUnion,...ce(t)});const cn=e=>e instanceof Do?cn(e.schema):e instanceof Vt?cn(e.innerType()):e instanceof No?[e.value]:e instanceof jn?e.options:e instanceof Lo?ve.objectValues(e.enum):e instanceof Fo?cn(e._def.innerType):e instanceof Oo?[void 0]:e instanceof Po?[null]:e instanceof tn?[void 0,...cn(e.unwrap())]:e instanceof $n?[null,...cn(e.unwrap())]:e instanceof ol||e instanceof Bo?cn(e.unwrap()):e instanceof Uo?cn(e._def.innerType):[];class ws extends ue{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.object)return L(n,{code:j.invalid_type,expected:B.object,received:n.parsedType}),ee;const r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(L(n,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),ee)}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 i of n){const a=cn(i.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of a){if(o.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);o.set(c,i)}}return new ws({typeName:q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...ce(r)})}}function Ya(e,t){const n=un(e),r=un(t);if(e===t)return{valid:!0,data:e};if(n===B.object&&r===B.object){const o=ve.objectKeys(t),i=ve.objectKeys(e).filter(c=>o.indexOf(c)!==-1),a={...e,...t};for(const c of i){const l=Ya(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===B.array&&r===B.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i<e.length;i++){const a=e[i],c=t[i],l=Ya(a,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===B.date&&r===B.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class jo extends ue{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(i,a)=>{if(Va(i)||Va(a))return ee;const c=Ya(i.value,a.value);return c.valid?((Za(i)||Za(a))&&n.dirty(),{status:n.value,value:c.data}):(L(r,{code:j.invalid_intersection_types}),ee)};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(([i,a])=>o(i,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}))}}jo.create=(e,t,n)=>new jo({left:e,right:t,typeName:q.ZodIntersection,...ce(n)});class on extends ue{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.array)return L(r,{code:j.invalid_type,expected:B.array,received:r.parsedType}),ee;if(r.data.length<this._def.items.length)return L(r,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ee;!this._def.rest&&r.data.length>this._def.items.length&&(L(r,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new rn(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>ut.mergeArray(n,a)):ut.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new on({...this._def,rest:t})}}on.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new on({items:e,typeName:q.ZodTuple,rest:null,...ce(t)})};class $o extends ue{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.object)return L(r,{code:j.invalid_type,expected:B.object,received:r.parsedType}),ee;const o=[],i=this._def.keyType,a=this._def.valueType;for(const c in r.data)o.push({key:i._parse(new rn(r,c,r.path,c)),value:a._parse(new rn(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?ut.mergeObjectAsync(n,o):ut.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof ue?new $o({keyType:t,valueType:n,typeName:q.ZodRecord,...ce(r)}):new $o({keyType:Gt.create(),valueType:t,typeName:q.ZodRecord,...ce(n)})}}class qi extends ue{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.map)return L(r,{code:j.invalid_type,expected:B.map,received:r.parsedType}),ee;const o=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:o._parse(new rn(r,c,r.path,[d,"key"])),value:i._parse(new rn(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 ee;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const l of a){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return ee;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}qi.create=(e,t,n)=>new qi({valueType:t,keyType:e,typeName:q.ZodMap,...ce(n)});class cr extends ue{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.set)return L(r,{code:j.invalid_type,expected:B.set,received:r.parsedType}),ee;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(L(r,{code:j.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(L(r,{code:j.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return ee;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>i._parse(new rn(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,...ce(t)});class Mr extends ue{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.function)return L(n,{code:j.invalid_type,expected:B.function,received:n.parsedType}),ee;function r(c,l){return Yi({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Zi(),Br].filter(d=>!!d),issueData:{code:j.invalid_arguments,argumentsError:l}})}function o(c,l){return Yi({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Zi(),Br].filter(d=>!!d),issueData:{code:j.invalid_return_type,returnTypeError:l}})}const i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Wr){const c=this;return ft(async function(...l){const d=new kt([]),u=await c._def.args.parseAsync(l,i).catch(_=>{throw d.addIssue(r(l,_)),d}),f=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(f,i).catch(_=>{throw d.addIssue(o(f,_)),d})})}else{const c=this;return ft(function(...l){const d=c._def.args.safeParse(l,i);if(!d.success)throw new kt([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,i);if(!f.success)throw new kt([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Mr({...this._def,args:on.create(t).rest(Jn.create())})}returns(t){return new Mr({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Mr({args:t||on.create([]).rest(Jn.create()),returns:n||Jn.create(),typeName:q.ZodFunction,...ce(r)})}}class Do extends ue{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Do.create=(e,t)=>new Do({getter:e,typeName:q.ZodLazy,...ce(t)});class No extends ue{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return L(n,{received:n.data,code:j.invalid_literal,expected:this._def.value}),ee}return{status:"valid",value:t.data}}get value(){return this._def.value}}No.create=(e,t)=>new No({value:e,typeName:q.ZodLiteral,...ce(t)});function Wp(e,t){return new jn({values:e,typeName:q.ZodEnum,...ce(t)})}class jn extends ue{constructor(){super(...arguments),ho.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return L(n,{expected:ve.joinValues(r),received:n.parsedType,code:j.invalid_type}),ee}if(Xi(this,ho)||Fp(this,ho,new Set(this._def.values)),!Xi(this,ho).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return L(n,{received:n.data,code:j.invalid_enum_value,options:r}),ee}return ft(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return jn.create(t,{...this._def,...n})}exclude(t,n=this._def){return jn.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}ho=new WeakMap;jn.create=Wp;class Lo extends ue{constructor(){super(...arguments),mo.set(this,void 0)}_parse(t){const n=ve.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==B.string&&r.parsedType!==B.number){const o=ve.objectValues(n);return L(r,{expected:ve.joinValues(o),received:r.parsedType,code:j.invalid_type}),ee}if(Xi(this,mo)||Fp(this,mo,new Set(ve.getValidEnumValues(this._def.values))),!Xi(this,mo).has(t.data)){const o=ve.objectValues(n);return L(r,{received:r.data,code:j.invalid_enum_value,options:o}),ee}return ft(t.data)}get enum(){return this._def.values}}mo=new WeakMap;Lo.create=(e,t)=>new Lo({values:e,typeName:q.ZodNativeEnum,...ce(t)});class Wr extends ue{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.promise&&n.common.async===!1)return L(n,{code:j.invalid_type,expected:B.promise,received:n.parsedType}),ee;const r=n.parsedType===B.promise?n.data:Promise.resolve(n.data);return ft(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Wr.create=(e,t)=>new Wr({type:e,typeName:q.ZodPromise,...ce(t)});class Vt extends ue{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:a=>{L(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const a=o.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return ee;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?ee:l.status==="dirty"||n.value==="dirty"?Rr(l.value):l});{if(n.value==="aborted")return ee;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?ee:c.status==="dirty"||n.value==="dirty"?Rr(c.value):c}}if(o.type==="refinement"){const a=c=>{const l=o.refinement(c,i);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"?ee:(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"?ee:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!sr(a))return a;const c=o.transform(a.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>sr(a)?Promise.resolve(o.transform(a.value,i)).then(c=>({status:n.value,value:c})):a);ve.assertNever(o)}}Vt.create=(e,t,n)=>new Vt({schema:e,typeName:q.ZodEffects,effect:t,...ce(n)});Vt.createWithPreprocess=(e,t,n)=>new Vt({schema:t,effect:{type:"preprocess",transform:e},typeName:q.ZodEffects,...ce(n)});class tn extends ue{_parse(t){return this._getType(t)===B.undefined?ft(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}tn.create=(e,t)=>new tn({innerType:e,typeName:q.ZodOptional,...ce(t)});class $n extends ue{_parse(t){return this._getType(t)===B.null?ft(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}$n.create=(e,t)=>new $n({innerType:e,typeName:q.ZodNullable,...ce(t)});class Fo extends ue{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===B.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Fo.create=(e,t)=>new Fo({innerType:e,typeName:q.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});class Uo extends ue{_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 To(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new kt(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new kt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Uo.create=(e,t)=>new Uo({innerType:e,typeName:q.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});class es extends ue{_parse(t){if(this._getType(t)!==B.nan){const r=this._getOrReturnCtx(t);return L(r,{code:j.invalid_type,expected:B.nan,received:r.parsedType}),ee}return{status:"valid",value:t.data}}}es.create=e=>new es({typeName:q.ZodNaN,...ce(e)});const rv=Symbol("zod_brand");class ol extends ue{_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 ri extends ue{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?ee:i.status==="dirty"?(n.dirty(),Rr(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?ee: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 ri({in:t,out:n,typeName:q.ZodPipeline})}}class Bo extends ue{_parse(t){const n=this._def.innerType._parse(t),r=o=>(sr(o)&&(o.value=Object.freeze(o.value)),o);return To(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}Bo.create=(e,t)=>new Bo({innerType:e,typeName:q.ZodReadonly,...ce(t)});function Ud(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Gp(e,t={},n){return e?Hr.create().superRefine((r,o)=>{var i,a;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=Ud(t,r),h=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;o.addIssue({code:"custom",...f,fatal:h})}});if(!c){const l=Ud(t,r),d=(a=(i=l.fatal)!==null&&i!==void 0?i:n)!==null&&a!==void 0?a:!0;o.addIssue({code:"custom",...l,fatal:d})}}):Hr.create()}const ov={object:He.lazycreate};var q;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(q||(q={}));const iv=(e,t={message:`Input not instance of ${e.name}`})=>Gp(n=>n instanceof e,t),zp=Gt.create,Kp=Pn.create,sv=es.create,av=Mn.create,Vp=Co.create,cv=ar.create,lv=Ji.create,dv=Oo.create,uv=Po.create,fv=Hr.create,pv=Jn.create,hv=gn.create,mv=Qi.create,gv=zt.create,_v=He.create,bv=He.strictCreate,vv=Mo.create,yv=ws.create,wv=jo.create,kv=on.create,Sv=$o.create,Ev=qi.create,Iv=cr.create,Av=Mr.create,Rv=Do.create,xv=No.create,Tv=jn.create,Cv=Lo.create,Ov=Wr.create,Bd=Vt.create,Pv=tn.create,Mv=$n.create,jv=Vt.createWithPreprocess,$v=ri.create,Dv=()=>zp().optional(),Nv=()=>Kp().optional(),Lv=()=>Vp().optional(),Fv={string:e=>Gt.create({...e,coerce:!0}),number:e=>Pn.create({...e,coerce:!0}),boolean:e=>Co.create({...e,coerce:!0}),bigint:e=>Mn.create({...e,coerce:!0}),date:e=>ar.create({...e,coerce:!0})},Uv=ee;var s=Object.freeze({__proto__:null,defaultErrorMap:Br,setErrorMap:jb,getErrorMap:Zi,makeIssue:Yi,EMPTY_PATH:$b,addIssueToContext:L,ParseStatus:ut,INVALID:ee,DIRTY:Rr,OK:ft,isAborted:Va,isDirty:Za,isValid:sr,isAsync:To,get util(){return ve},get objectUtil(){return Ka},ZodParsedType:B,getParsedType:un,ZodType:ue,datetimeRegex:Hp,ZodString:Gt,ZodNumber:Pn,ZodBigInt:Mn,ZodBoolean:Co,ZodDate:ar,ZodSymbol:Ji,ZodUndefined:Oo,ZodNull:Po,ZodAny:Hr,ZodUnknown:Jn,ZodNever:gn,ZodVoid:Qi,ZodArray:zt,ZodObject:He,ZodUnion:Mo,ZodDiscriminatedUnion:ws,ZodIntersection:jo,ZodTuple:on,ZodRecord:$o,ZodMap:qi,ZodSet:cr,ZodFunction:Mr,ZodLazy:Do,ZodLiteral:No,ZodEnum:jn,ZodNativeEnum:Lo,ZodPromise:Wr,ZodEffects:Vt,ZodTransformer:Vt,ZodOptional:tn,ZodNullable:$n,ZodDefault:Fo,ZodCatch:Uo,ZodNaN:es,BRAND:rv,ZodBranded:ol,ZodPipeline:ri,ZodReadonly:Bo,custom:Gp,Schema:ue,ZodSchema:ue,late:ov,get ZodFirstPartyTypeKind(){return q},coerce:Fv,any:fv,array:gv,bigint:av,boolean:Vp,date:cv,discriminatedUnion:yv,effect:Bd,enum:Tv,function:Av,instanceof:iv,intersection:wv,lazy:Rv,literal:xv,map:Ev,nan:sv,nativeEnum:Cv,never:hv,null:uv,nullable:Mv,number:Kp,object:_v,oboolean:Lv,onumber:Nv,optional:Pv,ostring:Dv,pipeline:$v,preprocess:jv,promise:Ov,record:Sv,set:Iv,strictObject:bv,string:zp,symbol:lv,transformer:Bd,tuple:kv,undefined:dv,union:vv,unknown:pv,void:mv,NEVER:Uv,ZodIssueCode:j,quotelessJson:Mb,ZodError:kt});const Hd=s.enum(["app_start","sign_in","window_focus","surface_open"]),Zp=s.object({id:s.string().min(1),state:s.enum(["active","paused","disabled"])}).passthrough(),Bv=s.object({tenant_id:s.string().min(1),tenant_name:s.string().optional(),eligible:s.boolean(),endpoint:Zp.nullable()}).passthrough(),Hv=s.object({code:s.string(),message:s.string(),details:s.record(s.unknown()).optional(),retry_after_seconds:s.number().optional()}).passthrough(),Wv=s.object({code:s.string().min(1),count:s.number().int().nonnegative(),session:s.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),Gv=s.object({in_force:s.boolean(),notice_pending:s.boolean().catch(!1)}).passthrough().optional().catch(void 0),SM=s.object({capability:s.number(),consent_account_guard:s.boolean().optional(),state:s.enum(["ready","signed_out","unavailable","update_required"]),account_id:s.string().nullable(),tenant_id:s.string().nullable(),surface_state:s.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:s.object({settings:s.boolean(),inbox:s.boolean(),account_door:s.boolean(),onboarding:s.boolean()}),update_required:s.boolean(),local:s.object({enabled:s.boolean(),onboarding:s.string(),session:s.string()}),status:s.object({tenants:s.array(Bv)}).passthrough().nullable(),consent:s.object({version:s.string().min(1).max(128),text:s.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:s.enum(["served","cached","embedded"])}).nullable(),error:Hv.nullable(),state_note:s.string().nullable().optional(),read_only:s.boolean().optional(),trial_ended:s.object({tenant_id:s.string().min(1),trial_ended_at:s.string().min(1)}).passthrough().nullable().optional().catch(null),delivery_hold:Wv,default_on:Gv}).passthrough(),zv=s.object({version:s.string().min(1),consented_at:s.string().min(1),consented_via:s.string().min(1),current:s.boolean()}).passthrough(),EM=s.object({endpoint:Zp.extend({tenant_id:s.string().min(1),label:s.string().optional(),consent:zv.nullable().optional(),created_at:s.string().optional(),updated_at:s.string().optional()}).nullable(),settings:s.object({tenant_id:s.string().min(1),eligible:s.boolean(),consent_version:s.string().optional(),consent_required:s.boolean()}).passthrough(),default_on:s.boolean().optional().catch(void 0),share_typing:s.boolean().optional().catch(void 0)}).passthrough(),Kv=s.object({kind:s.enum(["endpoint","account"]).optional(),endpoint_id:s.string().min(1).optional(),account_id:s.string().min(1).optional()}).passthrough().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id").refine(e=>e.kind===void 0||(e.kind==="endpoint"?e.endpoint_id!==void 0:e.account_id!==void 0),"An allowlist target's kind must agree with the id it carries"),Wd=s.object({direction:s.enum(["send","receive"]),effect:s.enum(["allow","deny"]),target:Kv,id:s.string().optional()}).passthrough(),Gd=s.object({mode:s.enum(["class_default","listed_only"]),allow:s.number(),deny:s.number()}).passthrough(),IM=s.object({allowlist:s.object({tenant_id:s.string().min(1),entries:s.array(Wd)}).passthrough(),view:s.object({tenant_id:s.string().nullable(),entries:s.array(Wd),directions:s.object({send:Gd,receive:Gd}),class_default:s.literal("cos_cos"),cues:s.object({allow_entry_switches_direction_to_listed_only:s.boolean(),listed_only_affects:s.string(),removing_allow_does_not_stop_open_thread:s.boolean(),deny_stops_pair_both_directions:s.boolean()}).passthrough()}).passthrough()}).passthrough(),AM=s.object({onboarding:s.literal("seen")}).passthrough();function Vv(e){return e?.default_on?.in_force===!0}function RM(e,t){const n=Zv(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function xM(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function TM(e,t){if(!e||!t||Vv(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 Zv(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const Yv=8,Xa=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],Ho=200,Xv=6*1024,Jv=512;function ts(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const o=[];for(const i of n){if(o.length===Jv)break;const c=new URLSearchParams({order_ids:i}).toString().length+1;if(r+c>Xv)break;e.append("order_ids",i),o.push(i),r+=c}return o}function Qv(e,t,n){return ts(new URLSearchParams(n),t,e)}const CM=3,qv=4096,OM=128,PM=/^[0-9a-f]{32}$/,ey=/^\.+$/,ty=new RegExp("\\p{Cf}","u"),ny=/[/\\:]/,I=s.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),zd=s.string().min(1).max(256).regex(/^[a-zA-Z0-9_-]+(?::[a-zA-Z0-9_-]+)?$/),ry=s.string().min(1).max(128),hi=s.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),mi=s.string().min(1).max(32768),Yp=/^[a-f0-9]{12}$/,F=s.string().regex(Yp),oy=["network-credentials"],iy=e=>Yp.test(e)||oy.includes(e),Ja=s.string().refine(iy,"not a notifications session id"),Xs=s.string().regex(/^[a-f0-9]{12}$/),Js=s.string().min(1).max(128),sy=s.string().min(1).max(4096),eo=s.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),Qs=s.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),gi=s.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),Kd=s.string().regex(/^[a-f0-9]{32}$/),ay=/^(\/|[A-Za-z]:[\\/])/,qs=s.string().min(1).max(4096).regex(ay),Vd=/^[a-f0-9]{32}$/,de=s.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),Zd=s.string().min(1).max(512).nullish(),gr=s.string().regex(/^[A-Za-z0-9_-]{1,128}$/),_r=s.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),cy=/^pp_[0-9a-f]{16}$/,ea=s.string().regex(cy),ly=["credential_finite_share","credential_inheritance"],xr=/^sha256:[0-9a-f]{64}$/,Yd={operation:s.enum(ly),requestDigest:s.string().regex(xr),disclosureDigest:s.string().regex(xr)},to=s.string().regex(/^la_[0-9a-f]{16}$/),no=s.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),Xd=s.object({data_b64:s.string().min(1).max(1e6),mime_type:s.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:s.string().max(4096).optional()}).strict(),dy=s.object({digest:s.string().regex(/^[0-9a-f]{32}$/),name:s.string().max(1024).optional(),mime_type:s.string().max(255).optional(),bytes:s.number().int().min(0).optional(),path:s.string().max(4096).optional()}).strict(),Jd=2e5,Qd=8,uy=256,fy=100,qd=16,py=256,hy=100,my=200,gy=1e6,_y=s.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),rt=s.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),_i=s.object({kind:s.enum(["agent","team"]),name:rt}).strict(),Xp=s.enum(["claude","codex","omp"]),by=s.record(s.string(),s.array(s.string().min(1).max(512)).max(5e3)),eu={sources:s.array(Xp).max(3).optional(),sessionIds:by.optional(),all:s.boolean().optional(),includeSubagents:s.boolean().optional(),includeClearedSegments:s.boolean().optional(),includeMemory:s.boolean().optional(),includeInstructions:s.boolean().optional(),maxSessions:s.number().int().min(1).max(5e3).optional()},ta=s.object({provider:s.string().min(1).max(128),model_id:s.string().min(1).max(512),reasoning_effort:s.string().min(1).max(64).nullable(),fast_mode:s.boolean().nullable().optional()}).strict(),tu=s.object({kind:s.enum(["role","specialist"]).optional(),description:s.string().max(8e3).optional(),instructions:s.string().max(8e3).optional(),tools:s.array(s.string().min(1).max(128)).max(256).optional(),effort:s.string().max(64).optional(),delegate:s.boolean().optional(),action_class:s.enum(["reactive","proactive"]).optional()}).strict(),nu=s.object({name:s.string().min(1).max(64).optional(),description:s.string().max(8e3).optional(),manager:rt.optional(),members:s.array(s.object({role:rt,count:s.number().int().min(1).max(16),kind:s.enum(["agent","team"]),tier:s.enum(["lo","med","hi"]).nullable().optional(),effort:_y.nullable().optional()}).strict()).max(128).optional(),instructions:s.string().max(8e3).optional(),project:s.string().max(8e3).optional()}).strict(),vy=s.record(s.array(s.string().max(1024)).max(100)),na=s.array(I).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),yy=s.array(s.object({kind:s.enum(["human","agent"]),account_id:I,endpoint_id:I.optional()}).strict()).max(50).refine(e=>new Set(e.map(t=>`${t.kind}:${t.account_id}:${t.endpoint_id??""}`)).size===e.length,"Duplicate mention"),ru=s.enum(["minutes","hours","days"]);function wy(e){return!ey.test(e)}const MM=e=>Li.safeParse(e).success,Li=s.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(wy),ou=s.enum(["str","int","float","bool","list","dict"]),iu=s.string().max(16384),ky=2e3,su=s.string().min(1).max(ky),au=s.string().min(1).max(64),Sy=s.string().min(1).max(64),Ey=s.string().min(1).max(64),cu=s.object({is_active:s.boolean().nullish(),one_time:s.boolean().nullish(),start_time_utc:s.string().max(64).nullish(),end_time_utc:s.string().max(64).nullish()}).strict(),Iy=s.object({conversation_length:s.number().int().optional(),detail_length:s.number().int().optional(),max_learnings_history:s.number().int().optional(),hosting:s.string().max(256).optional(),model_name:s.string().max(1024).optional(),auto_save_conversation:s.boolean().optional()}).strict(),Qa=128,lu=2e3,du=8e3,uu=64,fu=64,ks=e=>[...e].length,qa=e=>e>=9&&e<=13||e>=28&&e<=32||e===133||e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288,Ay=e=>e===9||e===10||e===11||e===12||e===13||e===133,Ry=e=>e<=31||e>=127&&e<=159,xy=e=>ty.test(String.fromCodePoint(e)),Ty=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,bi=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},Jp=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&qa(t[n].codePointAt(0)??0);)n++;for(;r>n&&qa(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},Cy=e=>{let t="",n=!1;for(const r of e){if(qa(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function Oy(e){const t=Jp(e);if(!t)return"must not be empty";if(ks(t)>Qa)return`must be at most ${Qa} characters`;if(ny.test(t))return'must not contain "/", "\\" or ":"';if(bi(t,Ty))return"must not contain Unicode bidirectional override characters";if(bi(t,Ay))return"must not contain whitespace";if(bi(t,Ry))return"must not contain control characters";if(bi(t,xy))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 jM(e){return Cy(Jp(e).normalize("NFKC").toLowerCase())}function Py(e){return e.trim()?ks(e)>lu?`must be at most ${lu} characters`:null:"must not be empty"}function My(e){return e.trim()?ks(e)>du?`must be at most ${du} characters`:null:"must not be empty"}function jy(e){if(e.length>fu)return`must hold at most ${fu} items`;for(const t of e)if(!t.trim()||ks(t)>uu)return`must hold items of 1 to ${uu} characters`;return null}const $y=e=>Oy(e)===null,Dy=s.string().refine($y,{message:"That is not a name the hub can publish."}),Ny=s.string().refine(e=>My(e)===null,{message:"That instruction body cannot be published."}),Ly=s.string().refine(e=>Py(e)===null,{message:"That description cannot be published."}),Fy=s.array(s.string()).refine(e=>jy(e)===null,{message:"That tool list cannot be published."}),ra={requestId:de.optional(),subscribe:s.boolean().optional(),autoPush:s.boolean().optional(),confirmPublicEgress:s.boolean().optional()},pu=s.object({name:Dy,description:Ly,instructions:Ny,kind:s.enum(["role","specialist"]),when_to_use:s.string(),tools:Fy,effort:s.string(),delegate:s.boolean(),version:s.string(),categories:s.array(s.string()),tags:s.array(s.string())}).partial().strict(),Uy=s.enum(["team","agent"]),By=s.string().min(1).max(64),Hy=s.string().min(1).max(256),Qp=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,oa=s.string().regex(Qp,{message:"Letters, digits, dot, underscore and dash; no spaces."}),Wy=["planning","active","qa","validation","done","paused","archived"],hu=s.enum(Wy),vi=s.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),mu=s.array(s.string().min(1).max(24)).max(8),Sn=s.string().min(1).max(64),Gy=1e3,gu=240,_u=80,zy=256,Ky=100,Vy=200,Zy=/^[a-z0-9][a-z0-9_-]{0,23}$/;function $M(e){return e?Qp.test(e)?null:"Names start with a letter or digit and may use letters, digits, dot, underscore or dash.":"Give the project a name."}function DM(e){return Zy.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const yi=s.enum(["agent","team","skill"]),ia=s.string().min(1).max(128).regex(/\S/),bu=s.enum(Xa),Yy=s.object({visible:s.array(bu).max(Xa.length),more:s.array(bu).max(Xa.length)}).strict(),fn=s.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),vu=s.object({selectionToken:s.string().min(1).max(512),reconcileIds:s.array(fn).max(500).optional(),excludedIds:s.array(fn).max(500).optional()}).strict(),Xy=s.object({operationToken:s.string().min(1).max(512),reconcileIds:s.array(fn).max(500).optional()}).strict(),yu=s.union([s.object({throughSeq:s.number().int().min(0).optional(),receipt:s.literal(!0).optional(),reconcileIds:s.array(fn).max(500).optional(),items:s.array(s.object({id:fn,revision:s.number().int().min(1)}).strict()).min(1).max(500)}).strict(),s.object({sessionId:Ja,throughSeq:s.number().int().min(0),observed:s.array(s.object({id:fn,revision:s.number().int().min(1)}).strict()).max(500)}).strict(),s.object({all:s.literal(!0),throughSeq:s.number().int().min(0),observed:s.array(s.object({id:fn,revision:s.number().int().min(1)}).strict()).max(500)}).strict()]),Jy={pointer:"pointerdown",key:"keydown",wheel:"wheel"},Qy=s.discriminatedUnion("op",[s.object({op:s.literal("capabilities")}).strict(),s.object({op:s.literal("runtimes.list")}).strict(),s.object({op:s.literal("profiles.list")}).strict(),s.object({op:s.literal("profiles.get"),name:rt}).strict(),s.object({op:s.literal("imports.sources")}).strict(),s.object({op:s.literal("imports.sessions"),source:Xp,includeSubagents:s.boolean().optional()}).strict(),s.object({op:s.literal("imports.preview"),...eu}).strict(),s.object({op:s.literal("imports.start"),...eu}).strict(),s.object({op:s.literal("imports.status"),jobId:s.string().min(1).max(128)}).strict(),s.object({op:s.literal("imports.cancel"),jobId:s.string().min(1).max(128)}).strict(),s.object({op:s.literal("profiles.update"),name:rt,requestId:de,fields:tu,expectedDefinitionRevision:Zd.optional()}).strict(),s.object({op:s.literal("profiles.install"),name:rt,requestId:de}).strict(),s.object({op:s.literal("profiles.create"),name:rt,requestId:de,fields:tu.extend({description:s.string().max(8e3),instructions:s.string().min(1).max(8e3)})}).strict(),s.object({op:s.literal("hub.updates")}).strict(),s.object({op:s.literal("hub.skillPull"),requestId:de,hubId:I,hubSource:s.string().min(1).max(2048),visibility:s.enum(["public","org"]),tenantId:I.nullable(),localAlias:rt,subscribe:s.boolean().optional(),autoPush:s.boolean().optional(),confirmPublicEgress:s.boolean().optional(),dryRun:s.boolean().optional(),adoptionStrategy:s.enum(["merge","keep-local","take-hub"]).optional(),allowLlm:s.boolean().optional(),confirm:s.boolean().optional(),adoptionReceipt:s.string().min(16).max(128).optional()}).strict(),s.object({op:s.literal("hub.skillSubscribe"),requestId:de,hubId:I,hubSource:s.string().min(1).max(2048),visibility:s.enum(["public","org"]),tenantId:I.nullable(),localAlias:rt}).strict(),s.object({op:s.literal("hub.skillUnpull"),requestId:de,linkId:s.string().min(1).max(256)}).strict(),s.object({op:s.literal("hub.skillPublish"),requestId:de,dryRun:s.boolean(),sourceSkill:rt,localAlias:rt,visibility:s.enum(["public","org"]),tenantId:I.nullable(),subscribe:s.boolean(),autoPush:s.boolean(),confirmPublicEgress:s.boolean(),previewReceipt:s.string().min(1).max(4096).optional(),confirmPublish:s.literal(!0).optional()}).strict(),s.object({op:s.literal("hub.links"),kind:s.enum(["agent","team","skill"]).optional()}).strict(),s.object({op:s.literal("hub.policy"),requestId:de,linkId:s.string().min(1).max(256),expectedPolicyRevision:s.string().min(1).max(256),subscribe:s.boolean().optional(),autoPush:s.boolean().optional(),confirmPublicEgress:s.boolean().optional()}).strict(),s.object({op:s.literal("hub.check"),requestId:de,kind:yi.optional(),name:rt.optional(),localId:ia.optional()}).strict(),s.object({op:s.literal("hub.apply"),requestId:de,kind:yi.optional(),name:rt.optional(),localId:ia.optional(),prefer:s.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:s.boolean().optional(),dryRun:s.boolean().optional(),resolveSource:s.literal(!0).optional(),hubSource:s.string().min(1).max(2048).optional(),visibility:s.enum(["public","org"]).optional(),tenantId:s.string().min(1).max(128).nullable().optional()}).strict(),s.object({op:s.literal("hub.applyAll"),requestId:de,kind:yi.optional()}).strict(),s.object({op:s.literal("hub.retry"),requestId:de,kind:yi.optional(),name:rt.optional(),localId:ia.optional()}).strict(),s.object({op:s.literal("hub.push"),requestId:de,linkId:s.string().min(1).max(256),direction:s.literal("push"),dryRun:s.boolean(),previewReceipt:s.string().min(1).max(4096).optional(),confirmPublish:s.literal(!0).optional()}).strict(),s.object({op:s.literal("teams.list")}).strict(),s.object({op:s.literal("teams.get"),name:rt}).strict(),s.object({op:s.literal("teams.effective"),name:rt}).strict(),s.object({op:s.literal("teams.update"),name:rt,requestId:de,fields:nu,expectedDefinitionRevision:Zd.optional()}).strict(),s.object({op:s.literal("teams.create"),requestId:de,fields:nu.extend({name:s.string().min(1).max(64)})}).strict(),s.object({op:s.literal("sessions.list"),limit:s.number().int().min(1).max(500).optional(),include_archived:s.boolean().optional(),include_temporary:s.boolean().optional(),include_peers:s.boolean().optional(),scope_kind:Uy.optional(),scope_name:By.optional(),cursor:Hy.optional(),with_counts:s.boolean().optional(),sort:s.literal("activity").optional()}).strict(),s.object({op:s.literal("delegated_cleanup_notice.ack")}).strict(),s.object({op:s.literal("sessions.search"),q:s.string().min(1).max(uy),limit:s.number().int().min(1).max(500).optional(),include_archived:s.boolean().optional()}).strict(),s.object({op:s.literal("sessions.archive"),sessionId:F,archived:s.boolean()}).strict(),s.object({op:s.literal("sessions.temporary"),sessionId:F,temporary:s.boolean()}).strict(),s.object({op:s.literal("sessions.delete"),sessionId:F,confirmed:s.literal(!0)}).strict(),s.object({op:s.literal("sessions.create"),requestId:de,cwd:s.string().min(1).max(4096).optional(),target:_i.optional(),purpose:s.literal("agents-config").optional(),model:ta.optional(),draftId:F.optional(),peer:gr.optional(),temporary:s.boolean().optional()}).strict(),s.object({op:s.literal("sessions.preview"),requestId:de,cwd:s.string().min(1).max(4096),target:_i.optional(),model:ta.optional()}).strict(),s.object({op:s.literal("sessions.draft"),requestId:de,cwd:s.string().min(1).max(4096),target:_i.optional(),model:ta.optional()}).strict(),s.object({op:s.literal("sessions.get"),sessionId:F,journalOrder:s.boolean().optional(),orderIds:s.array(s.string().min(1).max(128)).max(512).optional(),peerJournalSource:s.boolean().optional()}).strict(),s.object({op:s.literal("sessions.files"),sessionId:F,scope:s.enum(["family","self"]).optional(),kind:s.string().max(256).optional(),q:s.string().max(256).optional(),sort:s.enum(["recent","name","kind","modified","created","size"]).optional(),order:s.enum(["asc","desc"]).optional(),limit:s.number().int().min(1).max(200).optional(),cursor:s.string().max(8192).optional()}).strict(),s.object({op:s.literal("sessions.files.materialise"),sessionId:F,fileId:s.string().regex(/^[a-f0-9]{16}$/)}).strict(),s.object({op:s.literal("sessions.files.download"),sessionId:F,fileId:s.string().regex(/^[a-f0-9]{16}$/)}).strict(),s.object({op:s.literal("sessions.userAttachments"),sessionId:F}).strict(),s.object({op:s.literal("sessions.userAttachments.materialise"),sessionId:F,digest:s.string().regex(/^[a-f0-9]{32}$/)}).strict(),s.object({op:s.literal("sessions.history"),sessionId:F,beforeId:I.optional(),limit:s.number().int().min(1).max(500).optional(),openFrame:s.boolean().optional(),journalOrder:s.boolean().optional(),orderIds:s.array(s.string().min(1).max(128)).max(512).optional(),peerJournalSource:s.boolean().optional(),sourceRead:s.enum(["metadata","payload"]).optional(),expectedJournalGeneration:s.string().min(1).max(128).optional()}).strict(),s.object({op:s.literal("sessions.checkpoints"),sessionId:F}).strict(),s.object({op:s.literal("sessions.checkpoints.warm"),sessionId:F,ids:s.array(I).max(qd).optional(),limit:s.number().int().min(1).max(qd).optional()}).strict(),s.object({op:s.literal("sessions.find"),sessionId:F,q:s.string().min(1).max(py),limit:s.number().int().min(1).max(my).optional()}).strict(),s.object({op:s.literal("subagents.transcript"),sessionId:F,childId:F,beforeId:I.optional(),entryId:s.string().min(1).max(128).regex(/^[a-zA-Z0-9_:-]+$/).optional(),limit:s.number().int().min(1).max(500).optional()}).strict(),s.object({op:s.literal("sessions.diff"),sessionId:F,callId:zd,start:s.number().int().min(0).max(1e6),offset:s.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),limit:s.number().int().min(1).max(Ho)}).strict(),s.object({op:s.literal("subagents.diff"),sessionId:F,childId:F,callId:zd,start:s.number().int().min(0).max(1e6),offset:s.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),limit:s.number().int().min(1).max(Ho)}).strict(),s.object({op:s.literal("sessions.message"),sessionId:F,requestId:de,text:s.string().max(Jd),images:s.array(Xd).max(Qd).optional(),files:s.array(dy).max(Yv).optional(),mode:s.enum(["prompt","steer"]).optional(),inputMode:s.enum(["typed","dictated","mixed"]).optional(),inputPath:s.string().max(1024).optional()}).strict(),s.object({op:s.literal("sessions.command"),sessionId:F,requestId:de,command:s.string().regex(/^\/?[A-Za-z]+$/).max(64),args:s.string().max(Jd).optional(),images:s.array(Xd).max(Qd).optional()}).strict(),s.object({op:s.literal("sessions.move"),sessionId:F,requestId:de,cwd:s.string().min(1).max(4096)}).strict(),s.object({op:s.literal("settingsIntents.list"),sessionId:F.optional()}).strict(),s.object({op:s.literal("settingsIntents.submit"),sessionId:F,requestId:de,kind:s.enum(["model","effort","fast","cwd"]),value:s.union([s.string().min(1).max(4096),s.boolean()]),effort:s.string().min(1).max(64).optional()}).strict(),s.object({op:s.literal("settingsIntents.dismiss"),sessionId:F,kind:s.enum(["model","effort","fast","cwd"]),generation:s.number().int().nonnegative()}).strict(),s.object({op:s.literal("sessions.profileActionStatus"),sessionId:F,actionId:s.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),receiptId:s.string().min(1).max(160),profileKind:s.enum(["agent","team"]),profileName:s.string().min(1).max(128),toolCallId:s.string().min(1).max(160)}).strict(),s.object({op:s.literal("sessions.answer"),sessionId:F,epoch:I.optional(),requestId:I.optional(),value:s.string().max(32768).optional(),approved:s.boolean().optional(),questionIndex:s.number().int().min(0).optional(),askId:I.optional(),answers:s.record(s.string(),s.array(s.string().max(32768))).optional(),decline:s.boolean().optional(),revise:s.boolean().optional(),dismiss:s.boolean().optional(),reason:s.enum(["answered_in_chat","moot"]).optional()}).strict(),s.object({op:s.literal("sessions.seen"),sessionId:F,completionToken:s.string().uuid()}).strict(),s.object({op:s.literal("attention.seen"),items:s.array(s.object({sessionId:F,completionToken:s.string().uuid()}).strict()).min(1).max(500)}).strict(),s.object({op:s.literal("sessions.notified"),sessionId:F,completionToken:s.string().uuid()}).strict(),s.object({op:s.literal("tags.list")}).strict(),s.object({op:s.literal("tags.replace"),tags:s.array(s.object({id:s.string().optional(),name:s.string()}).strict())}).strict(),s.object({op:s.literal("sessions.tags"),expected_revision:s.string().optional(),sessionId:F,tags:s.array(s.string()),primary:s.string().nullable()}).strict(),s.object({op:s.literal("sessions.pin"),sessionId:F,pinned:s.boolean()}).strict(),s.object({op:s.literal("sessions.watch"),sessionId:F,subscriptionId:s.string().regex(Vd),visible:s.boolean(),canNotify:s.boolean()}).strict(),s.object({op:s.literal("sessions.warm"),sessionId:F}).strict(),s.object({op:s.literal("sessions.interrupt"),sessionId:F,requestId:de}).strict(),s.object({op:s.literal("supplements.cancel"),sessionId:F,job:Xs,anchor:Js}).strict(),s.object({op:s.literal("supplements.restart"),sessionId:F,job:Xs,anchor:Js}).strict(),s.object({op:s.literal("supplements.steer"),sessionId:F,job:Xs,anchor:Js,text:s.string().min(1).max(500)}).strict(),s.object({op:s.literal("sessions.variables.list"),sessionId:F}).strict(),s.object({op:s.literal("sessions.variables.create"),sessionId:F,key:Li,value:iu,type:ou}).strict(),s.object({op:s.literal("sessions.variables.update"),sessionId:F,key:Li,value:iu,type:ou}).strict(),s.object({op:s.literal("sessions.variables.delete"),sessionId:F,key:Li}).strict(),s.object({op:s.literal("sessions.presence"),subscriptionId:s.string().regex(/^[a-f0-9]{1,64}$/),canNotify:s.boolean(),canNotifyKinds:s.array(s.enum(["complete","error"])).max(4),sessionId:s.string().regex(/^([a-f0-9]{12})?$/),window:s.object({exists:s.boolean(),focused:s.boolean(),visible:s.boolean(),minimized:s.boolean()}).strict()}).strict(),s.object({op:s.literal("legacy.models"),provider:s.string().max(128).optional(),sort:s.enum(["id","name","provider","recommended"]).optional(),direction:s.enum(["ascending","descending"]).optional()}).strict(),s.object({op:s.literal("legacy.models.providers")}).strict(),s.object({op:s.literal("auth.probe"),provider:I}).strict(),s.object({op:s.literal("legacy.agent.upload"),agentId:I}).strict(),s.object({op:s.literal("agent.publish"),agentId:I,document:pu.optional(),...ra,visibility:s.literal("org").optional(),tenantId:I.optional()}).strict(),s.object({op:s.literal("agent.republish"),agentId:I,hubAgentId:I,expectedRemoteRevision:s.string().min(1).max(512).optional(),document:pu.optional(),...ra,visibility:s.literal("org").optional(),tenantId:I.optional()}).strict(),s.object({op:s.literal("team.publish"),teamId:I,...ra,visibility:s.literal("org").optional(),tenantId:I.optional()}).strict(),s.object({op:s.literal("team.pull"),teamId:I,tenantId:I.optional()}).strict(),s.object({op:s.literal("agent.nameAvailability"),name:s.string().min(1).max(Qa)}).strict(),s.object({op:s.literal("legacy.agents.list"),page:s.number().int().min(1).optional(),perPage:s.number().int().min(1).max(500).optional(),name:s.string().max(256).optional(),sort:s.string().max(64).optional(),direction:s.enum(["asc","desc"]).optional()}).strict(),s.object({op:s.literal("legacy.agent.get"),agentId:I}).strict(),s.object({op:s.literal("legacy.agent.history"),agentId:I,page:s.number().int().min(1).optional(),perPage:s.number().int().min(1).max(500).optional()}).strict(),s.object({op:s.literal("legacy.jobs.list"),agentId:I.optional(),status:s.string().max(64).optional()}).strict(),s.object({op:s.literal("legacy.job.get"),jobId:I}).strict(),s.object({op:s.literal("legacy.schedules.list"),page:s.number().int().min(1).optional(),perPage:s.number().int().min(1).max(100).optional()}).strict(),s.object({op:s.literal("legacy.agent.schedules.list"),agentId:I,page:s.number().int().min(1).optional(),perPage:s.number().int().min(1).max(100).optional()}).strict(),s.object({op:s.literal("legacy.agent.schedule.create"),agentId:I,schedule:cu.extend({prompt:s.string().max(64e3),interval:s.number().int().min(1),unit:ru})}).strict(),s.object({op:s.literal("legacy.schedule.get"),scheduleId:I}).strict(),s.object({op:s.literal("legacy.schedule.edit"),scheduleId:I,schedule:cu.extend({prompt:s.string().max(64e3).nullish(),interval:s.number().int().min(1).nullish(),unit:ru.nullish()})}).strict(),s.object({op:s.literal("legacy.schedule.remove"),scheduleId:I}).strict(),s.object({op:s.literal("legacy.agent.create"),agent:s.record(s.unknown())}).strict(),s.object({op:s.literal("legacy.agent.update"),agentId:I,update:s.record(s.unknown())}).strict(),s.object({op:s.literal("legacy.agent.delete"),agentId:I}).strict(),s.object({op:s.literal("legacy.agent.conversation.clear"),agentId:I}).strict(),s.object({op:s.literal("legacy.agent.systemPrompt.get"),agentId:I}).strict(),s.object({op:s.literal("legacy.agent.systemPrompt.update"),agentId:I,systemPrompt:s.string().max(gy)}).strict(),s.object({op:s.literal("legacy.agent.download"),agentId:I}).strict(),s.object({op:s.literal("legacy.job.cancel"),jobId:I}).strict(),s.object({op:s.literal("commands.list")}).strict(),s.object({op:s.literal("commands.entities"),sessionId:F,command:I,name:s.string().max(128).optional()}).strict(),s.object({op:s.literal("models.catalogue"),live:s.boolean().optional(),scope:s.enum(["usable","all"]).optional()}).strict(),s.object({op:s.literal("usage.get"),provider:I.optional(),live:s.boolean().optional(),refresh:s.boolean().optional()}).strict(),s.object({op:s.literal("usage.reset"),provider:I,credentialRef:ry.optional(),identity:s.string().min(1).max(256).optional(),redeemRequestId:s.string().uuid()}).strict(),s.object({op:s.literal("quota.notice"),provider:I.optional(),model:s.string().min(1).max(200).optional(),refresh:s.boolean().optional()}).strict(),s.object({op:s.literal("analytics.get"),sessionId:F.optional(),sinceMs:s.number().int().nonnegative().optional(),untilMs:s.number().int().nonnegative().optional(),days:s.number().int().min(1).max(366).optional()}).strict(),s.object({op:s.literal("analytics.models"),sessionId:F.optional(),sinceMs:s.number().int().nonnegative().optional(),untilMs:s.number().int().nonnegative().optional(),days:s.number().int().min(1).max(366).optional()}).strict(),s.object({op:s.literal("info.get")}).strict(),s.object({op:s.literal("sessions.report"),sessionId:F,recentLimit:s.number().int().min(0).max(50).optional()}).strict(),s.object({op:s.literal("skills.list"),sessionId:F.optional(),cwd:sy.optional(),name:eo.optional()}).strict(),s.object({op:s.literal("skills.create"),requestId:de,name:eo,copyFrom:eo}).strict(),s.object({op:s.literal("skills.update"),requestId:de,name:eo,expectedFingerprint:s.string().regex(/^[a-f0-9]{64}$/),files:s.array(s.object({path:s.string().min(1).max(240),content:s.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),s.object({op:s.literal("skills.remove"),requestId:de,name:eo,discardLocalChanges:s.boolean()}).strict(),s.object({op:s.literal("sessions.failovers"),sessionId:F}).strict(),s.object({op:s.literal("sessions.credential"),sessionId:F,action:s.enum(["list","store","forget"]),key:hi.optional(),value:mi.optional(),confirmed:s.boolean().optional()}).strict(),s.object({op:s.literal("sessions.fork"),sessionId:F,requestId:de,message:s.string().max(2e5).optional(),boundary:s.enum(["next_safe","at_entry"]).optional(),entryId:s.string().max(128).optional(),autoTag:s.boolean().optional()}).strict(),s.object({op:s.literal("sessions.stop"),requestId:de,targets:s.array(F).min(1).max(100),confirmed:s.literal(!0)}).strict(),s.object({op:s.literal("sessions.aside"),sessionId:F,requestId:de,text:s.string().min(1).max(32768),asideId:de.optional(),subscriptionId:s.string().regex(Vd).optional()}).strict(),s.object({op:s.literal("sessions.adopt"),sessionId:F,requestId:de,asideId:de,confirmed:s.literal(!0)}).strict(),s.object({op:s.literal("sessions.aside.get"),sessionId:F,asideId:de}).strict(),s.object({op:s.literal("sessions.aside.close"),sessionId:F,asideId:de}).strict(),s.object({op:s.literal("wakes.list"),limit:s.number().int().min(1).max(500).optional(),includeDormant:s.boolean().optional()}).strict(),s.object({op:s.literal("wakes.create"),requestId:de,sessionId:F.optional(),cwd:s.string().min(1).max(4096).optional(),target:_i.optional(),message:su,in:s.string().min(1).max(64).optional(),at:s.string().min(1).max(64).optional(),every:s.string().min(1).max(64).optional(),until:s.string().min(1).max(64).optional(),limit:s.number().int().min(1).optional(),title:s.string().min(1).max(200).optional()}).strict(),s.object({op:s.literal("wakes.edit"),sessionId:F,wakeId:au,message:su.optional(),in:s.string().min(1).max(64).optional(),at:s.string().min(1).max(64).optional(),every:s.string().min(1).max(64).optional(),until:s.string().min(1).max(64).optional(),limit:s.number().int().min(1).optional()}).strict(),s.object({op:s.literal("wakes.remove"),sessionId:F,wakeId:au}).strict(),s.object({op:s.literal("monitors.list"),limit:s.number().int().min(1).max(500).optional(),includeDormant:s.boolean().optional()}).strict(),s.object({op:s.literal("monitors.cancel"),sessionId:F,monitorId:Sy}).strict(),s.object({op:s.literal("jobs.cancel"),sessionId:F,jobId:Ey}).strict(),s.object({op:s.literal("mcp.list"),sessionId:F}).strict(),s.object({op:s.literal("mcp.credentials.store"),sessionId:F,name:s.string().min(1).max(256),values:s.record(s.string().min(1).max(128),s.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:s.array(s.string().min(1).max(128)).max(32)}).strict(),s.object({op:s.literal("mcp.control"),sessionId:F,control:s.object({action:s.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:Qs.optional(),scope:s.enum(["global","project"]).optional(),command:s.string().min(1).max(4096).optional(),args:s.array(s.string().max(8192)).max(128).optional(),env:s.record(gi).optional(),url:s.string().max(4096).optional(),headers:s.record(gi).optional(),oauth:s.boolean().optional(),confirmed:s.boolean().optional(),operation_id:Kd.optional()}).strict()}).strict(),s.object({op:s.literal("mcp.catalog"),cwd:qs.optional(),sessionId:F.optional()}).strict(),s.object({op:s.literal("mcp.catalog.control"),cwd:qs.optional(),control:s.object({action:s.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:Qs.optional(),scope:s.enum(["global","project"]).optional(),command:s.string().min(1).max(4096).optional(),args:s.array(s.string().max(8192)).max(128).optional(),env:s.record(gi).optional(),url:s.string().max(4096).optional(),headers:s.record(gi).optional(),confirmed:s.boolean().optional(),operation_id:Kd.optional()}).strict()}).strict(),s.object({op:s.literal("mcp.catalog.credentials"),header:s.string().min(1).max(128).optional(),cwd:qs.optional(),name:Qs,values:s.record(s.string().min(1).max(128),s.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:s.array(s.string().min(1).max(128)).max(32)}).strict(),s.object({op:s.literal("radient.request"),control:s.object({operation:s.enum(["account","prices","credits","usage","provision","application.create","agents.list","agents.get","agents.create","agents.update","agents.delete","agents.like","agents.unlike","agents.liked","agents.like_count","agents.favourite","agents.unfavourite","agents.favourited","agents.favourite_count","agents.download_count","agents.statuses","comments.list","comments.create","comments.update","comments.delete","account.agents","memberships.list","org_agents.list","org_team.get","org_teams.list","org_skills.list","org_skill.get","signup.resend","team_trial.eligibility","team_trial.start","team_trial.status"]),request_id:de.optional(),tenant_id:I.optional(),account_id:I.optional(),agent_id:I.optional(),comment_id:I.optional(),team_id:I.optional(),skill_id:I.optional(),query:s.record(s.union([s.string().max(1024),s.number().int()])).optional(),payload:s.record(s.unknown()).optional(),confirmed:s.boolean().optional()}).strict()}).strict(),s.object({op:s.literal("providers.list")}).strict(),s.object({op:s.literal("accounts.list")}).strict(),s.object({op:s.literal("accounts.remove"),accountId:s.number().int().positive(),confirmed:s.literal(!0)}).strict(),s.object({op:s.literal("tunnel.setup.read"),credentialId:s.number().int().positive().optional()}).strict(),s.object({op:s.literal("tunnel.setup.plan"),credentialId:s.number().int().positive().optional()}).strict(),s.object({op:s.literal("tunnel.setup.run"),credentialId:s.number().int().positive(),acceptMonthlyPrice:s.string().min(1).max(64).optional()}).strict(),s.object({op:s.literal("mobile.doctor")}).strict(),s.object({op:s.literal("auth.start"),provider:I}).strict(),s.object({op:s.literal("auth.status"),id:I}).strict(),s.object({op:s.literal("auth.input"),id:I,promptId:I,value:mi}).strict(),s.object({op:s.literal("auth.cancel"),id:I}).strict(),s.object({op:s.literal("auth.key"),provider:I,value:mi}).strict(),s.object({op:s.literal("auth.logout"),provider:I}).strict(),s.object({op:s.literal("agent_messages.status"),boundary:Hd}).strict(),s.object({op:s.literal("agent_messages.enable"),expected_account_id:I,tenant_id:I,state:s.literal("active"),consent_version:s.string().min(1).max(128),consented_via:s.literal("dialog")}).strict(),s.object({op:s.literal("agent_messages.settings"),tenant_id:I.optional()}).strict(),s.object({op:s.literal("agent_messages.settings.put"),expected_account_id:I,tenant_id:I.optional(),consent_version:s.string().min(1).max(128).optional(),consented_via:s.enum(["dialog","settings"]).optional(),label:s.string().min(1).max(128).optional(),state:s.enum(["active","paused","disabled"])}).strict(),s.object({op:s.literal("agent_messages.onboarding.dismiss")}).strict(),s.object({op:s.literal("agent_messages.allowlist.get"),tenant_id:I.optional()}).strict(),s.object({op:s.literal("agent_messages.allowlist.put"),expected_account_id:I,tenant_id:I.optional(),entries:s.array(s.object({direction:s.enum(["send","receive"]),effect:s.enum(["allow","deny"]),target:s.object({endpoint_id:I.optional(),account_id:I.optional()}).strict().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id")}).strict()).max(200)}).strict(),s.object({op:s.literal("team_bridge.conversations.list"),scope:s.literal("account").optional(),tenant_id:I.optional(),limit:s.number().int().min(1).max(100).optional(),cursor:s.string().min(1).max(512).optional(),before:s.string().min(1).max(64).optional(),status:s.enum(["open","archived"]).optional()}).strict(),s.object({op:s.literal("team_bridge.conversations.get"),conversation_id:I,tenant_id:I.optional()}).strict(),s.object({op:s.literal("team_bridge.conversations.create"),expected_account_id:I.optional(),tenant_id:I.optional(),kind:s.enum(["dm","group","channel"]),name:s.string().min(1).max(128).optional(),topic:s.string().min(1).max(512).optional(),visibility:s.enum(["private","tenant"]).optional(),agent_capable:s.boolean().optional(),members:s.array(s.object({account_id:I,kind:s.enum(["human","agent"]),endpoint_id:I.optional(),display_label:s.string().min(1).max(64)}).strict()).max(500)}).strict(),s.object({op:s.literal("team_bridge.conversations.lifecycle"),expected_account_id:I.optional(),tenant_id:I.optional(),conversation_id:I,action:s.enum(["archive","unarchive","join","leave"])}).strict(),s.object({op:s.literal("team_bridge.conversations.join"),expected_account_id:I.optional(),conversation_id:I,tenant_id:I.optional()}).strict(),s.object({op:s.literal("team_bridge.conversations.leave"),expected_account_id:I.optional(),conversation_id:I,tenant_id:I.optional()}).strict(),s.object({op:s.literal("team_bridge.conversations.notify"),expected_account_id:I.optional(),conversation_id:I,tenant_id:I.optional(),notify:s.enum(["all","mention","mute"])}).strict(),s.object({op:s.literal("team_bridge.conversations.agent_notify"),expected_account_id:I.optional(),conversation_id:I,tenant_id:I.optional(),notify:s.enum(["all","mention","mute"])}).strict(),s.object({op:s.literal("team_bridge.conversations.members.add"),expected_account_id:I.optional(),conversation_id:I,tenant_id:I.optional(),members:s.array(s.object({account_id:I,kind:s.enum(["human","agent"]),endpoint_id:I.optional(),display_label:s.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),s.object({op:s.literal("team_bridge.conversations.members.remove"),expected_account_id:I.optional(),tenant_id:I.optional(),conversation_id:I,account_id:I}).strict(),s.object({op:s.literal("team_bridge.conversations.delete"),expected_account_id:I.optional(),tenant_id:I.optional(),conversation_id:I}).strict(),s.object({op:s.literal("team_bridge.conversations.consent"),expected_account_id:I.optional(),conversation_id:I,account_id:I,decision:s.enum(["accept","decline","withdraw"]),consent_version:s.string().min(1).max(128).optional(),endpoint_id:I.optional(),tenant_id:I.optional()}).strict(),s.object({op:s.literal("team_bridge.owner_audit.conversations"),expected_account_id:I,tenant_id:I,limit:s.number().int().min(1).max(100).optional(),cursor:s.string().min(1).optional()}).strict(),s.object({op:s.literal("team_bridge.owner_audit.messages"),expected_account_id:I,tenant_id:I,conversation_id:I,limit:s.number().int().min(1).max(100).optional(),before_seq:s.number().int().nonnegative().optional()}).strict(),s.object({op:s.literal("team_bridge.owner_audit.replies"),expected_account_id:I,tenant_id:I,conversation_id:I,message_id:I,limit:s.number().int().min(1).max(100).optional(),after_seq:s.number().int().nonnegative().optional(),before_seq:s.number().int().positive().optional(),order:s.enum(["asc","desc"]).optional()}).strict(),s.object({op:s.literal("team_bridge.messages.list"),conversation_id:I,tenant_id:I.optional(),limit:s.number().int().min(1).max(100).optional(),before_seq:s.number().int().nonnegative().optional(),endpoint_id:I.optional()}).strict(),s.object({op:s.literal("team_bridge.typing.get"),conversation_id:I,tenant_id:I}).strict(),s.object({op:s.enum(["team_bridge.typing.set","team_bridge.typing.clear"]),conversation_id:I,tenant_id:I,expected_account_id:I,thread_root_id:I.optional()}).strict(),s.object({op:s.literal("agent_messages.settings.share_typing"),expected_account_id:I,share_typing:s.boolean()}).strict(),s.object({op:s.literal("team_bridge.reactions.toggle"),conversation_id:I,message_id:I,expected_account_id:I,tenant_id:I,emoji:s.string().min(1),active:s.boolean()}).strict(),s.object({op:s.literal("team_bridge.messages.send"),expected_account_id:I.optional(),conversation_id:I,tenant_id:I.optional(),client_ref:I,body:s.string(),agent_label:s.string().min(1).max(64).optional(),thread_root_id:I.optional(),attachment_ids:na.optional(),files:s.array(I).min(1).max(10).refine(e=>new Set(e).size===e.length,"Duplicate file").optional(),mentions:yy.optional()}).strict(),s.object({op:s.literal("team_bridge.messages.replies"),conversation_id:I,message_id:I,expected_account_id:I,tenant_id:I,limit:s.number().int().min(1).max(100).optional(),after_seq:s.number().int().nonnegative().optional(),before_seq:s.number().int().positive().optional(),order:s.enum(["asc","desc"]).optional()}).strict(),s.object({op:s.literal("team_bridge.scheduled.list"),tenant_id:I}).strict(),s.object({op:s.literal("team_bridge.scheduled.create"),tenant_id:I,conversation_id:I,client_ref:I,body:s.string(),send_at:s.string().datetime({offset:!0}),attachment_ids:na.optional(),thread_root_id:I.optional()}).strict(),s.object({op:s.literal("team_bridge.scheduled.update"),tenant_id:I,scheduled_id:I,body:s.string().optional(),send_at:s.string().datetime({offset:!0}).optional(),attachment_ids:na.optional(),expected_version:s.number().int().nonnegative().optional()}).strict(),s.object({op:s.literal("team_bridge.attachments.delete"),tenant_id:I,conversation_id:I,attachment_id:I,expected_account_id:I}).strict(),s.object({op:s.literal("team_bridge.scheduled.cancel"),tenant_id:I,scheduled_id:I}).strict(),s.object({op:s.literal("team_bridge.read"),expected_account_id:I.optional(),conversation_id:I,tenant_id:I.optional(),seq:s.number().int().nonnegative().optional(),muted:s.boolean().optional()}).strict(),s.object({op:s.literal("team_bridge.thread_read"),expected_account_id:I,conversation_id:I,message_id:I,tenant_id:I,seq:s.number().int().nonnegative()}).strict(),s.object({op:s.literal("team_bridge.unread"),scope:s.literal("account").optional(),tenant_id:I.optional()}).strict(),s.object({op:s.literal("team_bridge.directory"),tenant_id:I}).strict(),s.object({op:s.literal("team_bridge.status"),boundary:Hd.optional()}).strict(),s.object({op:s.literal("team_bridge.link_preview.resolve"),url:s.string().min(1).max(qv),index:s.number().int().nonnegative(),expectedAccountId:I}).strict(),s.object({op:s.literal("settings.list")}).strict(),s.object({op:s.literal("settings.edit"),key:hi,value:s.unknown().refine(e=>e!==void 0,"A setting value is required."),base:vy.optional()}).strict(),s.object({op:s.literal("settings.reset"),key:hi}).strict(),s.object({op:s.literal("tts.paths")}).strict(),s.object({op:s.literal("notification_sounds.list")}).strict(),s.object({op:s.literal("notification_sounds.rename"),id:s.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/),name:s.string().min(1).max(200)}).strict(),s.object({op:s.literal("notification_sounds.remove"),id:s.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)}).strict(),s.object({op:s.literal("config.get")}).strict(),s.object({op:s.literal("config.update"),value:Iy}).strict(),s.object({op:s.literal("instructions.get")}).strict(),s.object({op:s.literal("instructions.update"),content:s.string().max(64e3)}).strict(),s.object({op:s.literal("credentials.list")}).strict(),s.object({op:s.literal("credentials.update"),key:hi,value:mi}).strict(),s.object({op:s.literal("peers.list")}).strict(),s.object({op:s.literal("networks.list")}).strict(),s.object({op:s.literal("networks.invite"),networkId:gr,role:s.enum(["read","drive","admin"]),deviceId:gr.optional()}).strict(),s.object({op:s.literal("networks.member.remove"),networkId:gr,deviceId:gr,confirm:s.string().min(1).max(256)}).strict(),s.object({op:s.literal("sessions.transfer"),sessionId:F,to:s.union([s.literal("local"),gr]),keep:s.boolean().optional(),waitS:s.number().min(0).max(300).optional(),requestId:de.optional()}).strict(),s.object({op:s.literal("profileProposals.list"),state:s.enum(["pending","all"]).optional()}).strict(),s.object({op:s.literal("profileProposals.get"),proposalId:ea}).strict(),s.object({op:s.literal("profileProposals.accept"),proposalId:ea,requestId:de,after:s.record(s.string().regex(/^[a-z][a-z0-9_]{0,63}$/),s.unknown()).optional()}).strict(),s.object({op:s.literal("profileProposals.reject"),proposalId:ea,requestId:de,note:s.string().max(2e3).optional()}).strict(),s.object({op:s.literal("approvals.list")}).strict(),s.object({op:s.literal("approvals.approve"),approvalId:_r}).strict(),s.object({op:s.literal("approvals.deny"),approvalId:_r}).strict(),...["approvals.approveOperation","approvals.applyOperation"].map(e=>s.object({op:s.literal(e),approvalId:_r,operation:s.enum(["profile_save","pair_phone"]),requestDigest:s.string().regex(xr),disclosureDigest:s.string().regex(xr)}).strict()),s.object({op:s.literal("approvals.pairAck"),approvalId:_r,requestDigest:s.string().regex(xr),disclosureDigest:s.string().regex(xr),code:s.string().min(1).max(32).optional()}).strict(),s.object({op:s.literal("devices.list")}).strict(),s.object({op:s.literal("devices.remove"),deviceId:s.string().regex(/^[A-Za-z0-9]{1,64}$/)}).strict(),s.object({op:s.literal("operator.setup.read")}).strict(),s.object({op:s.literal("operator.setup.run")}).strict(),s.object({op:s.literal("mobile.password")}).strict(),s.object({op:s.literal("approvals.approveCredential"),approvalId:_r,...Yd}).strict(),s.object({op:s.literal("approvals.applyCredential"),approvalId:_r,...Yd}).strict(),s.object({op:s.literal("asks.list")}).strict(),s.object({op:s.literal("projects.list")}).strict(),s.object({op:s.literal("projects.get"),key:Sn}).strict(),s.object({op:s.literal("projects.create"),name:oa,description:s.string().max(gu).optional(),status:hu.optional(),tags:mu.optional()}).strict(),s.object({op:s.literal("projects.update"),key:Sn,fields:s.object({name:oa.optional(),title:s.string().max(80).optional(),owner:s.string().max(80).optional(),team:s.string().max(80).optional(),description:s.string().max(gu).optional(),status:hu.optional(),progress:s.string().max(Gy).optional(),tags:mu.optional(),start_date:vi.optional(),target_date:vi.optional(),completed_at:vi.optional(),estimate:s.number().positive().max(1e3).optional(),estimate_unit:s.enum(["points","days"]).optional()}).strict(),force_done:s.boolean().optional()}).strict(),s.object({op:s.literal("projects.delete"),key:Sn,confirmed_name:oa}).strict(),s.object({op:s.literal("projects.link"),key:Sn,sessionId:F}).strict(),s.object({op:s.literal("projects.unlink"),key:Sn,sessionId:F}).strict(),s.object({op:s.literal("projects.milestone"),key:Sn,name:s.string().min(1).max(_u),targetDate:vi.optional(),completed:s.boolean().optional()}).strict(),s.object({op:s.literal("projects.milestone.remove"),key:Sn,name:s.string().min(1).max(_u)}).strict(),s.object({op:s.literal("projects.request_update"),key:Sn}).strict(),s.object({op:s.literal("projects.for_session"),sessionId:F}).strict(),s.object({op:s.literal("projects.search"),q:s.string().min(1).max(zy),limit:s.number().int().min(1).max(Vy).optional()}).strict(),s.object({op:s.literal("aida.status")}).strict(),s.object({op:s.literal("aida.control"),action:s.enum(["open","pause","resume","greet","status"])}).strict(),s.object({op:s.literal("code_requests.list"),sessionId:F}).strict(),s.object({op:s.literal("code_requests.refresh"),sessionId:F,keys:s.array(s.string().min(1).max(512)).max(256).optional(),force:s.boolean().optional()}).strict(),s.object({op:s.literal("static.sign"),route:s.enum(["images","videos","audio","html"]),path:s.string().min(1),ttlS:s.number().int().min(1).max(3600).optional()}).strict(),s.object({op:s.literal("library.list"),scope:s.enum(["final","all"]).optional(),q:s.string().max(512).optional(),category:s.string().min(1).max(64).optional(),kind:s.string().min(1).max(64).optional(),origin_group:s.enum(["generated","created","mentioned"]).optional(),origin:s.string().min(1).max(64).optional(),tag:s.string().min(1).max(128).optional(),tag_mode:s.enum(["all","any"]).optional(),highlighted:s.boolean().optional(),organized:s.boolean().optional(),favorite:s.boolean().optional(),session:s.string().min(1).max(12).optional(),session_id:s.string().min(1).max(512).optional(),sort:s.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:s.enum(["asc","desc"]).optional(),limit:s.number().int().min(1).max(200).optional(),cursor:s.string().max(512).optional()}).strict(),s.object({op:s.literal("library.get"),id:to}).strict(),s.object({op:s.literal("library.update"),id:to,fields:s.object({name:s.string().max(200).optional(),description:s.string().max(2e3).optional(),favorite:s.boolean().optional(),locked:s.boolean().optional(),archived:s.boolean().optional()}).strict()}).strict(),s.object({op:s.literal("library.tags")}).strict(),s.object({op:s.literal("library.tags.create"),name:s.string().trim().min(1).max(24),category:s.string().min(1).max(64).optional()}).strict(),s.object({op:s.literal("library.tags.update"),id:no,name:s.string().trim().min(1).max(24).optional(),category:s.string().min(1).max(64).optional()}).strict(),s.object({op:s.literal("library.tags.delete"),id:no}).strict(),s.object({op:s.literal("library.tags.merge"),id:no,into:no}).strict(),s.object({op:s.literal("library.tags.assign"),id:to,tags:s.array(no).max(64),primary:s.string().max(128).optional()}).strict(),s.object({op:s.literal("library.chat.link"),id:to,sessionId:F}).strict(),s.object({op:s.literal("library.chat.clear"),id:to}).strict(),s.object({op:s.literal("library.librarian"),action:s.enum(["status","open","pause","resume","run"]).optional()}).strict(),s.object({op:s.literal("sidebar_layout.get")}).strict(),s.object({op:s.literal("sidebar_layout.set"),layout:Yy}).strict(),s.object({op:s.literal("notifications.list"),preview:s.literal(!0).optional(),includeAskReads:s.boolean().optional(),countSessionIds:s.array(F).max(50).optional(),includeSessionCounts:s.literal(!0).optional(),kind:s.enum(["all","asks","updates"]).optional(),bulkPriority:s.enum(["any","high","normal_up"]).optional(),state:s.enum(["unread","all","dismissed"]).optional(),source:s.enum(["notify","ask"]).optional(),priority:s.enum(["high","normal","low"]).optional(),sessionId:Ja.optional(),throughSeq:s.number().int().min(0).optional(),cursor:s.string().min(1).max(64).optional(),limit:s.number().int().min(1).max(100).optional()}).strict(),s.object({op:s.literal("notifications.get"),id:fn}).strict(),s.object({op:s.literal("notifications.count")}).strict(),s.object({op:s.literal("notifications.read"),verb:s.enum(["read","unread","undo"]),target:s.union([yu,vu,Xy])}).strict(),s.object({op:s.literal("notifications.dismiss"),verb:s.enum(["dismiss","undismiss"]),target:s.union([yu,vu])}).strict(),s.object({op:s.literal("notifications.seen"),items:s.array(s.object({id:fn,revision:s.number().int().min(1),anchorId:s.string().min(1).max(256),visibleSinceMs:s.number().int().min(0)}).strict()).min(1).max(50),evidence:s.object({sessionId:Ja,inputKind:s.enum(["pointer","key","wheel"]),inputAtMs:s.number().int().min(0),visibleSinceMs:s.number().int().min(0)}).strict()}).strict()]);Qy.superRefine((e,t)=>{if(e.op==="usage.reset"&&!e.credentialRef&&!e.identity&&t.addIssue({code:s.ZodIssueCode.custom,message:"A usage reset must name an account: send `credentialRef` or `identity`.",path:["credentialRef"]}),e.op==="team_bridge.conversations.consent"&&e.decision==="withdraw"!=(e.consent_version===void 0)&&t.addIssue({code:s.ZodIssueCode.custom,message:"accept and decline require consent_version; withdraw carries none",path:["consent_version"]}),(e.op==="notifications.read"||e.op==="notifications.dismiss")&&"items"in e.target&&!!e.target.receipt!=(e.target.throughSeq!==void 0)&&t.addIssue({code:s.ZodIssueCode.custom,message:"Receipt writes require a sequence boundary",path:["target"]}),e.op==="notifications.read"&&e.verb==="undo"!="operationToken"in e.target&&t.addIssue({code:s.ZodIssueCode.custom,message:"Undo requires an operation token, and only undo accepts one",path:["target"]}),e.op==="team_bridge.messages.send"&&e.files){const n=e.attachment_ids??[];(n.length+e.files.length>10||e.files.some(r=>n.includes(r)))&&t.addIssue({code:s.ZodIssueCode.custom,message:"Invalid combined attachment set",path:["files"]})}if((e.op==="team_bridge.messages.send"||e.op==="team_bridge.scheduled.create"||e.op==="team_bridge.scheduled.update"&&e.body!==void 0)&&e.body?.trim()===""&&(e.attachment_ids?.length??0)===0&&!(e.op==="team_bridge.messages.send"&&e.files?.length)){t.addIssue({code:s.ZodIssueCode.custom,message:"A message needs text or an image",path:["body"]});return}if(e.op.startsWith("team_bridge.")&&"expected_account_id"in e&&e.expected_account_id&&(!("tenant_id"in e)||!e.tenant_id)){t.addIssue({code:s.ZodIssueCode.custom,path:["tenant_id"],message:"Guarded conversation writes require an explicit tenant"});return}if(e.op==="team_bridge.messages.send"&&e.thread_root_id!==void 0&&!e.expected_account_id){t.addIssue({code:s.ZodIssueCode.custom,path:["expected_account_id"],message:"Thread replies require the captured account"});return}if(e.op==="hub.skillPull"||e.op==="hub.skillSubscribe"||e.op==="hub.skillPublish"){if(e.visibility==="public"&&e.tenantId!==null||e.visibility==="org"&&!e.tenantId){t.addIssue({code:s.ZodIssueCode.custom,message:"A skill destination requires explicit paired scope",path:["tenantId"]});return}if(e.op==="hub.skillPublish"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:s.ZodIssueCode.custom,message:"An initial skill publication requires its reviewed draft receipt",path:["previewReceipt"]});return}}if(e.op==="hub.check"||e.op==="hub.apply"||e.op==="hub.retry"){const n=e.name!==void 0,r=e.localId!==void 0,o=e.op!=="hub.check";if(n&&r||o&&!n&&!r||r&&e.kind===void 0){t.addIssue({code:s.ZodIssueCode.custom,message:"A hub action addresses one item by name or local id, never both",path:["localId"]});return}}if(e.op==="hub.apply"&&e.resolveSource===!0){const n=e.visibility==="public"&&e.tenantId===null||e.visibility==="org"&&typeof e.tenantId=="string"&&e.tenantId.length>0;if(!e.hubSource||!n||e.acknowledgeUnknownBaseline!==!0||e.localId!==void 0||e.prefer!==void 0){t.addIssue({code:s.ZodIssueCode.custom,message:"Confirming a source requires its exact stated destination and the unknown-baseline acknowledgement, addressed by name, with no preference",path:["hubSource"]});return}}if(e.op==="hub.push"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:s.ZodIssueCode.custom,message:"A confirmed publication requires its reviewed preview receipt",path:["previewReceipt"]});return}if(e.op==="hub.policy"&&e.subscribe===void 0&&e.autoPush===void 0){t.addIssue({code:s.ZodIssueCode.custom,message:"A hub policy change must name subscribe or autoPush",path:["subscribe"]});return}if((e.op==="team_bridge.conversations.list"||e.op==="team_bridge.unread")&&e.scope==="account"&&e.tenant_id!==void 0){t.addIssue({code:s.ZodIssueCode.custom,message:"An account-scoped read cannot name a tenant",path:["scope"]});return}if(e.op==="team_bridge.conversations.list"&&e.scope==="account"&&e.before!==void 0){t.addIssue({code:s.ZodIssueCode.custom,message:"An account-scoped page uses cursor, not before",path:["before"]});return}if(e.op==="sessions.answer"){if(e.askId!==void 0){if(e.askId||t.addIssue({code:s.ZodIssueCode.custom,message:"ask_id must be a non-empty string",path:["askId"]}),e.dismiss===!0){(e.answers!==void 0||e.decline===!0||e.revise===!0)&&t.addIssue({code:s.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:s.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:s.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:s.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:s.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:s.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:s.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:s.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:s.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:s.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:s.ZodIssueCode.custom,message:"reason applies to a queued ask",path:["reason"]});return}if(e.op==="sessions.create"&&e.purpose===void 0){e.cwd===void 0&&t.addIssue({code:s.ZodIssueCode.custom,message:"A conversation needs a working directory: only a configuration run (`purpose`) may omit `cwd`.",path:["cwd"]});return}if(e.op==="sessions.create"&&e.purpose!==void 0){for(const n of["cwd","target","model","draftId"])e[n]!==void 0&&t.addIssue({code:s.ZodIssueCode.custom,message:`A configuration run resolves its own \`${n}\`: send \`purpose\` alone.`,path:[n]});return}if(!(e.op!=="agent.publish"&&e.op!=="agent.republish"&&e.op!=="team.publish")){if((e.subscribe!==void 0||e.autoPush!==void 0||e.confirmPublicEgress!==void 0)&&!e.requestId){t.addIssue({code:s.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:s.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const We={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed",serverUpdating:"transient.server-updating"},qp="service is preparing a safe reload; retry shortly",eh="serve_reloading";function qy(e,t){if(e!==503||t===null||typeof t!="object")return!1;const n=t.detail;return n===qp?!0:n!==null&&typeof n=="object"&&n.code===eh}function ew(e){return e!==null&&typeof e=="object"&&e.updating===!0}function tw(e){return e!==null&&typeof e=="object"&&e.update_stalled===!0}const nw={runtimeUnreachable:"runtime_unreachable"},Ss="runtime_busy",th="runtime_retiring";s.object({data:s.object({aside_id:s.string().optional(),status:s.union([s.enum(["adopted","queued"]),s.string()]).optional()}).passthrough()}).passthrough();const nh=s.object({name:s.string(),description:s.string().nullish(),source:s.string().nullish(),link_id:s.string().nullish(),editable:s.boolean().nullish(),installed:s.boolean().nullish(),fingerprint:s.string().nullish(),form:s.string().nullish()}).passthrough(),rw=s.object({path:s.string(),size:s.number().nullish(),preview:s.string().nullish(),preview_truncated:s.boolean().nullish()}).passthrough(),ow=nh.extend({body:s.string().nullish(),body_in_detail:s.boolean().nullish(),body_length:s.number().nullish(),body_bytes:s.number().nullish(),body_truncated:s.boolean().nullish(),files:s.array(rw).nullish(),files_total:s.number().nullish(),files_truncated:s.boolean().nullish(),publish_budget:s.object({limit:s.number(),total:s.number()}).passthrough().nullish()}).passthrough(),NM=s.object({skills:s.array(nh),scope:s.string().nullish(),detail:s.string().nullish(),skill_detail:ow.nullish(),warning_count:s.number().nullish(),version:s.string().nullish()}).passthrough(),LM=s.object({reset:s.object({outcome:s.union([s.enum(["reset","already_redeemed","no_credit","nothing_to_reset","failed","refused"]),s.string()]),windows_reset:s.number().int().nonnegative(),detail:s.string().default(""),refused:s.boolean()}).passthrough(),usage:s.object({reports:s.array(s.record(s.unknown())),source:s.string(),fetched_at:s.number()}).passthrough().nullish()}).passthrough(),FM="aside_adopt_refused",iw=["session_closed","open_tool_batch","turn_running"];function UM(e){if(typeof e!="object"||e===null)return;const t=e.reason;return iw.find(n=>n===t)}const sw={[We.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[We.refused]:"ui.common.errors.desktop_refusal.refused",[We.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[We.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed",[We.serverUpdating]:"ui.common.errors.desktop_refusal.server_updating"},ec={noCredential:"Restart with a desktop-managed backend to use these controls.",transportFailed:"The backend could not complete this request. Check its connection and try again."};function Es(e){return e!==void 0&&Object.values(We).includes(e)}function aw(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return We.refused;if(t===503)return We.planeClosed}}const BM=s.object({step:s.string(),blocked_on:s.string(),configured:s.boolean(),ready:s.boolean(),verified:s.boolean(),url:s.string().nullable(),credential_id:s.number().int().positive().nullable(),identity_label:s.string().nullable(),credential_choices:s.array(s.object({id:s.number().int().positive(),identity_label:s.string().nullable().optional()}).passthrough()).default([]),quote:s.object({monthly_price_usd:s.string().nullable(),positive_balance:s.boolean(),eligible:s.boolean(),account_valid:s.boolean()}).passthrough().nullable(),receipts:s.array(s.object({step:s.string(),ok:s.boolean(),text:s.string()})).default([]),remedy:s.object({kind:s.string(),text:s.string(),command:s.string().nullable().optional(),url:s.string().nullable().optional()}).nullable(),source:s.string(),in_progress:s.boolean().default(!1),progress:s.array(s.string()).default([]),active_credential_id:s.number().int().positive().nullable().default(null),billing_outcome:s.string().optional(),reservation_outcome:s.string().optional(),failure_stage:s.string().optional(),transport:s.string().optional()}).passthrough();function HM(e){return e.transport!=="relay"?!1:e.blocked_on==="cloudflared"||e.remedy?.kind==="install_cloudflared"}const WM=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),cw=88e4,lw=11e5,dw=2e4,uw=9e4,fw=new Set(["analytics.get","analytics.models","sessions.report"]),pw=new Set(["usage.get"]),hw=new Set(["networks.list","peers.list"]),mw=new Set(["usage.reset"]),gw=new Set(["sessions.files.download"]),_w=new Set([...fw,...pw,...hw,...mw,...gw]),bw=90,vw=30,yw=300,ww=10,rh=15,kw=1e4;function Sw(e){const n=e.to==="local"||e.keep?yw:vw,r=Math.max(0,e.waitS??0);return(bw+n+ww+rh)*1e3+r*1e3}const Ew=18e4,sa=Ew+15e3,Iw=120,Aw=135e3,Rw=93e4,oh=(Iw+30+rh)*1e3,xw=6e4,Tw=5*oh,Cw=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function Ow(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 oh;case"hub.check":return xw;case"hub.applyAll":return Tw;default:return null}}function Pw(e){if(typeof e!="string"&&e.op==="sessions.transfer")return Sw(e)+kw;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential"||typeof e!="string"&&e.op==="approvals.approveOperation"&&e.operation==="pair_phone"||t==="devices.remove"||t==="operator.setup.run")return sa;if(t==="tunnel.setup.run")return Rw;if(t==="tunnel.setup.plan")return Aw;const n=Ow(t);return n!==null?n:_w.has(t)?uw:dw}const Mw=5e3;function ih(e){return Pw(e)+Mw}const il="deadline_exceeded",sh="foreground_required",ah="View these completions in the foreground before marking them read.",jw=new Set(["capabilities","agent_messages.status","agent_messages.settings","agent_messages.allowlist.get","team_bridge.conversations.list","team_bridge.conversations.get","team_bridge.messages.list","team_bridge.messages.replies","team_bridge.owner_audit.conversations","team_bridge.owner_audit.messages","team_bridge.owner_audit.replies","team_bridge.unread","team_bridge.directory","team_bridge.status","accounts.list","analytics.get","analytics.models","approvals.list","profileProposals.list","profileProposals.get","commands.entities","commands.list","config.get","credentials.list","hub.updates","hub.links","info.get","instructions.get","legacy.agent.get","legacy.agent.history","legacy.agent.schedules.list","legacy.agents.list","legacy.job.get","legacy.jobs.list","legacy.models","legacy.models.providers","legacy.schedule.get","legacy.schedules.list","mcp.catalog","mcp.list","mobile.doctor","models.catalogue","networks.list","peers.list","profiles.get","profiles.list","projects.search","providers.list","quota.notice","runtimes.list","sessions.aside.get","sessions.checkpoints","sessions.failovers","sessions.find","sessions.get","sessions.history","sessions.files","sessions.userAttachments","sessions.list","sessions.preview","sessions.report","sessions.search","sessions.variables.list","skills.list","subagents.transcript","sessions.diff","subagents.diff","teams.effective","teams.get","teams.list","tunnel.setup.plan","tunnel.setup.read","devices.list","operator.setup.read","mobile.password","usage.get"]),$w=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Dw(e,t){const n=Math.round(t/1e3),r=il;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.`}:Cw.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:jw.has(e)?{code:r,message:$w.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 GM=cw,zM=lw;s.object({state:s.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:s.string(),kind:s.enum(["balance","subscription","radient","none"]),model_free:s.boolean(),title:s.string(),body:s.string(),actions:s.array(s.object({id:s.enum(["open_url","resend_verification","refresh"]),label:s.string(),url:s.string().nullable().optional()})),resets_at_ms:s.number().int().nullable().optional(),checked_at_ms:s.number().int(),age_ms:s.number().int().nullable().optional(),source:s.enum(["cached","live"])});function Nw(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function wu(e){return{...e.in!==void 0?{in:e.in}:{},...e.at!==void 0?{at:e.at}:{},...e.every!==void 0?{every:e.every}:{},...e.until!==void 0?{until:e.until}:{},...e.limit!==void 0?{limit:e.limit}:{}}}function aa(e){return{...e.requestId?{request_id:e.requestId}:{},...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}}function ca(e){if(e.visibility==="org"!=!!e.tenantId)throw new Error('A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.')}function ku(e){return{sources:e.sources??null,session_ids:e.sessionIds??{},all:e.all??!1,include_subagents:e.includeSubagents??!1,include_cleared_segments:e.includeClearedSegments??!1,include_memory:e.includeMemory??!0,include_instructions:e.includeInstructions??!0,...e.maxSessions===void 0?{}:{max_sessions:e.maxSessions}}}function ro(e){const t=new URLSearchParams;return e.tenant_id&&t.set("tenant_id",e.tenant_id),e.expected_account_id&&t.set("expected_account_id",e.expected_account_id),t.size?`?${t.toString()}`:""}function wi(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function Lw(e){switch(e.op){case"capabilities":return{path:"/v1/capabilities",method:"GET"};case"runtimes.list":return{path:"/v1/desktop/runtimes?probe=false",method:"GET"};case"peers.list":return{path:"/v1/desktop/peers",method:"GET"};case"networks.list":return{path:"/v1/desktop/networks",method:"GET"};case"asks.list":return{path:"/v1/desktop/asks",method:"GET"};case"networks.invite":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/invite`,method:"POST",body:{role:e.role,device:e.deviceId??null}};case"networks.member.remove":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/members/${encodeURIComponent(e.deviceId)}`,method:"DELETE",body:{confirm:e.confirm}};case"sessions.transfer":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/transfer`,method:"POST",body:{to:e.to,keep:e.keep??!1,wait_s:e.waitS??0,...e.requestId?{request_id:e.requestId}:{}}};case"profileProposals.list":return{path:`/v1/desktop/profile-proposals?state=${e.state??"pending"}`,method:"GET"};case"profileProposals.get":return{path:`/v1/desktop/profile-proposals/${encodeURIComponent(e.proposalId)}`,method:"GET"};case"profileProposals.accept":return{path:`/v1/desktop/profile-proposals/${encodeURIComponent(e.proposalId)}/accept`,method:"POST",body:{request_id:e.requestId,...e.after?{after:e.after}:{}}};case"profileProposals.reject":return{path:`/v1/desktop/profile-proposals/${encodeURIComponent(e.proposalId)}/reject`,method:"POST",body:{request_id:e.requestId,...e.note?{note:e.note}:{}}};case"approvals.list":return{path:"/v1/desktop/approvals",method:"GET"};case"approvals.approve":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/approve`,method:"POST"};case"approvals.deny":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/deny`,method:"POST"};case"approvals.approveOperation":case"approvals.applyOperation":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveOperation"?"approve-operation":"apply-operation"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"approvals.pairAck":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/pair-ack`,method:"POST",body:{request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest,...e.code!==void 0?{code:e.code}:{}}};case"devices.list":return{path:"/v1/desktop/devices",method:"GET"};case"devices.remove":return{path:`/v1/desktop/devices/${encodeURIComponent(e.deviceId)}`,method:"DELETE"};case"mobile.password":return{path:"/v1/desktop/mobile/password",method:"GET"};case"operator.setup.read":return{path:"/v1/desktop/operator/setup",method:"GET"};case"operator.setup.run":return{path:"/v1/desktop/operator/setup",method:"POST",body:{}};case"approvals.approveCredential":case"approvals.applyCredential":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveCredential"?"approve-credential":"apply-credential"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"profiles.list":return{path:"/v1/desktop/profiles",method:"GET"};case"profiles.get":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"GET"};case"profiles.install":return{path:"/v1/desktop/profiles/install",method:"POST",body:{request_id:e.requestId,name:e.name}};case"imports.sources":return{path:"/v1/desktop/imports/sources",method:"GET"};case"imports.sessions":{const t=new URLSearchParams({source:e.source});return e.includeSubagents&&t.set("include_subagents","true"),{path:`/v1/desktop/imports/sessions?${t.toString()}`,method:"GET"}}case"imports.preview":return{path:"/v1/desktop/imports/preview",method:"POST",body:ku(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:ku(e)};case"imports.status":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"GET"};case"imports.cancel":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"DELETE"};case"profiles.create":return{path:"/v1/desktop/profiles",method:"POST",body:{request_id:e.requestId,name:e.name,...e.fields}};case"profiles.update":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"hub.updates":return{path:"/v1/desktop/hub/updates",method:"GET"};case"hub.skillPull":return{path:"/v1/desktop/hub/skills/pull",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.adoptionStrategy!==void 0?{adoption_strategy:e.adoptionStrategy}:{},...e.allowLlm!==void 0?{allow_llm:e.allowLlm}:{},...e.confirm!==void 0?{confirm:e.confirm}:{},...e.adoptionReceipt!==void 0?{adoption_receipt:e.adoptionReceipt}:{}}};case"hub.skillSubscribe":return{path:"/v1/desktop/hub/skills/subscribe",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias}};case"hub.skillUnpull":return{path:"/v1/desktop/hub/skills/unpull",method:"POST",body:{request_id:e.requestId,link_id:e.linkId}};case"hub.skillPublish":return{path:"/v1/desktop/hub/skills/publish",method:"POST",body:{request_id:e.requestId,dry_run:e.dryRun,source_skill:e.sourceSkill,local_alias:e.localAlias,visibility:e.visibility,tenant_id:e.tenantId,subscribe:e.subscribe,auto_push:e.autoPush,confirm_public_egress:e.confirmPublicEgress,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"hub.links":return{path:`/v1/desktop/hub/links${e.kind?`?kind=${e.kind}`:""}`,method:"GET"};case"hub.policy":return{path:`/v1/desktop/hub/links/${encodeURIComponent(e.linkId)}`,method:"PATCH",body:{request_id:e.requestId,expected_policy_revision:e.expectedPolicyRevision,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}};case"hub.check":return{path:"/v1/desktop/hub/updates/check",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{}}};case"hub.apply":return{path:"/v1/desktop/hub/updates/apply",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{},...e.prefer?{prefer:e.prefer}:{},...e.acknowledgeUnknownBaseline!==void 0?{acknowledge_unknown_baseline:e.acknowledgeUnknownBaseline}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.resolveSource===!0?{resolve_source:!0,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId??null}:{}}};case"hub.applyAll":return{path:"/v1/desktop/hub/updates/apply-all",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{}}};case"hub.retry":return{path:"/v1/desktop/hub/updates/retry",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{}}};case"hub.push":return{path:"/v1/desktop/hub/updates/push",method:"POST",body:{request_id:e.requestId,link_id:e.linkId,direction:e.direction,dry_run:e.dryRun,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"teams.list":return{path:"/v1/desktop/teams",method:"GET"};case"teams.get":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"GET"};case"teams.effective":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}/effective`,method:"GET"};case"teams.create":return{path:"/v1/desktop/teams",method:"POST",body:{request_id:e.requestId,...e.fields}};case"teams.update":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"sessions.list":{const t=new URLSearchParams;return t.set("limit",String(e.limit??100)),e.include_archived&&t.set("include_archived","true"),e.scope_kind&&t.set("scope_kind",e.scope_kind),e.scope_name&&t.set("scope_name",e.scope_name),e.cursor&&t.set("cursor",e.cursor),e.with_counts&&t.set("with_counts","true"),e.include_peers&&t.set("include_peers","true"),e.sort&&t.set("sort",e.sort),e.include_temporary&&t.set("include_temporary","true"),{path:`/v1/desktop/sessions?${t}`,method:"GET"}}case"delegated_cleanup_notice.ack":return{path:"/v1/desktop/delegated-cleanup-notice/ack",method:"POST"};case"sessions.search":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??fy)});return e.include_archived&&t.set("include_archived","true"),{path:`/v1/desktop/sessions/search?${t}`,method:"GET"}}case"sessions.archive":return{path:`/v1/desktop/sessions/${e.sessionId}/archive`,method:"POST",body:{archived:e.archived}};case"sessions.temporary":return{path:`/v1/desktop/sessions/${e.sessionId}/temporary`,method:"POST",body:{temporary:e.temporary}};case"sessions.delete":return{path:`/v1/desktop/sessions/${e.sessionId}`,method:"DELETE",body:{confirmed:!0}};case"sessions.create":return{path:"/v1/desktop/sessions",method:"POST",body:{request_id:e.requestId,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.peer?{peer:e.peer}:{},...e.target?{target:e.target}:{},...e.model?{model:e.model}:{},...e.draftId?{draft_id:e.draftId}:{},...e.purpose?{purpose:e.purpose}:{},...e.temporary?{temporary:!0}:{}}};case"sessions.preview":return{path:"/v1/desktop/sessions/preview",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.draft":return{path:"/v1/desktop/sessions/draft",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.get":{const t=new URLSearchParams;return e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),ts(t,`/v1/desktop/sessions/${e.sessionId}`,e.orderIds??[])),{path:`/v1/desktop/sessions/${e.sessionId}${t.size?`?${t}`:""}`,method:"GET"}}case"sessions.files":{const t=new URLSearchParams({limit:String(e.limit??200)});for(const n of["scope","kind","q","sort","order","cursor"]){const 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.files.download":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files/${encodeURIComponent(e.fileId)}/download`,method:"POST"};case"sessions.userAttachments":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/user-attachments`,method:"GET"};case"sessions.userAttachments.materialise":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/user-attachments/${encodeURIComponent(e.digest)}/materialise`,method:"POST"};case"sessions.history":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.openFrame&&(t.set("open_frame","1"),t.set("supplements","1"),t.set("diff_bindings","1")),e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),e.sourceRead==="metadata"?t.set("source_read","metadata"):e.sourceRead==="payload"&&e.expectedJournalGeneration&&t.set("source_read","payload"),e.expectedJournalGeneration&&t.set("expected_journal_generation",e.expectedJournalGeneration),ts(t,`/v1/desktop/sessions/${e.sessionId}/history`,e.orderIds??[])),{path:`/v1/desktop/sessions/${e.sessionId}/history?${t}`,method:"GET"}}case"sessions.checkpoints":return{path:`/v1/desktop/sessions/${e.sessionId}/checkpoints`,method:"GET"};case"sessions.checkpoints.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/checkpoints/warm`,method:"POST",body:{...e.ids?{ids:e.ids}:{},...e.limit!==void 0?{limit:e.limit}:{}}};case"sessions.find":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??hy)});return{path:`/v1/desktop/sessions/${e.sessionId}/find?${t}`,method:"GET"}}case"subagents.transcript":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.entryId&&t.set("entry_id",e.entryId),{path:`/v1/desktop/sessions/${e.sessionId}/children/${e.childId}/transcript?${t}`,method:"GET"}}case"sessions.diff":case"subagents.diff":{const t=new URLSearchParams({start:String(e.start),offset:String(e.offset??0),limit:String(e.limit)}),n=encodeURIComponent(e.callId);return{path:`/v1/desktop/sessions/${e.op==="subagents.diff"?`${e.sessionId}/children/${e.childId}`:e.sessionId}/tool-calls/${n}/diff?${t}`,method:"GET"}}case"sessions.message":return{path:`/v1/desktop/sessions/${e.sessionId}/messages`,method:"POST",body:{request_id:e.requestId,text:e.text,images:e.images??[],...e.files?.length?{files:e.files}:{},mode:e.mode??"prompt",...e.inputMode?{input_mode:e.inputMode}:{},...e.inputPath?{input_path:e.inputPath}:{}}};case"sessions.command":return{path:`/v1/desktop/sessions/${e.sessionId}/commands`,method:"POST",body:{request_id:e.requestId,command:e.command,args:e.args??"",images:e.images??[]}};case"sessions.profileActionStatus":return{path:`/v1/desktop/sessions/${e.sessionId}/profile-action-status`,method:"POST",body:{action_id:e.actionId,receipt_id:e.receiptId,profile_kind:e.profileKind,profile_name:e.profileName,tool_call_id:e.toolCallId}};case"sessions.answer":return e.askId!==void 0?{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{ask_id:e.askId,answers:e.answers,decline:e.decline,...e.revise===!0?{revise:!0}:{},...e.dismiss===!0?{dismiss:!0,...e.reason!==void 0?{reason:e.reason}:{}}:{}}}:{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{epoch:e.epoch,request_id:e.requestId,value:e.value,approved:e.approved,question_index:e.questionIndex}};case"sessions.seen":return{path:`/v1/desktop/sessions/${e.sessionId}/seen`,method:"POST",body:{completion_token:e.completionToken}};case"attention.seen":return{path:"/v1/desktop/attention/seen",method:"POST",body:{items:e.items.map(t=>({session_id:t.sessionId,completion_token:t.completionToken}))}};case"sessions.notified":return{path:`/v1/desktop/sessions/${e.sessionId}/notified`,method:"POST",body:{completion_token:e.completionToken}};case"tags.list":return{path:"/v1/desktop/tags",method:"GET"};case"tags.replace":return{path:"/v1/desktop/tags",method:"PUT",body:{tags:e.tags}};case"sessions.tags":return{path:`/v1/desktop/sessions/${e.sessionId}/tags`,method:"PUT",body:{tags:e.tags,primary:e.primary,...e.expected_revision===void 0?{}:{expected_revision:e.expected_revision}}};case"sessions.pin":return{path:`/v1/desktop/sessions/${e.sessionId}/pin`,method:"POST",body:{pinned:e.pinned}};case"sessions.watch":return{path:`/v1/desktop/sessions/${e.sessionId}/watch`,method:"POST",body:{subscription_id:e.subscriptionId,visible:e.visible,can_notify:e.canNotify}};case"sessions.presence":return{path:"/v1/desktop/presence",method:"POST",body:{subscription_id:e.subscriptionId,can_notify_kinds:e.canNotifyKinds,session_id:e.sessionId,window:e.window,can_notify:e.canNotify}};case"sessions.move":return{path:`/v1/desktop/sessions/${e.sessionId}/working-directory`,method:"POST",body:{request_id:e.requestId,cwd:e.cwd}};case"settingsIntents.list":return{path:e.sessionId?`/v1/desktop/settings-intents?session_id=${e.sessionId}`:"/v1/desktop/settings-intents",method:"GET"};case"settingsIntents.submit":return{path:`/v1/desktop/sessions/${e.sessionId}/settings-intents`,method:"POST",body:{request_id:e.requestId,kind:e.kind,value:e.value,...e.effort!==void 0?{effort:e.effort}:{}}};case"settingsIntents.dismiss":return{path:`/v1/desktop/sessions/${e.sessionId}/settings-intents/${e.kind}?generation=${e.generation}`,method:"DELETE"};case"sessions.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/warm`,method:"POST",body:{}};case"sessions.interrupt":return{path:`/v1/desktop/sessions/${e.sessionId}/interrupt`,method:"POST",body:{request_id:e.requestId}};case"supplements.cancel":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/cancel`,method:"POST",body:{anchor:e.anchor}};case"supplements.restart":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/restart`,method:"POST",body:{anchor:e.anchor}};case"supplements.steer":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/steer`,method:"POST",body:{anchor:e.anchor,text:e.text}};case"sessions.variables.list":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"GET"};case"sessions.variables.create":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"POST",body:{key:e.key,value:e.value,type:e.type}};case"sessions.variables.update":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"PATCH",body:{value:e.value,type:e.type}};case"sessions.variables.delete":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"DELETE"};case"legacy.models":{const t=new URLSearchParams;return e.provider&&t.set("provider",e.provider),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:t.size>0?`/v1/models?${t}`:"/v1/models",method:"GET"}}case"legacy.models.providers":return{path:"/v1/models/providers",method:"GET"};case"auth.probe":return{path:`/v1/auth/providers/${e.provider}/probe`,method:"POST"};case"legacy.agent.upload":return{path:`/v1/agents/${e.agentId}/upload`,method:"POST"};case"agent.publish":{ca(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"POST",body:{document:e.document??{},...aa(e)}}}case"agent.republish":{ca(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"PUT",body:{hub_agent_id:e.hubAgentId,document:e.document??{},...aa(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{ca(e);const t=new URLSearchParams;return e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId)),{path:`/v1/teams/${e.teamId}/publish${t.size?`?${t}`:""}`,method:"POST",body:aa(e)}}case"team.pull":{const t=new URLSearchParams;e.tenantId&&t.set("tenant_id",e.tenantId);const n=t.toString();return{path:`/v1/teams/pull/${e.teamId}${n?`?${n}`:""}`,method:"GET"}}case"agent.nameAvailability":return{path:`/v1/agent-name-availability?${new URLSearchParams({name:e.name})}`,method:"GET"};case"legacy.agents.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return e.name&&t.set("name",e.name),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:`/v1/agents?${t}`,method:"GET"}}case"legacy.agent.get":return{path:`/v1/agents/${e.agentId}`,method:"GET"};case"legacy.agent.history":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/history?${t}`,method:"GET"}}case"wakes.list":{const t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",String(e.limit)),e.includeDormant!==void 0&&t.set("include_dormant",String(e.includeDormant)),{path:t.size>0?`/v1/desktop/wakes?${t}`:"/v1/desktop/wakes",method:"GET"}}case"wakes.create":return{path:"/v1/desktop/wakes",method:"POST",body:{request_id:e.requestId,...Nw(e),message:e.message,...wu(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...wu(e)}};case"wakes.remove":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"DELETE"};case"monitors.list":{const t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",String(e.limit)),e.includeDormant!==void 0&&t.set("include_dormant",String(e.includeDormant)),{path:t.size>0?`/v1/desktop/monitors?${t}`:"/v1/desktop/monitors",method:"GET"}}case"monitors.cancel":return{path:`/v1/desktop/monitors/${encodeURIComponent(e.sessionId)}/${encodeURIComponent(e.monitorId)}`,method:"DELETE"};case"jobs.cancel":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/jobs/${encodeURIComponent(e.jobId)}/cancel`,method:"POST"};case"legacy.jobs.list":{const t=new URLSearchParams;return e.agentId&&t.set("agent_id",e.agentId),e.status&&t.set("status",e.status),{path:t.size>0?`/v1/jobs?${t}`:"/v1/jobs",method:"GET"}}case"legacy.job.get":return{path:`/v1/jobs/${e.jobId}`,method:"GET"};case"legacy.schedules.list":return{path:`/v1/schedules?${new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)})}`,method:"GET"};case"legacy.agent.schedules.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/schedules?${t}`,method:"GET"}}case"legacy.agent.schedule.create":return{path:`/v1/agents/${e.agentId}/schedules`,method:"POST",body:e.schedule};case"legacy.schedule.get":return{path:`/v1/schedules/${e.scheduleId}`,method:"GET"};case"legacy.schedule.edit":return{path:`/v1/schedules/${e.scheduleId}`,method:"PATCH",body:e.schedule};case"legacy.schedule.remove":return{path:`/v1/schedules/${e.scheduleId}`,method:"DELETE"};case"legacy.agent.create":return{path:"/v1/agents",method:"POST",body:e.agent};case"legacy.agent.update":return{path:`/v1/agents/${e.agentId}`,method:"PATCH",body:e.update};case"legacy.agent.delete":return{path:`/v1/agents/${e.agentId}`,method:"DELETE"};case"legacy.agent.conversation.clear":return{path:`/v1/agents/${e.agentId}/conversation`,method:"DELETE"};case"legacy.agent.systemPrompt.get":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"GET"};case"legacy.agent.systemPrompt.update":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"PUT",body:{system_prompt:e.systemPrompt}};case"legacy.agent.download":return{path:`/v1/agents/${e.agentId}/download`,method:"GET"};case"legacy.job.cancel":return{path:`/v1/jobs/${e.jobId}`,method:"DELETE"};case"commands.list":return{path:"/v1/desktop/commands",method:"GET"};case"commands.entities":return{path:`/v1/desktop/sessions/${e.sessionId}/command-entities?command=${encodeURIComponent(e.command)}${e.name?`&name=${encodeURIComponent(e.name)}`:""}`,method:"GET"};case"models.catalogue":{const t=e.scope?`&scope=${e.scope}`:"";return{path:`/v1/desktop/models?live=${e.live??!1}${t}`,method:"GET"}}case"usage.get":{const t=new URLSearchParams({live:String(e.live??!1),refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),{path:`/v1/desktop/usage?${t}`,method:"GET"}}case"usage.reset":{const t={provider:e.provider,redeem_request_id:e.redeemRequestId};return e.credentialRef&&(t.credential_ref=e.credentialRef),e.identity&&(t.identity=e.identity),{path:"/v1/desktop/usage/reset",method:"POST",body:t}}case"quota.notice":{const t=new URLSearchParams({refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),e.model&&t.set("model",e.model),{path:`/v1/desktop/quota-notice?${t}`,method:"GET"}}case"analytics.get":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics?${t}`,method:"GET"}}case"analytics.models":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics/models?${t}`,method:"GET"}}case"info.get":return{path:"/v1/desktop/info",method:"GET"};case"sessions.report":{const t=new URLSearchParams({recent_limit:String(e.recentLimit??12)});return{path:`/v1/desktop/sessions/${e.sessionId}/report?${t}`,method:"GET"}}case"skills.list":{const t=new URLSearchParams;e.sessionId&&t.set("session_id",e.sessionId),e.cwd&&t.set("cwd",e.cwd),e.name&&t.set("name",e.name);const n=t.toString();return{path:`/v1/desktop/skills${n?`?${n}`:""}`,method:"GET"}}case"skills.create":return{path:"/v1/desktop/skills",method:"POST",body:{request_id:e.requestId,name:e.name,copy_from:e.copyFrom}};case"skills.update":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"PUT",body:{request_id:e.requestId,expected_fingerprint:e.expectedFingerprint,files:e.files}};case"skills.remove":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"DELETE",body:{request_id:e.requestId,discard_local_changes:e.discardLocalChanges}};case"sessions.failovers":return{path:`/v1/desktop/sessions/${e.sessionId}/failovers`,method:"GET"};case"sessions.credential":return{path:`/v1/desktop/sessions/${e.sessionId}/credentials`,method:"POST",body:{action:e.action,key:e.key,value:e.value,confirmed:e.confirmed}};case"sessions.fork":return{path:`/v1/desktop/sessions/${e.sessionId}/fork`,method:"POST",body:{request_id:e.requestId,message:e.message,boundary:e.boundary,entry_id:e.entryId,auto_tag:e.autoTag}};case"sessions.stop":return{path:"/v1/desktop/stop",method:"POST",body:{request_id:e.requestId,targets:e.targets,confirmed:e.confirmed}};case"sessions.aside":return{path:`/v1/desktop/sessions/${e.sessionId}/asides`,method:"POST",body:{request_id:e.requestId,text:e.text,aside_id:e.asideId,subscription_id:e.subscriptionId}};case"sessions.adopt":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}/adopt`,method:"POST",body:{request_id:e.requestId,confirmed:e.confirmed}};case"sessions.aside.get":case"sessions.aside.close":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}`,method:e.op==="sessions.aside.get"?"GET":"DELETE"};case"mcp.list":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"GET"};case"mcp.credentials.store":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp/credentials`,method:"POST",body:{name:e.name,values:e.values,confirmed_replace:e.confirmedReplace}};case"mcp.control":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"POST",body:e.control};case"mcp.catalog":{const t=new URLSearchParams;e.cwd&&t.set("cwd",e.cwd),e.sessionId&&t.set("session_id",e.sessionId);const n=t.toString();return{path:n?`/v1/desktop/mcp?${n}`:"/v1/desktop/mcp",method:"GET"}}case"mcp.catalog.control":return{path:"/v1/desktop/mcp",method:"POST",body:{...e.control,...e.cwd?{cwd:e.cwd}:{}}};case"mcp.catalog.credentials":return{path:"/v1/desktop/mcp/credentials",method:"POST",body:{name:e.name,values:e.values,...e.header?{header:e.header}:{},confirmed_replace:e.confirmedReplace,...e.cwd?{cwd:e.cwd}:{}}};case"radient.request":return{path:"/v1/desktop/radient",method:"POST",body:e.control};case"providers.list":return{path:"/v1/auth/providers",method:"GET"};case"accounts.list":return{path:"/v1/auth/status",method:"GET"};case"accounts.remove":return{path:`/v1/auth/accounts/${e.accountId}`,method:"DELETE"};case"tunnel.setup.read":return{path:e.credentialId===void 0?"/v1/desktop/tunnel/setup":`/v1/desktop/tunnel/setup?credential_id=${e.credentialId}`,method:"GET"};case"tunnel.setup.plan":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"plan",...e.credentialId!==void 0?{credential_id:e.credentialId}:{}}};case"tunnel.setup.run":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"run",credential_id:e.credentialId,...e.acceptMonthlyPrice!==void 0?{accept_monthly_price:e.acceptMonthlyPrice}:{}}};case"mobile.doctor":return{path:"/v1/desktop/mobile/doctor",method:"GET"};case"auth.start":return{path:"/v1/auth/login",method:"POST",body:{provider:e.provider}};case"auth.status":return{path:`/v1/auth/operations/${e.id}`,method:"GET"};case"auth.input":return{path:`/v1/auth/operations/${e.id}/input`,method:"POST",body:{prompt_id:e.promptId,value:e.value}};case"auth.cancel":return{path:`/v1/auth/operations/${e.id}`,method:"DELETE"};case"auth.key":return{path:`/v1/auth/providers/${e.provider}/key`,method:"PUT",body:{value:e.value}};case"auth.logout":return{path:`/v1/auth/providers/${e.provider}/credentials`,method:"DELETE"};case"agent_messages.status":return{path:`/v1/desktop/team-bridge/status?boundary=${e.boundary}`,method:"GET"};case"agent_messages.enable":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,state:e.state,consent_version:e.consent_version,consented_via:e.consented_via}};case"agent_messages.settings":return{path:`/v1/desktop/team-bridge/settings${wi(e.tenant_id)}`,method:"GET"};case"agent_messages.settings.put":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,...e.tenant_id===void 0?{}:{tenant_id:e.tenant_id},...e.consent_version===void 0?{}:{consent_version:e.consent_version},...e.consented_via===void 0?{}:{consented_via:e.consented_via},...e.label===void 0?{}:{label:e.label},state:e.state}};case"agent_messages.onboarding.dismiss":return{path:"/v1/desktop/team-bridge/onboarding/dismiss",method:"POST"};case"agent_messages.allowlist.get":return{path:`/v1/desktop/team-bridge/allowlist${wi(e.tenant_id)}`,method:"GET"};case"agent_messages.allowlist.put":return{path:"/v1/desktop/team-bridge/allowlist",method:"PUT",body:{expected_account_id:e.expected_account_id,...e.tenant_id===void 0?{}:{tenant_id:e.tenant_id},entries:e.entries}};case"team_bridge.conversations.list":{const t=new URLSearchParams;return e.scope==="account"&&t.set("scope","account"),e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor),e.before&&t.set("before",e.before),e.status&&t.set("status",e.status),{path:`/v1/desktop/team-bridge/conversations${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.conversations.get":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}${wi(e.tenant_id)}`,method:"GET"};case"team_bridge.conversations.create":return{path:"/v1/desktop/team-bridge/conversations",method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},kind:e.kind,...e.name?{name:e.name}:{},...e.topic?{topic:e.topic}:{},...e.visibility?{visibility:e.visibility}:{},...e.agent_capable===void 0?{}:{agent_capable:e.agent_capable},members:e.members}};case"team_bridge.conversations.lifecycle":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/${e.action}${e.action==="join"?"":ro(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${ro(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)}${ro(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)}${ro(e)}`,method:"DELETE"};case"team_bridge.conversations.consent":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}/consent`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},decision:e.decision,...e.consent_version?{consent_version:e.consent_version}:{},...e.endpoint_id?{endpoint_id:e.endpoint_id}:{}}};case"team_bridge.owner_audit.conversations":case"team_bridge.owner_audit.messages":case"team_bridge.owner_audit.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit));let n="/v1/desktop/team-bridge/owner-audit/conversations";return e.op==="team_bridge.owner_audit.conversations"?e.cursor!==void 0&&t.set("cursor",e.cursor):(n+=`/${encodeURIComponent(e.conversation_id)}/messages`,e.op==="team_bridge.owner_audit.messages"?e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)):(n+=`/${encodeURIComponent(e.message_id)}/replies`,e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order))),{path:`${n}?${t}`,method:"GET"}}case"team_bridge.messages.list":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.endpoint_id&&t.set("endpoint_id",e.endpoint_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages${n}`,method:"GET"}}case"team_bridge.typing.get":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/typing${wi(e.tenant_id)}`,method:"GET"};case"team_bridge.typing.set":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/typing`,method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,...e.thread_root_id?{thread_root_id:e.thread_root_id}:{}}};case"team_bridge.typing.clear":{const t=new URLSearchParams({tenant_id:e.tenant_id,expected_account_id:e.expected_account_id});return e.thread_root_id&&t.set("thread_root_id",e.thread_root_id),{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/typing?${t}`,method:"DELETE"}}case"agent_messages.settings.share_typing":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,share_typing:e.share_typing}};case"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}${ro(e)}`,method:"DELETE"}}case"team_bridge.messages.send":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},client_ref:e.client_ref,body:e.body,...e.agent_label?{agent_label:e.agent_label}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{},...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.files?.length?{files:e.files}:{},...e.mentions?.length?{mentions:e.mentions}:{}}};case"team_bridge.scheduled.list":return{path:`/v1/desktop/team-bridge/scheduled?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"GET"};case"team_bridge.scheduled.create":return{path:"/v1/desktop/team-bridge/scheduled",method:"POST",body:{tenant_id:e.tenant_id,conversation_id:e.conversation_id,client_ref:e.client_ref,body:e.body,send_at:e.send_at,...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{}}};case"team_bridge.scheduled.update":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"PATCH",body:{...e.body===void 0?{}:{body:e.body},...e.send_at===void 0?{}:{send_at:e.send_at},...e.attachment_ids===void 0?{}:{attachment_ids:e.attachment_ids},...e.expected_version===void 0?{}:{expected_version:e.expected_version}}};case"team_bridge.attachments.delete":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/attachments/${encodeURIComponent(e.attachment_id)}?${new URLSearchParams({tenant_id:e.tenant_id,expected_account_id:e.expected_account_id})}`,method:"DELETE"};case"team_bridge.scheduled.cancel":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"DELETE"};case"team_bridge.messages.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit)),e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/replies${n}`,method:"GET"}}case"team_bridge.read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.seq===void 0?{}:{seq:e.seq},...e.muted===void 0?{}:{muted:e.muted}}};case"team_bridge.thread_read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/read`,method:"POST",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,seq:e.seq}};case"team_bridge.unread":{const t=new URLSearchParams;return e.scope==="account"?t.set("scope","account"):e.tenant_id&&t.set("tenant_id",e.tenant_id),{path:`/v1/desktop/team-bridge/unread${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.directory":return{path:`/v1/desktop/team-bridge/directory?tenant_id=${encodeURIComponent(e.tenant_id)}`,method:"GET"};case"team_bridge.status":{const t=new URLSearchParams;return e.boundary&&t.set("boundary",e.boundary),{path:`/v1/desktop/team-bridge/status${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.link_preview.resolve":return{path:"/v1/desktop/team-bridge/link-preview/resolve",method:"POST",body:{url:e.url,index:e.index,expected_account_id:e.expectedAccountId}};case"settings.list":return{path:"/v1/settings",method:"GET"};case"settings.edit":return{path:`/v1/settings/${e.key}`,method:"PATCH",body:{value:e.value,base:e.base}};case"settings.reset":return{path:`/v1/settings/${e.key}/reset`,method:"POST"};case"tts.paths":return{path:"/v1/tts/paths",method:"GET"};case"notification_sounds.list":return{path:"/v1/notification-sounds",method:"GET"};case"notification_sounds.rename":return{path:`/v1/notification-sounds/${e.id}`,method:"PATCH",body:{name:e.name}};case"notification_sounds.remove":return{path:`/v1/notification-sounds/${e.id}`,method:"DELETE"};case"config.get":return{path:"/v1/config",method:"GET"};case"config.update":return{path:"/v1/config",method:"PATCH",body:e.value};case"instructions.get":return{path:"/v1/config/system-prompt",method:"GET"};case"instructions.update":return{path:"/v1/config/system-prompt",method:"PATCH",body:{content:e.content}};case"credentials.list":return{path:"/v1/credentials",method:"GET"};case"credentials.update":return{path:"/v1/credentials",method:"PATCH",body:{key:e.key,value:e.value}};case"library.list":{const t=new URLSearchParams;e.scope&&t.set("scope",e.scope),e.q&&t.set("q",e.q),e.category&&t.set("category",e.category),e.kind&&t.set("kind",e.kind),e.origin_group&&t.set("origin_group",e.origin_group),e.origin&&t.set("origin",e.origin),e.tag&&t.set("tag",e.tag),e.tag_mode&&t.set("tag_mode",e.tag_mode),e.highlighted!==void 0&&t.set("highlighted",e.highlighted?"1":"0"),e.organized!==void 0&&t.set("organized",e.organized?"1":"0"),e.favorite!==void 0&&t.set("favorite",e.favorite?"1":"0"),e.session&&t.set("session",e.session),e.session_id&&t.set("session_id",e.session_id),e.sort&&t.set("sort",e.sort),e.order&&t.set("order",e.order),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);const n=t.toString();return{path:`/v1/desktop/library/assets${n?`?${n}`:""}`,method:"GET"}}case"library.get":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"GET"};case"library.update":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"PATCH",body:e.fields};case"library.tags":return{path:"/v1/desktop/library/tags",method:"GET"};case"library.tags.create":return{path:"/v1/desktop/library/tags",method:"POST",body:{name:e.name,...e.category!==void 0?{category:e.category}:{}}};case"library.tags.update":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"PATCH",body:{...e.name!==void 0?{name:e.name}:{},...e.category!==void 0?{category:e.category}:{}}};case"library.tags.delete":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"DELETE"};case"library.tags.merge":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}/merge`,method:"POST",body:{into:e.into}};case"library.tags.assign":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/tags`,method:"PUT",body:{tags:e.tags,...e.primary!==void 0?{primary:e.primary}:{}}};case"library.chat.link":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"PUT",body:{session_id:e.sessionId}};case"library.chat.clear":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"DELETE"};case"library.librarian":{const t=e.action??"status";return t==="status"?{path:"/v1/desktop/librarian",method:"GET"}:{path:"/v1/desktop/librarian",method:"POST",body:{op:t}}}case"projects.list":return{path:"/v1/desktop/projects",method:"GET"};case"projects.get":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"GET"};case"projects.create":return{path:"/v1/desktop/projects",method:"POST",body:{name:e.name,...e.description!==void 0?{description:e.description}:{},...e.status!==void 0?{status:e.status}:{},...e.tags!==void 0?{tags:e.tags}:{}}};case"projects.update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"PATCH",body:{...e.fields,...e.force_done===!0?{force_done:!0}:{}}};case"projects.delete":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"DELETE",body:{confirm:e.confirmed_name}};case"projects.link":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links`,method:"POST",body:{session_id:e.sessionId}};case"projects.unlink":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links/${encodeURIComponent(e.sessionId)}`,method:"DELETE"};case"projects.milestone":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones`,method:"POST",body:{name:e.name,...e.targetDate!==void 0?{target_date:e.targetDate}:{},...e.completed!==void 0?{completed:e.completed}:{}}};case"projects.milestone.remove":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones/${encodeURIComponent(e.name)}`,method:"DELETE"};case"projects.request_update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/request-update`,method:"POST"};case"projects.for_session":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/projects`,method:"GET"};case"projects.search":return{path:`/v1/desktop/projects/search?${new URLSearchParams({q:e.q,limit:String(e.limit??Ky)})}`,method:"GET"};case"aida.status":return{path:"/v1/desktop/aida",method:"GET"};case"aida.control":return{path:"/v1/desktop/aida",method:"POST",body:{op:e.action}};case"code_requests.list":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests`,method:"GET"};case"code_requests.refresh":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests/refresh`,method:"POST",body:{...e.keys!==void 0?{keys:e.keys}:{},...e.force!==void 0?{force:e.force}:{}}};case"static.sign":return{path:"/v1/static/sign",method:"POST",body:{route:e.route,path:e.path,ttl_s:e.ttlS}};case"sidebar_layout.get":return{path:"/v1/desktop/sidebar-layout",method:"GET"};case"sidebar_layout.set":return{path:"/v1/desktop/sidebar-layout",method:"PUT",body:{layout:e.layout}};case"notifications.list":{const t=new URLSearchParams;e.preview&&t.set("preview","true"),e.includeAskReads&&t.set("include_ask_reads","true"),e.includeSessionCounts&&t.set("include_session_counts","true");for(const n of e.countSessionIds??[])t.append("count_session_ids",n);return e.kind&&t.set("kind",e.kind),e.bulkPriority&&t.set("bulk_priority",e.bulkPriority),e.state&&t.set("state",e.state),e.source&&t.set("source",e.source),e.priority&&t.set("priority",e.priority),e.sessionId&&t.set("session_id",e.sessionId),e.cursor&&t.set("cursor",e.cursor),e.throughSeq!==void 0&&t.set("through_seq",String(e.throughSeq)),e.limit!==void 0&&t.set("limit",String(e.limit)),{path:`/v1/desktop/notifications${t.size?`?${t}`:""}`,method:"GET"}}case"notifications.get":return{path:`/v1/desktop/notifications/${encodeURIComponent(e.id)}`,method:"GET"};case"notifications.count":return{path:"/v1/desktop/notifications/count",method:"GET"};case"notifications.read":case"notifications.dismiss":return{path:"/v1/desktop/notifications",method:"PATCH",body:{op:e.verb,...Fw(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:Jy[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function Fw(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 KM=64,VM=64*1024*1024,ZM="superseded_completion_token",YM="store_busy",Uw="session_is_remote",Bw="owner_build_behind";function XM(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 Tr(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 Hw(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const JM=e=>typeof e?.goal_status=="string",QM=e=>(e?.goal??"").trim().length>0;function Ww(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function Gw(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 ko={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 zw(e){return e?e===ko.notPaired?"notPaired":e===ko.serverDown?"serverDown":e===ko.frameBudget?"frameTooLarge":"lost":"lost"}const Kw=/^[a-f0-9]{12}$/,Vw=/^[a-zA-Z0-9_-]{1,128}$/,Zw=()=>performance.timeOrigin+performance.now();function Yw(e){e&&(e.rendererEntryEpochMs=Zw())}function sl(e,t){e&&(e.delivery=t,e.deliveryAt=performance.now())}function Xw(e,t,n,r){const o=a=>a===void 0?"-":a.toFixed(3),i=(a,c)=>a===void 0||c===void 0?void 0:a-c;return["[snapshot-receipt]",`openToken=${t??"-"}`,`session=${Kw.test(e.sessionId)?e.sessionId:"?"}`,`streamId=${Vw.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(i(e.preloadReceiptEpochMs,e.mainSendEpochMs))}`,`preloadReceiptEpochMs=${o(e.preloadReceiptEpochMs)}`,`preloadReadyMs=${o(e.preloadReadyMs)}`,`bridgeApproxMs=${o(i(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(i(e.deliveryAt,e.bufferedAt))}`,`deliveryToParseMs=${o(i(n,e.deliveryAt))}`,`parseMs=${o(r-n)}`].join(" ")}const Su=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(_=>_(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},Jw=e=>e?Su(e):Su,Qw=e=>e;function qw(e,t=Qw){const n=Sd.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return Sd.useDebugValue(n),n}const Eu=e=>{const t=Jw(e),n=r=>qw(t,r);return Object.assign(n,t),n},oi=e=>e?Eu(e):Eu;function ch(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const a=l=>l===null?null:JSON.parse(l,void 0),c=(i=n.getItem(o))!=null?i:null;return c instanceof Promise?c.then(a):a(c)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,void 0)),removeItem:o=>n.removeItem(o)}}const tc=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return tc(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return tc(r)(n)}}}},e0=(e,t)=>(n,r,o)=>{let i={storage:ch(()=>localStorage),partialize:v=>v,version:0,merge:(v,b)=>({...b,...v}),...t},a=!1;const c=new Set,l=new Set;let d=i.storage;if(!d)return e((...v)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...v)},r,o);const u=()=>{const v=i.partialize({...r()});return d.setItem(i.name,{state:v,version:i.version})},f=o.setState;o.setState=(v,b)=>{f(v,b),u()};const h=e((...v)=>{n(...v),u()},r,o);o.getInitialState=()=>h;let _;const y=()=>{var v,b;if(!d)return;a=!1,c.forEach(A=>{var k;return A((k=r())!=null?k:h)});const p=((b=i.onRehydrateStorage)==null?void 0:b.call(i,(v=r())!=null?v:h))||void 0;return tc(d.getItem.bind(d))(i.name).then(A=>{if(A)if(typeof A.version=="number"&&A.version!==i.version){if(i.migrate){const k=i.migrate(A.state,A.version);return k instanceof Promise?k.then(M=>[!0,M]):[!0,k]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,A.state];return[!1,void 0]}).then(A=>{var k;const[M,P]=A;if(_=i.merge(P,(k=r())!=null?k:h),n(_,!0),M)return u()}).then(()=>{p?.(_,void 0),_=r(),a=!0,l.forEach(A=>A(_))}).catch(A=>{p?.(void 0,A)})};return o.persist={setOptions:v=>{i={...i,...v},v.storage&&(d=v.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>y(),hasHydrated:()=>a,onHydrate:v=>(c.add(v),()=>{c.delete(v)}),onFinishHydration:v=>(l.add(v),()=>{l.delete(v)})},i.skipHydration||y(),_||h},Is=e0,t0=(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 n0(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 lh=oi()(Is(e=>({notice:null,receive:t=>e(n=>t0(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:ch(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function Qn(e){return g(sw[e])}let nc=null;function r0(e){if(e===null){nc=null;return}nc={openFrame:e.openFrame===!0,journalOrder:e.journalOrder===!0,peerJournalSource:e.peerJournalSource===!0}}function dh(){return nc}const Iu=()=>g("ui.common.errors.desktop_backend_offline"),o0=()=>g("ui.common.errors.desktop_backend_compatibility");async function uh(e){if(window.api?.desktop)try{return await i0(window.api.desktop.request(e),e)}catch(n){throw n instanceof Ae?n:u0(n)?new _n(ah,sh):new Ae(null,Iu(),n)}let t;try{t=await fetch("/__desktop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(n){throw new Ae(null,Iu(),n)}if(!t.ok)throw new Ae(t.status,o0());return t.json()}function i0(e,t){const n=ih(t);let r;return Promise.race([e,new Promise((o,i)=>{r=setTimeout(()=>{const a=Dw(t.op,n);i(new Ae(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const fh="This server did not answer the request for its desktop controls.",s0=()=>g("ui.common.errors.desktop_refusal_placeholder");class Ae extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,o,i,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=o,this.retryAfterMs=i,this.detail=a}}class _n extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function al(e){return e instanceof Ae||e instanceof _n?e.code===We.serverUpdating?!0:e instanceof Ae&&ew(e.detail):!1}function qM(e){return e instanceof Ae&&tw(e.detail)}function ns(e,t){return al(e)?Qn(We.serverUpdating):e instanceof Ae||e instanceof _n?Es(e.code)?Qn(e.code):e.message===fh?s0():e.message:t}function a0(e,t,n,r){return r===eh&&t===503?We.serverUpdating:typeof r=="string"?r:n===qp&&t===503?We.serverUpdating:n===ec.noCredential?We.noCredential:n===ec.transportFailed?We.transportFailed:aw(Lw(e).path,t)}async function Ge(e){const t=await uh(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 Ae(t.status,r??fh,void 0,a0(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"&&c0(n?.result),n?.result}function c0(e){if(typeof e!="object"||e===null)return;const t=n0(e.delegated_cleanup_notice);t&&lh.getState().receive(t)}async function l0(){try{await Ge({op:"delegated_cleanup_notice.ack"})}catch{}}async function ej(){lh.getState().dismiss(),await l0()}function d0(e){return e instanceof Ae&&e.code===il}function tj(e){if(!(e instanceof Ae))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===Bw:e.code===Uw}function nj(e){return e instanceof _n&&e.code===sh}function u0(e){return e instanceof Error&&e.message.includes(ah)}async function rj(e){const t=await uh(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function oj(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await Ge({op:"auth.status",id:e});if(!n.auth_url)throw new Error("This sign-in is no longer waiting for a browser.");const 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 f0(e,t,n){const r=b0(e);return r.record?(n?.("adopted"),Au(e.sessionId,"adopted","none",rc(e),null),w0(r.record,t)):(Kt&&pn(),n?.("requested"),Au(e.sessionId,"requested",r.refusal,rc(e),r.held),ph(e,t))}const p0=6e4,h0=512;function rc(e){return{openFrame:e.openFrame===!0,journalOrder:e.journalOrder===!0,peerJournalSource:e.peerJournalSource===!0}}let Kt=null,qn=null;function pn(){qn!==null&&(clearTimeout(qn),qn=null);const e=Kt;Kt=null,e&&(e.live=null,e.buffered=[],e.disposeTransport())}function m0(){return Kt?.sessionId??null}function g0(e){!e||Kt?.sessionId!==e||pn()}function _0(e,t){if(!e||Kt?.sessionId===e)return;pn();const n=dh(),r={openFrame:n?.openFrame===!0,journalOrder:n?.journalOrder===!0,peerJournalSource:n?.peerJournalSource===!0&&t?.remoteOwned===!0};let o=!1;const i={sessionId:e,negotiation:r,buffered:[],live:null,ended:!1,disposeTransport:()=>{}};if(i.disposeTransport=ph({sessionId:e,...r.openFrame?{openFrame:!0}:{},...r.journalOrder?{journalOrder:!0}:{},...r.peerJournalSource?{peerJournalSource:!0}:{}},c=>{if(i.live){sl(c.receipt,"live"),i.live(c);return}if(c.kind==="error"||c.kind==="end"){i.ended=!0,o=!0,pn();return}if(i.buffered.length>=h0){o=!0,pn();return}c.receipt&&(c.receipt.bufferedAt=performance.now()),i.buffered.push(c)}),o){i.disposeTransport();return}Kt=i;const a=setTimeout(()=>{Kt===i&&pn()},p0);typeof a.unref=="function"&&a.unref(),qn=a}function b0(e){const t=Kt;if(!t)return{record:null,refusal:"none",held:null};if(t.ended)return pn(),{record:null,refusal:"ended",held:t.negotiation};if(t.sessionId!==e.sessionId)return{record:null,refusal:"other-session",held:null};const n=rc(e);return e.epoch!==void 0||e.afterSeq!==void 0||(e.orderIds?.length??0)>0?(pn(),{record:null,refusal:"resuming",held:t.negotiation}):n.openFrame!==t.negotiation.openFrame||n.journalOrder!==t.negotiation.journalOrder||n.peerJournalSource!==t.negotiation.peerJournalSource?(pn(),{record:null,refusal:"negotiation",held:t.negotiation}):{record:t,refusal:null,held:t.negotiation}}const v0=/^[A-Za-z0-9_-]{1,80}$/,y0="[stream-prewarm]";function Au(e,t,n,r,o){if(t==="requested"&&n==="none")return;const i=v0.test(e)?e:"?",a=l=>[l.openFrame?"1":"0",l.journalOrder?"1":"0",l.peerJournalSource?"1":"0"].join(","),c=[y0,`session=${i}`,`decision=${t}`];t==="requested"&&(c.push(`why=${n}`,`asked=${a(r)}`),o&&c.push(`prewarm=${a(o)}`),n==="negotiation"&&c.push(`caps=${dh()?"recorded":"absent"}`)),console.warn(c.join(" "))}function w0(e,t){const n=e.buffered;e.buffered=[],e.live=t,qn!==null&&(clearTimeout(qn),qn=null),Kt===e&&(Kt=null);let r=!1;return queueMicrotask(()=>{if(!r)for(const o of n)sl(o.receipt,"replay"),t(o)}),()=>{r||(r=!0,e.live=null,e.disposeTransport())}}function ph(e,t){const n=window.api?.desktop?.stream;if(n){const i=n.subscribe(e,a=>{const c=a.receipt?{...a,receipt:{...a.receipt}}:a;Yw(c.receipt),sl(c.receipt,"direct"),t(c)});return()=>i.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"),r.set("diff_bindings","1")),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),ts(r,"/__desktop/stream",e.orderIds??[]));const o=new EventSource(`/__desktop/stream?${r}`);return o.onmessage=i=>{t({kind:"data",data:i.data})},o.onerror=()=>{o.readyState===EventSource.CLOSED&&(t({kind:"error",detail:ko.ended}),o.close())},()=>{o.close(),t({kind:"end"})}}async function ij(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 i="The media request failed.",a,c;if(o.includes("application/json"))try{const l=await r.json();qy(r.status,l)&&(a=We.serverUpdating);const d=l?.detail;if(typeof d=="string")i=d;else if(typeof d=="object"&&d!==null){const u=d;typeof u.text=="string"&&u.text.trim()?i=u.text:typeof u.message=="string"&&u.message.trim()&&(i=u.message),typeof u.code=="string"&&a===void 0&&(a=u.code);const f=d.params;typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}}catch{}return{status:r.status,kind:"error",detail:i,code:a!==void 0&&Es(a)?a:i===ec.noCredential?We.noCredential:void 0,...e.op==="notification_sounds.upload"&&a!==void 0?{refusal:{code:a.slice(0,64),...c?{params:c}:{}}}:{}}}return 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 sj(e){return e.kind==="error"?Es(e.code)?new _n(Qn(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function k0(e){if(al(e))return"updating";if(d0(e))return"deadline";const t=e instanceof Ae?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const hh={updating:"",unreachable:"",deadline:"",unauthorized:"",get outdated(){return g("ui.common.connection.backend.remedy_outdated")},unknown:""},Fi={get updating(){return Qn(We.serverUpdating)},get unreachable(){return g("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return g("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return g("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return g("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function S0(e,t){const n=k0(t);return[e,Fi[n],hh[n]].filter(Boolean).join(" ")}const oc={get successor(){return g("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return g("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return g("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return g("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return g("ui.common.connection.backend.pairing_unpaired")}},E0={get successor(){return g("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return g("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return g("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return g("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return g("ui.common.connection.backend.pane_unpaired")}};function aj(e,t){return e!=="unpaired"?null:E0[t??"unpaired"]}function cj(e,t){return e!=="unpaired"?null:oc[t??"unpaired"]}function lj(e){const{kind:t,unpaired:n,answered:r,cause:o=null,servedByThisApp:i=!1}=e;return o==="pre-handshake"?i:o!==null||n?!1:r?i:t==="outdated"}function dj(e){const{kind:t,unpaired:n,missing:r,answered:o,cause:i=null}=e;if(i!==null)return oc[i];if(!o){if(t==="updating")return Fi.updating;if(t==="unreachable")return g("ui.common.connection.backend.compatibility_unreachable",{diagnosis:Fi.unreachable});if(t==="unauthorized")return g("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return g("ui.common.connection.backend.compatibility_deadline",{diagnosis:Fi.deadline});if(t==="outdated")return g("ui.common.connection.backend.compatibility_outdated",{remedy:hh.outdated})}return n?oc.unpaired:o?g("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):g("ui.common.connection.backend.compatibility_unknown")}const I0=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function uj(e,t=null){return t!==null||!e?!0:I0.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function A0(e,t){return t instanceof Ae&&t.status===null?!1:e<1}function fj(e,t){return t instanceof Ae&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const R0={get successor(){return g("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return g("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return g("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return g("ui.common.connection.backend.card_credential_refused")},get unpaired(){return g("ui.common.connection.backend.card_unpaired")}};function pj(e,t,n){return e===null?{sentence:S0(t,n),remedy:!0}:{sentence:R0[e],remedy:Np(e)}}const mh={settings:["desktop","settings"],capabilities:["desktop","capabilities"],providers:["desktop","auth","providers"],commands:["desktop","commands"],commandsFor:e=>["desktop","commands",e],accounts:["desktop","auth","accounts"],catalogue:["desktop","models"],credentials:e=>["desktop","credentials",e]},x0=3e4,T0=15e3;function C0(e){return e?.desktop_available===!0}function hj(){const{client:e,provided:t}=Pb();return Dp({enabled:t,queryKey:mh.capabilities,queryFn:async()=>{try{const n=await Ge({op:"capabilities"});return r0(P0(n)),n}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>C0(n.state.data)?x0:T0,refetchIntervalInBackground:!0},e)}function O0(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function la(e,t,n=1){return O0(e,t,n)==="enabled"}function P0(e){return{openFrame:la(e,"open_frame"),journalOrder:la(e,"journal_order"),peerJournalSource:la(e,"peer_journal_source")}}function mj(e){return Dp({queryKey:mh.providers,queryFn:()=>Ge({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:A0})}let As=!1,rs=!1;const os=[];function gj(){typeof window>"u"||!window.__loDevDriver?.armed||(As=!0,rs=!1,os.length=0)}function M0(){return As}function j0(e){if(As)try{if(os.length>=256){rs=!0;return}os.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{rs=!0}}function _j(){return{armed:As,fault:rs,receipts:os.map(e=>({...e}))}}const oo=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function gh(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=oo(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=oo(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>oo(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=oo(a);c!==null&&o.set(c,a)}const i=[];for(const a of t.order){const c=String(a),l=o.get(c);l&&(i.push(l),o.delete(c))}for(const a of r){const c=oo(a);c!==null&&o.has(c)?(i.push(a),o.delete(c)):c===null&&i.push(a)}return i}const ic=e=>({revision:xt(e),demand:e.orderDemand}),er=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Gr(e,t,n,r,o,i={}){let a=e;const c=t.journal_generation;if(t.reconcile===!0){const h=typeof c=="string"&&c.length>0?c:void 0;return a.orderNeedsReconcile&&a.orderWantedGeneration===h?a.journalMode?a:{...a,journalMode:!0}:{...a,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:h,orderDemand:h!==void 0?{generation:h}:{}}}if(typeof c!="string"||c.length===0)return t.journal_order_state&&t.journal_order_state!=="unsupported"&&!a.journalMode?{...a,journalMode:!0}:a;if(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},i.peer===!0)){const h=(a.orderRevision??0)+1,_=new Map;for(const y of a.records){const v=y.sourceEntryId??(y.kind==="tool"||y.kind==="supplement"?null:y.id);typeof v=="string"&&v.length>0&&v.length<=128&&_.set(v,h)}l={...l,..._.size>0?{journalBodyOwed:_}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(h,_,y)=>{if(!er(y))return;const v=d.get(h);v&&v.seq>=y||(d===u&&(d=new Map(d)),d.set(h,{entryId:_,seq:y}))};for(const[h,_]of Object.entries(t.journal_ordinals??{}))f(h,h,_);for(const h of n)typeof h.id=="string"&&(f(h.id,h.id,h.journal_seq),h.role==="tool"&&typeof h.tool_call_id=="string"&&f(`tool:${h.tool_call_id}`,h.id,h.journal_seq),typeof h.anchor=="string"&&f(`supplement:${h.anchor}`,h.id,h.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function cl(e,t){if(!e.journalMode||typeof t.id!="string"||!Array.isArray(t.tool_calls))return e;let n=e.journalCallOwners??new Map,r=e.journalCallSlots??new Map;const o=n,i=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===i&&(r=new Map(r)),r.set(a.id,c)))}),n===o&&r===i?e:{...e,journalCallOwners:n,journalCallSlots:r}}function _h(e,t){const n=new Set(e.map(i=>i.id));let r=!1,o;for(let i=0;i<e.length;i++){const a=e[i];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[i]=l,r=!0}o=e[i];continue}!t(a)&&o&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[i]={...a,sourceAdmissionAnchor:o.id},r=!0),o=e[i]}return r}function bh(e,t,n,r,o){const i=[],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),i.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of i)o.set(d,l);return l}const $0=Number.MAX_SAFE_INTEGER;function D0(e,t){const n=new Map,r=new Map,o=new Map;for(const i of e){if(i.sourcePrecedes===void 0)continue;const a=t(i);if(a!==void 0)r.set(i.sourcePrecedes,a);else{const c=r.get(i.sourcePrecedes);c!==void 0&&n.set(i.id,{seq:c,slot:$0})}}for(let i=e.length-1;i>=0;i--){const a=e[i];if(a.sourcePrecedes===void 0)continue;const c=t(a);if(c!==void 0)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 vh(e,t){return{floor:N0(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:D0(e,t)}}function yh(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 i=new Set;let a=1,c=t.get(e.sourcePrecedes);for(;c!==void 0&&!i.has(c.id);){i.add(c.id);const l=n(c);if(l!==void 0)return{seq:l,slot:-a};const d=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 wh(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:r}=n,o=new Set;let i=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:i}}o.add(a.id),i+=1,a=t.get(a.sourcePrecedes)}}function N0(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 kh(e,t){const n=new Map;return r=>{if(!r)return;const o=t(r);if(o===void 0)return;const i=[],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),i.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of i)n.set(d,l);return l?o:void 0}}function is(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 i=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]])||(i===t&&(i=t.slice()),a.forEach((l,d)=>{i[l]=c[d]}))}return i}function Sh(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return L0(e,t);const n=e.journalGeneration,r=e.journalPositions;let o=!1,i=!1;const a=t.map(v=>{v.sourcePrecedes!==void 0&&(i=!0);let p=[r?.get(v.sourceEntryId??v.id),r?.get(v.id)].filter(M=>M!==void 0).sort((M,P)=>P.seq-M.seq)[0];if(v.journalGeneration===n&&er(v.journalSeq)&&(!p||v.journalSeq>p.seq)&&(p={entryId:v.sourceEntryId??v.id,seq:v.journalSeq}),!p||!n||!(v.kind==="user"&&(v.provisional===!0||v.local===!0))&&v.sourceEntryId===p.entryId&&v.journalSeq===p.seq&&v.journalGeneration===n)return v;o=!0;let k={...v,sourceEntryId:p.entryId,journalSeq:p.seq,journalGeneration:n};if(k.kind==="user"){const{provisional:M,local:P,...W}=k;k=W}return k});_h(a,v=>v.journalGeneration===n&&er(v.journalSeq))&&(o=!0);const l=new Map,d=new Map(a.map(v=>[v.id,v])),u=kh(d,v=>v!==void 0&&v.journalGeneration===n&&er(v.journalSeq)?v.journalSeq:void 0),f=v=>u(v)!==void 0,h=i?vh(a,u):void 0,_=(v,b)=>{const p=u(v);if(v.kind==="user"&&v.provisional===!0&&p===void 0)return[1,0,0,0,b];const A=v.kind==="supplement"?v.anchor:v.kind==="tool"?e.journalCallOwners?.get(v.toolCallId)??e.argsByCall.get(v.toolCallId)?.anchorId:void 0,k=typeof A=="string"?u(d.get(A)):void 0,M=k===void 0&&p===void 0?yh(v,d,u,h):void 0,P=p===void 0&&M===void 0?bh(v,d,f,u,l):void 0,W=k??p??M?.seq??P;if(W===void 0){const R=wh(v,d,h);return[1,R?.slot??b,R?-R.depth:0,0,b]}return[0,W,k!==void 0?1:p!==void 0?0:M!==void 0?M.slot:2,p??Number.MAX_SAFE_INTEGER,b]},y=a.map((v,b)=>({record:v,index:b,rank:_(v,b)}));return y.sort((v,b)=>{for(let p=0;p<v.rank.length;p++){const A=v.rank[p]-b.rank[p];if(A)return A}return 0}),!o&&y.every((v,b)=>v.index===b)?is(e,t):is(e,y.map(v=>v.record))}function L0(e,t){const n=e.journalGeneration,r=e.journalPositions,o=new Map;let i=!1;for(const p of t){p.sourcePrecedes!==void 0&&(i=!0);let k=[r?.get(p.sourceEntryId??p.id),r?.get(p.id)].filter(M=>M!==void 0).sort((M,P)=>P.seq-M.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();_h(l,p=>p.journalGeneration===n&&er(p.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(p=>[p.id,p])),h=kh(f,p=>a(p)?.seq),_=p=>h(p)!==void 0,y=i?vh(l,h):void 0,v=(p,A)=>{const k=h(p);if(p.kind==="user"&&p.provisional===!0&&k===void 0)return[1,0,0,0,A];const M=p.kind==="supplement"?p.anchor:p.kind==="tool"?e.journalCallOwners?.get(p.toolCallId)??e.argsByCall.get(p.toolCallId)?.anchorId:void 0,P=typeof M=="string"?h(f.get(M)):void 0,W=P===void 0&&k===void 0?yh(p,f,h,y):void 0,R=k===void 0&&W===void 0?bh(p,f,_,h,u):void 0,m=P??k??W?.seq??R;if(m===void 0){const w=wh(p,f,y);return[1,w?.slot??A,w?-w.depth:0,0,A]}return[0,m,P!==void 0?1:k!==void 0?0:W!==void 0?W.slot:2,k??Number.MAX_SAFE_INTEGER,A]},b=l.map((p,A)=>({record:p,index:A,rank:v(p,A)}));return b.sort((p,A)=>{for(let k=0;k<p.rank.length;k++){const M=p.rank[k]-A.rank[k];if(M)return M}return 0}),!c&&b.every((p,A)=>p.index===A)?is(e,t):is(e,b.map(p=>p.record))}function Jt(e){const t=e.records.filter(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(...ll(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let o=r.length-1;o>=0;o--){const i=r[o];typeof i=="string"&&e.journalSourceVoid.has(i)&&r.splice(o,1)}return[...new Set(r.filter(o=>typeof o=="string"&&o.length>0&&o.length<=128))]}function ll(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 Jt(e).filter(r=>!n?.has(r)&&!t?.has(r))}const xt=e=>e.orderRevision??0;async function F0(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"?ll(c):l==="lookup"?Eh(c):Jt(c);let o=e.getTranscript().journalGeneration,i=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=ic(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",h=Qv(r(c,f).filter(b=>!n(f).has(b)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),_=await e.read(h,f);if(!e.isCurrent()||xt(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(_,d,l),!e.isCurrent())return{kind:"stale"};const y=e.getTranscript(),v=e.page(_);if(v.journal_order_state==="ready"&&v.journal_generation===y.journalGeneration){v.journal_generation!==o&&(t.clear(),o=v.journal_generation);for(const A of h)n(f).add(A);if(y.orderNeedsReconcile){if(y.orderDemand===l.demand||i===1)return{kind:"waiting"};i++,t.clear();continue}if(f==="payload"){const A=(v.source_retry_ids??[]).filter(k=>typeof k=="string"&&k.length>0&&k.length<=128);if(A.length>0&&h.length>1&&a===0){a++;for(const k of A)n("payload").delete(k);continue}}const b=e.sweep?.(y,n);if(b?.kind==="none")return{kind:"complete",transcript:y};const p=b?.kind??"authority";if(r(y,p).some(A=>!n(p).has(A)))continue;return{kind:"complete",transcript:y}}if(!y.orderNeedsReconcile||y.orderDemand===l.demand||i===1)return{kind:"waiting"};i++,t.clear()}}function Ft(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const o=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof o=="string"&&o?o:e.id}function da(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function Ru(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function bj(e){if(!e||e.runs_state!=="ready")return null;const t=e.runs;if(!t||t.length===0)return null;const n=new Map;for(const i of t){if(!i.settled||typeof i.run_key!="string"||i.run_key.length===0)continue;const a=da(i.action_count);if(a===null)continue;const c={actions:a,workedSeconds:Ru(i.worked_seconds),failed:da(i.failed_count)??0,complete:i.complete!==!1,openingUserId:typeof i.opening_user_id=="string"&&i.opening_user_id.length>0?i.opening_user_id:null,closingAnswerId:typeof i.closing_answer_id=="string"&&i.closing_answer_id.length>0?i.closing_answer_id:null,crossSessionActions:da(i.cross_session_action_count),crossSessionWorkedSeconds:Ru(i.cross_session_worked_seconds)};n.set(i.run_key,c),c.openingUserId!==null&&n.set(c.openingUserId,c),c.closingAnswerId!==null&&n.set(c.closingAnswerId,c)}if(n.size===0)return null;const r=new Set;for(const i of e.entries)r.add(Ft(i));const o=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:o?Ft(o):null}}}function U0(e){if(!e||e.runs_state!=="ready"||e.head_cut===!0)return null;const t=e.runs,n=e.entries[0];if(!n||!t||t.length===0||!t.find(i=>i.opening_user_id===n.id))return null;const o=Math.round((n.ts??0)*1e3);return o>0?{id:n.id,tsMs:o}:null}function B0(e,t,n){const r=U0(e),o=e?.entries;if(r===null||!o||o.length===0)return!1;const i=Math.round((o[o.length-1].ts??0)*1e3);if(!(i>r.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>r.tsMs)||!(c<i)))return!1;return!0}const H0=new Set(["completed","done","failed","cancelled","interrupted"]);function W0(e,t){const n=new Set;for(const o of t)o.kind==="custom"&&o.jobId&&n.add(o.jobId);const r=[];for(const o of e){const i=o.id==null?"":String(o.id);!i||n.has(i)||H0.has(String(o.status??""))&&r.push(i)}return r}function G0(e,t,n,r){let o=t,i=!1;for(const a of e){const c=a.changes??{};Array.isArray(c.jobs)?o=c.jobs:a.job_deltas&&(o=gh(o,a.job_deltas));const l=c.history_cursor;typeof l=="string"&&l!==""&&!r(l)&&(i=!0)}return i?W0(o,n):[]}const dl=new Set,Dn="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",ul=new RegExp(`[${Dn}]`),z0=new RegExp(`[${Dn}]+`),vj=new RegExp(`[${Dn}]+`,"g"),K0=new RegExp(`^[${Dn}]+|[${Dn}]+$`,"g"),V0=new RegExp(`^[${Dn}]+`),yj=new RegExp(`[^${Dn}]`);function nn(e){return e.replace(K0,"")}function Wo(e){return e.replace(V0,"")}function Ih(e,t){return t===0||ul.test(e[t-1])}function Ah(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&Ih(e,n)&&t.push(n);return t}function fl(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
2
- `,n-1)+1,o=e.indexOf(`
3
- `,n),i=o===-1?e.length:o;let a=e.slice(r,i);return a.endsWith("\r")&&(a=a.slice(0,-1)),{line:a,lineStart:r,column:n-r}}function Z0(e,t){if(t.size===0)return null;for(const n of Ah(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 pl(e,t,n){const r=Z0(e,n);let o=null;for(const i of Ah(e)){if(i===r)return t>i?i:o;i<=t&&(o=i)}return o}function Y0(e,t=null,n=dl){const{line:r,lineStart:o,column:i}=fl(e,t),a=pl(r,i,n);if(a===null)return null;let c=a+1;for(;c<r.length&&!ul.test(r[c]);)c++;return i>c?null:{start:o+a,query:r.slice(a+1,c),end:o+c}}function wj(e,t=null,n=dl){const{line:r,lineStart:o,column:i}=fl(e,t),a=pl(r,i,n);return a===null?null:{start:o+a,end:o+r.length}}function X0(e,t,n=null,r=dl){const{line:o,lineStart:i,column:a}=fl(e,n),c=r.size>0?r:new Set(t.map(_=>_.toLowerCase())),l=pl(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(_=>_.toLowerCase()===f.toLowerCase()))return null;const h=l+1+f.length;return a<=h?null:{value:d.slice(u+1),start:i+h+1,end:i+o.length,tokenStart:i+l}}function xu(e,t){return nn(e.slice(0,t))===""}function kj(e,t,n,r){const o=X0(e,r,t,n);if(o!==null&&xu(e,o.tokenStart))return"argument";const i=Y0(e,t,n);return i!==null&&xu(e,i.start)?"command":null}function Sj(e,t,n,r){let o=t,i=n;const a=c=>c>=0&&c<e.length&&`
4
- `.includes(e[c]);return r===""?o>0&&a(o-1)?o-=1:a(i)&&(i+=1):o===0&&a(i)&&(i+=1),{text:`${e.slice(0,o)}${r}${e.slice(i)}`,caret:o+r.length}}const J0=1e3,Q0=900,q0=40,Rh=3;function ek(e,t){let n=0,r=-2,o=0;for(const i of e){const a=t.indexOf(i,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(q0,n))}function xh(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n?n===r?J0:r.startsWith(n)?Q0:ek(n,r):0}function tk(e){const n=nn(e).split(z0).pop()??"";return n.startsWith("/")?n.slice(1):n}function nk(e,t){const n=tk(e),r=[];return t.forEach((o,i)=>{let a=0,c=o.name;for(const l of[o.name,...o.aliases]){const d=xh(n,l);d>a&&(a=d,c=l)}a>0&&r.push({score:a,index:i,name:c,command:o})}),r.sort((o,i)=>i.score-o.score||o.index-i.index),r.map(o=>({name:o.name,command:o.command}))}function Ej(e,t){if(!e)return t.map(i=>({name:i.name,command:i}));const n=nk(`/${e}`,t);if(e.length>=Rh)return n;const r=e.toLowerCase(),o=n.filter(({name:i})=>i.toLowerCase().startsWith(r));return o.length>0?o:n}function Tu(e,t){if(!e)return t.map(r=>({name:r.name,choice:r}));const n=[];return t.forEach((r,o)=>{const i=Math.max(0,...[r.name,...r.aliases??[]].map(a=>xh(e,a)));i>0&&n.push({score:i,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 Cu=/^-+/;function Ij(e,t,n,r,o){if(o)return!0;const i=nn(e).toLowerCase(),a=nn(t).toLowerCase();return i===a||i.length>0&&i.replace(Cu,"")===a.replace(Cu,"")?!0:!r&&n<=1}const rk=new RegExp("\\p{Ll}","u");function Th(e){for(const t of e)if(rk.test(t))return!0;return!1}function Aj(e,t,n){if(n){if(!e)return t.map(a=>({name:a.name,choice:a}));const r=Tu(e,t);if(e.length>=Rh)return r;const o=e.toLowerCase(),i=r.filter(a=>a.name.toLowerCase().startsWith(o));return i.length>0?i:r}return Th(e)?Tu(e,t).filter(r=>r.name.startsWith(e)):[]}const ok=/<skill name="([^"]*)" invocation="([^"]*)">/,ik=/[A-Za-z0-9]/,sk=/[A-Za-z0-9._-]/,ak=/[._-]/;function ck(e,t){if(t>=e.length||!ik.test(e[t]))return t;let n=t+1;for(;n<e.length&&sk.test(e[n]);)n++;return n}function lk(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!Ih(e,n)){n+=1;continue}const r=ck(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 dk(e,t,n,r,o,i){let a=n;for(;;){const c=e.slice(t+1,a);if(r.has(c))return{end:a,name:c};if(i||Th(c)){const l=o.get(c.toLowerCase());if(l!==void 0)return{end:a,name:l}}if(a>t+2&&ak.test(e[a-1])){a-=1;continue}return null}}function uk(e,t,n={}){return Ch(e,t,n.skipSpans??[],!0)}function Rj(e,t,n={}){return Ch(e,t,n.skipSpans??[],!1)}function Ch(e,t,n,r){const o=new Set(t),i=new Map;for(const l of t)i.has(l.toLowerCase())||i.set(l.toLowerCase(),l);const a=[],c=new Set;for(const l of lk(e)){if(n.some(([f,h])=>f<=l.start&&l.start<h))continue;const d=Wo(e.slice(0,l.start))==="",u=dk(e,l.start,l.end,o,i,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 Cr="<operator-skills>",ss="</operator-skills>",go=`
5
-
6
- `,Oh="The user invoked the following skills directly. Follow them for this request. Their reference files, if any, are listed at the end of each body and are read with `skill://<name>/<path>`.",hl="​",fk=Cr.replace("<",`<${hl}`),pk=ss.replace("<",`<${hl}`),hk=`<${hl}skill name=`,mk=/^<skill name="([^"]*)">/;function gk(e){return e.replace(/<\/operator-skills>/g,pk).replace(/<operator-skills>/g,fk).replace(/<skill name="/g,hk)}function xj(e){const t=e.map(({name:n,body:r})=>`<skill name="${n}">
7
- ${gk(r)}
8
- </skill>`);return Cr+go+Oh+go+t.join(go)+go+ss}function ml(e){const t=[],n=Cr+go+Oh;let r=0;for(;;){const o=e.indexOf(n,r);if(o===-1)return t;const i=e.indexOf(ss,o+n.length),a=e.indexOf(Cr,o+Cr.length);if(i===-1||a!==-1&&a<i){r=o+Cr.length;continue}const c=i+ss.length;t.push([o,c]),r=c}}function _k(e){const t=[];for(const[n,r]of ml(e)){let o=0;for(const i of e.slice(n,r).split(`
9
- `)){if(o>0){i.startsWith("</skill>")&&(o-=1);continue}const a=mk.exec(i);a!==null&&(t.push(a[1]),o=1)}}return t}function Tj(e,t){const n=ml(e),r=uk(e,t,{skipSpans:n});if(r.length===0)return[];const o=new Set(_k(e));return r.filter(i=>!o.has(i.name))}const Ou=new RegExp(`[${Dn}]+$`);function Ph(e){const t=ml(e);if(t.length===0)return e;const n=[];let r=0;for(const[i,a]of[...t].sort((c,l)=>c[0]-l[0])){if(a<=r)continue;const c=Math.max(i,r);n.push(e.slice(r,c).replace(Ou,"")),r=a}n.push(e.slice(r).replace(Ou,""));let o="";for(const i of n)i&&(o&&!ul.test(i[0])&&(o+=" "),o+=i);return o}function Cj(e){if(!e||nn(e)==="")return!1;let t=Wo(e);if(t.startsWith("---")){const n=t.slice(3),r=n.indexOf(`
10
- ---`);r!==-1&&(t=n.slice(r+4))}return nn(t)!==""}function bk(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 vk(e,t=0){return(nt[e[t+0]]+nt[e[t+1]]+nt[e[t+2]]+nt[e[t+3]]+"-"+nt[e[t+4]]+nt[e[t+5]]+"-"+nt[e[t+6]]+nt[e[t+7]]+"-"+nt[e[t+8]]+nt[e[t+9]]+"-"+nt[e[t+10]]+nt[e[t+11]]+nt[e[t+12]]+nt[e[t+13]]+nt[e[t+14]]+nt[e[t+15]]).toLowerCase()}let ua;const yk=new Uint8Array(16);function wk(){if(!ua){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ua=crypto.getRandomValues.bind(crypto)}return ua(yk)}const kk=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Pu={randomUUID:kk};function Sk(e,t,n){if(Pu.randomUUID&&!e)return Pu.randomUUID();e=e||{};const r=e.random??e.rng?.()??wk();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,vk(r)}const Mh=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,sc=e=>{let t=e;for(;;){const n=Mh.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},Mu=e=>{const t=[];let n=e;for(;;){const r=Mh.exec(n);if(r===null)break;t.push({id:Sk(),text:r[1]}),n=n.slice(r[0].length)}return{replies:t,remainingContent:n.trim()}};function Rs(e){return gl(e)?.skill}const Ek=/^\s/,Ik=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,Ak=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function Rk(e){const t=Wo(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 xk(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function ju(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 i=e.slice(r+1).trim();if(i!==""&&!i.startsWith("#"))return null;const a=n.join(""),c=t==="'"?a.replace(/''/g,"'"):xk(a);return c===""?null:c}return null}function Tk(e){const t=e.split(`
13
- `);for(const[n,r]of t.entries()){if(!r.startsWith("description:"))continue;const o=r.slice(12).trim(),i=o!==""&&Ik.test(o),a=[];o!==""&&!i&&a.push(o);for(let u=n+1;u<t.length;u+=1){const f=t[u];if(f.trim()!==""){if(!Ek.test(f))break;a.push(f.trim())}}if(a.length===0)return null;const c=a.join(" ");if(i)return c.trim()===""?null:c.trim();if(c.startsWith('"'))return ju(c,'"');if(c.startsWith("'"))return ju(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function gl(e){const{prefix:t,rest:n}=sc(e),r=n.slice(0,n.length-Wo(n).length),o=Wo(n),i=Ak.exec(o);if(i===null)return null;const a=ok.exec(o.slice(i[0].length));if(a===null||a.index!==0||a[1]!==i[1])return null;const c=i[0].length+a[0].length,l=o.indexOf("</skill>",c);if(l===-1)return null;const d=o.slice(c,l),u=Rk(d),f=u===null?null:Tk(d.slice(0,u)),h=a[1],_=bk(a[2]);return{text:t+r+_,skill:{name:h,token:`$${h}`,request:nn(o.slice(l+8)),purpose:f,body:nn(u===null?d:d.slice(u))}}}function Oj(e){const t=gl(e);if(t!==null)return t.text;const n=Ph(e);return n===e?e:nn(n)}function Ck(e){const t=gl(e);if(t===null){const r=Ph(e);if(r===e)return null;const{prefix:o}=sc(e);return{replies:Mu(e).replies,text:r.slice(o.length).trimStart()}}const{prefix:n}=sc(e);return{replies:Mu(e).replies,text:t.text.slice(n.length).trimStart()}}function Pj(e){return Ck(e)?.text??e}const Ok=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"]]),Pk=/\blabel=(['"])(.*?)\1/,Mk=/\bjob=(['"])(.*?)\1/,jk=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function ac(e){const t=typeof e.text=="string"?e.text:"",n=jk.exec(t);let r=n?.[2];const o=r?.indexOf(`
14
-
15
- `)??-1,a=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&o>=0?Ok.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:zr(e.label??(n&&Pk.exec(n[0].split(`
16
- `,1)[0])?.[2])),jobId:zr(e.job_id??(n&&Mk.exec(n[0].split(`
17
- `,1)[0])?.[2])),sender:Fh(e).sender,expectsReply:typeof e.expects_reply=="boolean"?e.expects_reply:e.expects_reply===void 0&&a?a==="ask":null,steer:typeof e.steer=="boolean"?e.steer:e.steer===void 0&&a?a==="steer":null}}function Mj(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 $k(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 jj(e){return $k(e)!==null}const jh=/\s+/,Dk=/[\\/]+$/,Nk=/[\\/]/,$h=`
18
-
19
- `,Lk=" — cancel with wake(",Fk=120,Dh=/(?:\u001b[\]PX^_]|[\u009d\u0090\u0098\u009e\u009f])(?:(?!\u0007|\u001b\\|\u009c)[\s\S])*(?:\u0007|\u001b\\|\u009c|$)|(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]|(?:\u001b\[|\u009b)[0-?]*[ -/]*$|\u001b[ -/]+[0-~]|\u001b[@-Z\\-_]|\u001b$|[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g,Uk=new RegExp("\\p{Cf}","gu"),Bk=4096;function zr(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(Dh,"").replace(Uk,"").split(jh).filter(Boolean).join(" ").slice(0,Fk)}const $j={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function Nh(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(Dk,"");if(t){const n=t.split(Nk).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function Lh(e){const{name:t,quoted:n}=Nh(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function Hk(e){const{name:t,quoted:n}=Nh(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 Dj(e,t){return t.trim()?!0:Hk(e)!==Lh(e)}function Wk(e){for(const t of e.slice(0,Bk).split(`
20
- `)){const n=zr(t);if(n)return n}return""}function Nj(e,t){const n=Lh(e),r=Wk(t);return r?`${n} · ${r}`:n}function fa(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const Gk=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,zk=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,Kk=/^<peer-session-message[^>]*>/,Vk=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function Fh(e){const t=String(e.text??e.detail??""),n=Gk.exec(t.trim()),r={};if(n)for(const d of n[1].matchAll(Vk))r[d[1]]=d[2]??d[3]??d[4]??"";const o=n?n[2]:"",a=(String(e.body??"").trim()||o||(n?"":t.trim().replace(Kk,""))).replace(zk,"").trim(),c=e.sender??{},l=(d,u)=>zr(d)||zr(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 Zk(e){return!!e.wake_catchup}function Yk(e){return e.hidden===!0}function Lj(e){let t=e.split($h)[0]??"";t=t.split(jh).filter(Boolean).join(" "),t=t.split(Lk)[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 Fj(e){const t=e.indexOf($h);return t===-1?"":e.slice(t+2).trim()}const ki=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},io=e=>typeof e=="string"?zr(e):"";function Xk(e){const t=ki(e.bridge_receipt),n=t.v===1,r=ki(n?t.sender:e.sender),o=n?ki(t.conversation):{},i=n?t.attachment_count:void 0;return{sender:{name:io(r.name),...r.kind==="human"||r.kind==="agent"?{kind:r.kind}:{},...io(r.organization)?{organization:io(r.organization)}:{}},conversation:{...o.kind==="dm"||o.kind==="group"||o.kind==="channel"?{kind:o.kind}:{},...io(o.label)?{label:io(o.label)}:{}},...typeof i=="number"&&Number.isSafeInteger(i)&&i>=0?{attachmentCount:i}:{}}}const Jk=new Set(["channel_post","channel_create","channel_history","channel_thread","react","shared_history"]),Qk=new Set(["channel_post","dm","send","reply"]),qk=new Set(["take_up","ack","send","reply","channels","channel_create","channel_post","channel_history","react","channel_thread","directory","dm","shared_conversations","shared_history"]),eS=/^(?:bcv|bcmsg|acc|ep)_/i,tS=/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]|\x9b[0-?]*[ -/]*[@-~]/g,nS=/[\x00-\x08\x0e-\x1f\x7f-\x9f]/g,Uh=new RegExp("(?![\\u200c\\u200d])\\p{Cf}","gu");function Uj(e){return e.replace(Uh,"")}const rS=/[\t\n\r\v\f ]+/,oS=/\r\n|\r|\n/,iS=/^bcv_\S+$/,sS=200;function Go(e){return typeof e!="string"?null:e.replace(tS,"").replace(nS,"").replace(Uh,"").split(rS).filter(Boolean).join(" ").slice(0,sS)||null}function Zn(e){const t=Go(e);return t&&!eS.test(t)?t:null}const aS=/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d{1,9}[.)]\s+)+/u,cS=/!?\[([^\]]*)\]\([^)]*\)/gu,lS=/\*\*|__|~~|`+/gu,dS=/(?<![\p{L}\p{N}_*])[*_](?=[^\s*_])|(?<=[^\s*_])[*_](?![\p{L}\p{N}_*])/gu,uS=/^[-=*_~`#> ]*$/;function fS(e){return e.replace(aS,"").replace(cS,"$1").replace(lS,"").replace(dS,"")}function pa(e){if(typeof e!="string")return null;for(const t of e.split(oS)){const n=Go(fS(t));if(n&&!uS.test(n))return n}return null}const bn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function Bh(e){if(typeof e!="string")return null;try{return JSON.parse(e)}catch{}const t=e.indexOf(`
21
-
22
- `);if(t<0)return null;try{return JSON.parse(e.slice(t+2))}catch{return null}}function pS(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 Hh(e){return Jk.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function Wh(e,t,n){const 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=bn(Bh(n?.content)),c=Zn(a?.name);if(c)return c}if(e==="channel_create"){const a=Zn(t.name);if(a)return a}const o=Hh(e);if(o!=="person"&&o!=="dm")return null;const i=bn(t.to);return Zn(i?.name)}function hS(e,t,n){const r=Hh(e);return r==="none"||r==="message"||r==="directory"?{kind:r,label:null}:{kind:r,label:Wh(e,t,n)}}function mS(e){if(Array.isArray(e))return e.length;const t=bn(e);if(!t)return null;for(const n of["conversations","items","data"])if(Array.isArray(t[n]))return t[n].length;return null}function gS(e,t){if(!t)return null;const n=Bh(t.content),r=bn(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=bn(r.root)?1:0,i=Array.isArray(r.replies)?r.replies.length:null;return i===null&&o===0?null:o+(i??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"?mS(n):null}function _S(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=Go(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 xs(e,t){const n=e??{},r=Go(n.op)??"",o=bn(t),i=qk.has(r),a=Qk.has(r)||r==="take_up"?pa(n.body)??pa(n.text)??pa(o?.text):null;return{op:r,action:pS(r,n,o),target:i?hS(r,n,o):{kind:"none",label:null},preview:a,count:i&&o?.ok===!0?gS(r,o):null,emoji:r==="react"?Go(n.emoji):null,...i?_S(r,o):{outcome:null,code:null}}}function Gh(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&iS.test(n.trim()))return n.trim();return null}const bS=new Set(["channel_post","dm","send","reply","channels","channel_create","channel_history","channel_thread","react","react_remove","directory","shared_conversations","shared_history","take_up","ack_working","ack_done"]),zh=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return bS.has(t)?t:"unknown"},vS={channel_post:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:g("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:g("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:g("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function cc(e){return vS[zh(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"?g("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?g("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?g("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?g("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function lc(e,t,n,r){const o=Gh(t,r),i=!e.target.label&&o&&n?n(o):null,a=Kh(e,i),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?a:g("ui.chat.canonical.tool_row.bridge.summary.messages",{target:a,count:e.count}).trim();switch(zh(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?g("ui.chat.canonical.tool_row.bridge.target.thread",{target:a}):a;return c(d,e.preview)}case"dm":case"send":case"reply":case"take_up":return c(a,e.preview);case"channels":case"shared_conversations":return e.count===null?"":g("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":g("ui.chat.canonical.tool_row.bridge.summary.members",{count:e.count});case"channel_history":case"channel_thread":case"shared_history":return l();case"react":case"react_remove":return c(a,e.emoji);case"channel_create":case"ack_working":case"ack_done":return a;default:return e.op}}function yS(e){return e.outcome==="refused"?e.code?g("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):g("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?g("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):g("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const wS=["conversation_id","message_id","seq","thread_root_id","body_sha256","destination_type","receipt_stage","execution_confirmed","resolved_account_id","recipient_state","account_id","endpoint_id","state","code"];function Vh(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const r=bn(t);if(!r)return n??null;const{_images:o,...i}=r;return n&&SS(n,i)?n:i}function kS(e){const t=bn(e);if(!t)return null;const n=t.destination_type==="conversation_dm"?"dm":t.state==="created"?"channel_create":"channel_post";return Wh(n,{},t)}function Zh(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:bn(t)?kS(t):n??null}function SS(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 ES={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"},IS=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function $u(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function Bj(e,t){const n=e.args??{},r=e.details??null,o=xs(n,r),i=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=Gh(n,r),c=!i.target.label&&a&&t?t(a):null,l=Kh(i,c),d=i.outcome==="refused"||i.outcome==="failed",u=e.failed||d?cc(i.action).failed:null,f=u??cc(i.action).settled,h=lc({...i,preview:null,emoji:null},n,t,r),_=i.target.label??Zn(c)??g("ui.chat.canonical.tool_row.bridge.fallback.teammate"),y=i.op==="dm"?g("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:_}):h?g("ui.chat.canonical.tool_row.bridge.detail.headline.target",{verb:f,target:h}):f,v=[n.body,n.text,r?.text].find(S=>typeof S=="string"&&S.trim()!==""),b=typeof r?.seq=="number"?r.seq:null,p=$u(r?.error),A=(i.target.kind==="channel"||i.target.kind==="dm")&&l?l:g("ui.chat.canonical.tool_row.bridge.fallback.conversation"),k=p?p.replace(IS,(S,T)=>T.toLowerCase()==="bcv"?A:"…"):null,M=i.outcome==="refused"||i.outcome==="failed"?k&&i.code?g(i.outcome==="refused"?"ui.chat.canonical.tool_row.bridge.detail.outcome.refused":"ui.chat.canonical.tool_row.bridge.detail.outcome.failed",{code:i.code,error:k}):k:i.outcome==="unconfirmed"?k:r?.ok===!0&&b!==null?g("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:b}):null,P=[],W=new Set,R=(S,T)=>{const N=$u(T);N===null||W.has(S)||(W.add(S),P.push({key:S,value:N}))};for(const S of wS)R(S,r?.[S]);p&&p!==k&&R("error",p);for(const[S,T]of Object.entries(ES))R(T,n[S]);const m=typeof r?.content=="string"&&r.content||e.output||null,w=m&&m.trim()===p?null:m;return{tokens:i,summary:lc(i,n,t,r),failedVerb:u,failureWord:yS(i),headline:y,body:v??null,outcome:M,internals:P,raw:w}}const AS=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),RS=new Set(["true","yes","y","t","on","1"]),xS={hub:{steps:e=>{const t=jr(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=jr(e);return t!==null&&t>0?`· ${qh(t/1e3)}`:""}}};function jr(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"&&e!==""){const t=Number(e);return Number.isFinite(t)?t:null}return null}const Du="mcp__",TS=/^\/(?:Users|home)\/[^/]+\//,CS=/\s+/;function OS(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(TS,"~/")}function wt(e){return typeof e=="string"?OS(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function PS(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function MS(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(CS).filter(Boolean).join(" ")||"?"}function jS(e){return[PS(e),wt(MS(e))||"?",wt(e.message)].filter(Boolean).join(" · ")}const $S=new Set(["delivered","mailbox","unconfirmed","failed"]);function DS(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:r}=xs({op:n},t);return r==="inbox_only"?"inbox_only":r==="awaiting_acceptance"?"awaiting_acceptance":r==="unconfirmed"?"unconfirmed":null}function NS(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return DS(e);const n=e.delivery;if(!n||typeof n!="object")return null;const r=n.state;return typeof r=="string"&&$S.has(r)?r:null}function Yh(e,t,n){return!e||typeof e!="object"?t??null:NS(e,n)}function LS(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 FS=["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 US(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 BS=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function HS(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:BS.every(i=>i==="cost"?n.cost?.basis===o.cost?.basis:n[i]===o[i])})}function WS(e,t){for(const n of FS){const r=e[n],o=t[n];if(n==="artifacts"){if(!HS(r,o))return!1;continue}if(n==="cost"){const i=a=>a&&typeof a=="object"?a.basis:void 0;if(i(r)!==i(o))return!1;continue}if(n==="log_lines"){if(!US(r,o))return!1;continue}if(r!==o)return!1}return!0}function Xh(e,t){const n=LS(e);return n?t&&WS(n,t)?t:n:t??null}const GS={mailbox:"ui.chat.trace.send.delivery.mailbox.word",unconfirmed:"ui.chat.trace.send.delivery.unconfirmed.word",failed:"ui.chat.trace.send.delivery.failed.word"},zS={mailbox:"ui.chat.trace.send.delivery.mailbox.title",unconfirmed:"ui.chat.trace.send.delivery.unconfirmed.title"},KS={mailbox:"ui.chat.trace.send.delivery.mailbox.note",unconfirmed:"ui.chat.trace.send.delivery.unconfirmed.note",failed:"ui.chat.trace.send.delivery.failed.note"},VS={mailbox:"ui.chat.trace.send.delivery.mailbox.label",unconfirmed:"ui.chat.trace.send.delivery.unconfirmed.label"};function Jh(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const Ts=e=>e?g(e):null,ii=e=>e.trim().toLowerCase()==="bridge";function Hj(e,t=""){return e?e==="inbox_only"?g("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?g("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&ii(t)?g("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):Ts(GS[e]):null}function Wj(e,t){return e==="inbox_only"?g("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?g("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&ii(t)?g("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function Gj(e,t=""){if(e)return e==="inbox_only"?g("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?g("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&ii(t)?g("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):Ts(zS[e])??void 0}function zj(e,t=""){return e?e==="inbox_only"?g("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?g("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&ii(t)?g("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):Ts(VS[e]):null}function Kj(e,t=""){return e?e==="inbox_only"?g("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?g("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&ii(t)?g("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):Ts(KS[e]):null}function Vj(e){return Jh(e)?"partial":null}function Zj(e){return e==="failed"?g("ui.chat.trace.send.delivery.failed.verb"):null}function Yj(e,t){return e!==!0?!1:!Jh(t)}function Nu(e){const t=jr(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:wt(e.session)||wt(e.target)||"?"}function ZS(e){const t=wt(e.query);if(t){const a=jr(e.steps);return a!==null&&Number.isInteger(a)&&a>=0?`search ${t} · ${a} around`:`search ${t}`}const n=jr(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=jr(e.head);if(r!==null&&Number.isInteger(r)&&r>=0)return`first ${r}`;if(e.digest===!0)return"digest";const o=wt(e.before_id);if(o)return`before ${o}`;const i=wt(e.around_id);return i?`around ${i}`:""}function YS(e){const t=qS(e);if(t==="spawn"){const n=wt(e.visibility)||"workstream",r=wt(e.name)||wt(e.prompt);return[n,r].filter(Boolean).join(" · ")}if(t==="stop"||t==="resume"||t==="info")return Nu(e);if(t==="peek")return[Nu(e),ZS(e)].filter(Boolean).join(" · ");if(t==="list"){const n=[];e.include_stored===!0&&n.push("stored");const r=wt(e.query);return r&&n.push(r),n.join(" · ")}return null}function Xj(e,t,n,r){const o=e.trim();if(o.toLowerCase()==="bridge")return lc(xs(t,n),t,r,n);if(!t)return o;if(o==="send")return jS(t)||o;if(o.toLowerCase()==="sessions"){const c=YS(t);if(c!==null)return c||o}const i=eE(o)?Object.entries(t).filter(([c])=>!em.has(c)):Object.entries(t);let a=i.filter(([c])=>AS.has(c)).map(([,c])=>wt(c)).filter(Boolean);if(a.length===0){const c=xS[o.toLowerCase()];a=i.map(([l,d])=>c?.[l]?.(d)||wt(d)).filter(Boolean)}return a.slice(0,2).join(" ")||o}function Qh(e){const t=e.trim();if(!t.toLowerCase().startsWith(Du))return t;const n=t.slice(Du.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function XS(e,t){return e===t||e===Qh(t)}const JS=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,QS="… ";function Jj(e,t=!1){if(!e||t)return null;for(const n of e.split(`
23
- `)){const r=n.trim();if(r&&!JS.test(r))return`${QS}${r.slice(0,160)}`}return null}function qh(e){const t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;if(t<3600){const o=Math.floor(t/60),i=t%60;return i===0?`${o}m`:`${o}m${i}s`}if(t<86400){const o=Math.floor(t/3600),i=Math.floor(t%3600/60);return i===0?`${o}h`:`${o}h${i}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 Qj(e){if(e===null)return"";const t=Math.max(0,e);return t<.05?"<0.1s":t<10?`${t.toFixed(1)}s`:t<60?`${Math.round(t)}s`:qh(t)}function Lu(e){const t=e*10,n=Math.floor(t),r=t-n;return((r>.5?n+1:r<.5||n%2===0?n:n+1)/10).toFixed(1)}function qj(e){const t={minimumFractionDigits:1,maximumFractionDigits:1};return e<1024?wo(e,"B",{maximumFractionDigits:0}):e<1024*1024?wo(Number(Lu(e/1024)),"KB",t):wo(Number(Lu(e/(1024*1024))),"MB",t)}function dc(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const Fu={read:"read",glob:"read",grep:"read",web_fetch:"read",web_read:"read",web_search:"read",browser:"read",lsp:"read",list_variables:"read",read_variable:"read",write:"mutate",edit:"mutate",bash:"exec",eval:"exec",console:"exec",task:"meta",agent:"meta",team:"meta",hub:"meta",todo:"meta",send:"meta",wake:"meta",ask:"meta",wait:"meta",jobs:"meta",secret:"meta",network:"meta",project:"meta",team_delete:"meta",project_delete:"meta",sessions:"meta",bridge:"meta"};function e$(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Fu,t)?Fu[t]:"plain"}function qS(e){if(!e)return"";for(const t of em){const n=e[t];if(typeof n=="string"&&n.trim()){const r=n.trim().toLowerCase(),o=e.remove,i=o===!0||o===1||typeof o=="string"&&RS.has(o.toLowerCase());return r==="milestone"&&i?"milestone-remove":t==="op"&&(r==="react"||r==="ack")?xs(e).action:r}}return""}const em=new Set(["op","action","method"]),eE=e=>Object.prototype.hasOwnProperty.call(tm,e.trim().toLowerCase()),Uu=({settled:e,running:t})=>({settled:g(e),running:g(t)}),tE={bash:{settled:"ui.chat.canonical.tool_row.verb.ran.settled",running:"ui.chat.canonical.tool_row.verb.ran.running"},eval:{settled:"ui.chat.canonical.tool_row.verb.ran_python.settled",running:"ui.chat.canonical.tool_row.verb.ran_python.running"},read:{settled:"ui.chat.canonical.tool_row.verb.read.settled",running:"ui.chat.canonical.tool_row.verb.read.running"},write:{settled:"ui.chat.canonical.tool_row.verb.wrote.settled",running:"ui.chat.canonical.tool_row.verb.wrote.running"},edit:{settled:"ui.chat.canonical.tool_row.verb.edited.settled",running:"ui.chat.canonical.tool_row.verb.edited.running"},glob:{settled:"ui.chat.canonical.tool_row.verb.listed.settled",running:"ui.chat.canonical.tool_row.verb.listed.running"},grep:{settled:"ui.chat.canonical.tool_row.verb.searched.settled",running:"ui.chat.canonical.tool_row.verb.searched.running"},web_search:{settled:"ui.chat.canonical.tool_row.verb.searched_the_web.settled",running:"ui.chat.canonical.tool_row.verb.searched_the_web.running"},web_fetch:{settled:"ui.chat.canonical.tool_row.verb.fetched.settled",running:"ui.chat.canonical.tool_row.verb.fetched.running"},web_read:{settled:"ui.chat.canonical.tool_row.verb.read.settled",running:"ui.chat.canonical.tool_row.verb.read.running"},browser:{settled:"ui.chat.canonical.tool_row.verb.browsed.settled",running:"ui.chat.canonical.tool_row.verb.browsed.running"},list_variables:{settled:"ui.chat.canonical.tool_row.verb.listed_variables.settled",running:"ui.chat.canonical.tool_row.verb.listed_variables.running"},read_variable:{settled:"ui.chat.canonical.tool_row.verb.read_variable.settled",running:"ui.chat.canonical.tool_row.verb.read_variable.running"},ask:{settled:"ui.chat.canonical.tool_row.verb.asked.settled",running:"ui.chat.canonical.tool_row.verb.asked.running"},send:{settled:"ui.chat.canonical.tool_row.verb.sent.settled",running:"ui.chat.canonical.tool_row.verb.sent.running"},wait:{settled:"ui.chat.canonical.tool_row.verb.waited_for_jobs.settled",running:"ui.chat.canonical.tool_row.verb.waited_for_jobs.running"},team_delete:{settled:"ui.chat.canonical.tool_row.verb.deleted_team.settled",running:"ui.chat.canonical.tool_row.verb.deleted_team.running"},project_delete:{settled:"ui.chat.canonical.tool_row.verb.deleted_project.settled",running:"ui.chat.canonical.tool_row.verb.deleted_project.running"},peer:{settled:"ui.chat.canonical.tool_row.verb.received.settled",running:"ui.chat.canonical.tool_row.verb.received.running"},task:{settled:"ui.chat.canonical.tool_row.verb.delegated.settled",running:"ui.chat.canonical.tool_row.verb.delegated.running"}},tm={agent:{list:{settled:"ui.chat.canonical.tool_row.verb.listed_agents.settled",running:"ui.chat.canonical.tool_row.verb.listed_agents.running"},show:{settled:"ui.chat.canonical.tool_row.verb.viewed_agent.settled",running:"ui.chat.canonical.tool_row.verb.viewed_agent.running"},search:{settled:"ui.chat.canonical.tool_row.verb.searched_agents.settled",running:"ui.chat.canonical.tool_row.verb.searched_agents.running"},install:{settled:"ui.chat.canonical.tool_row.verb.installed_agent.settled",running:"ui.chat.canonical.tool_row.verb.installed_agent.running"},reset:{settled:"ui.chat.canonical.tool_row.verb.reset_agent.settled",running:"ui.chat.canonical.tool_row.verb.reset_agent.running"},create:{settled:"ui.chat.canonical.tool_row.verb.created_agent.settled",running:"ui.chat.canonical.tool_row.verb.created_agent.running"},update:{settled:"ui.chat.canonical.tool_row.verb.updated_agent.settled",running:"ui.chat.canonical.tool_row.verb.updated_agent.running"},sync:{settled:"ui.chat.canonical.tool_row.verb.synced_agents.settled",running:"ui.chat.canonical.tool_row.verb.synced_agents.running"}},team:{list:{settled:"ui.chat.canonical.tool_row.verb.listed_teams.settled",running:"ui.chat.canonical.tool_row.verb.listed_teams.running"},show:{settled:"ui.chat.canonical.tool_row.verb.viewed_team.settled",running:"ui.chat.canonical.tool_row.verb.viewed_team.running"},create:{settled:"ui.chat.canonical.tool_row.verb.created_team.settled",running:"ui.chat.canonical.tool_row.verb.created_team.running"},update:{settled:"ui.chat.canonical.tool_row.verb.updated_team.settled",running:"ui.chat.canonical.tool_row.verb.updated_team.running"}},hub:{list:{settled:"ui.chat.canonical.tool_row.verb.listed_subagents.settled",running:"ui.chat.canonical.tool_row.verb.listed_subagents.running"},peek:{settled:"ui.chat.canonical.tool_row.verb.peeked_at.settled",running:"ui.chat.canonical.tool_row.verb.peeked_at.running"},send:{settled:"ui.chat.canonical.tool_row.verb.messaged.settled",running:"ui.chat.canonical.tool_row.verb.messaged.running"},ask:{settled:"ui.chat.canonical.tool_row.verb.asked.settled",running:"ui.chat.canonical.tool_row.verb.asked.running"},steer:{settled:"ui.chat.canonical.tool_row.verb.steered.settled",running:"ui.chat.canonical.tool_row.verb.steered.running"},pause:{settled:"ui.chat.canonical.tool_row.verb.paused.settled",running:"ui.chat.canonical.tool_row.verb.paused.running"},cancel:{settled:"ui.chat.canonical.tool_row.verb.cancelled.settled",running:"ui.chat.canonical.tool_row.verb.cancelled.running"},resume:{settled:"ui.chat.canonical.tool_row.verb.resumed.settled",running:"ui.chat.canonical.tool_row.verb.resumed.running"}},secret:{store:{settled:"ui.chat.canonical.tool_row.verb.stored_secret.settled",running:"ui.chat.canonical.tool_row.verb.stored_secret.running"},retrieve:{settled:"ui.chat.canonical.tool_row.verb.retrieved_secret.settled",running:"ui.chat.canonical.tool_row.verb.retrieved_secret.running"},list:{settled:"ui.chat.canonical.tool_row.verb.listed_secrets.settled",running:"ui.chat.canonical.tool_row.verb.listed_secrets.running"},describe:{settled:"ui.chat.canonical.tool_row.verb.described_secret.settled",running:"ui.chat.canonical.tool_row.verb.described_secret.running"},update:{settled:"ui.chat.canonical.tool_row.verb.updated_secret.settled",running:"ui.chat.canonical.tool_row.verb.updated_secret.running"},delete:{settled:"ui.chat.canonical.tool_row.verb.deleted_secret.settled",running:"ui.chat.canonical.tool_row.verb.deleted_secret.running"}},project:{list:{settled:"ui.chat.canonical.tool_row.verb.listed_projects.settled",running:"ui.chat.canonical.tool_row.verb.listed_projects.running"},show:{settled:"ui.chat.canonical.tool_row.verb.viewed_project.settled",running:"ui.chat.canonical.tool_row.verb.viewed_project.running"},create:{settled:"ui.chat.canonical.tool_row.verb.created_project.settled",running:"ui.chat.canonical.tool_row.verb.created_project.running"},update:{settled:"ui.chat.canonical.tool_row.verb.updated_project.settled",running:"ui.chat.canonical.tool_row.verb.updated_project.running"},link:{settled:"ui.chat.canonical.tool_row.verb.linked_session_to.settled",running:"ui.chat.canonical.tool_row.verb.linked_session_to.running"},unlink:{settled:"ui.chat.canonical.tool_row.verb.unlinked_session_from.settled",running:"ui.chat.canonical.tool_row.verb.unlinked_session_from.running"},milestone:{settled:"ui.chat.canonical.tool_row.verb.updated_milestone.settled",running:"ui.chat.canonical.tool_row.verb.updated_milestone.running"},"milestone-remove":{settled:"ui.chat.canonical.tool_row.verb.removed_milestone.settled",running:"ui.chat.canonical.tool_row.verb.removed_milestone.running"}},todo:{view:{settled:"ui.chat.canonical.tool_row.verb.read_todos.settled",running:"ui.chat.canonical.tool_row.verb.read_todos.running"},init:{settled:"ui.chat.canonical.tool_row.verb.updated_todos.settled",running:"ui.chat.canonical.tool_row.verb.updated_todos.running"},add:{settled:"ui.chat.canonical.tool_row.verb.updated_todos.settled",running:"ui.chat.canonical.tool_row.verb.updated_todos.running"},done:{settled:"ui.chat.canonical.tool_row.verb.updated_todos.settled",running:"ui.chat.canonical.tool_row.verb.updated_todos.running"},block:{settled:"ui.chat.canonical.tool_row.verb.updated_todos.settled",running:"ui.chat.canonical.tool_row.verb.updated_todos.running"},drop:{settled:"ui.chat.canonical.tool_row.verb.updated_todos.settled",running:"ui.chat.canonical.tool_row.verb.updated_todos.running"}},wake:{create:{settled:"ui.chat.canonical.tool_row.verb.scheduled.settled",running:"ui.chat.canonical.tool_row.verb.scheduled.running"},list:{settled:"ui.chat.canonical.tool_row.verb.listed_wakes.settled",running:"ui.chat.canonical.tool_row.verb.listed_wakes.running"},cancel:{settled:"ui.chat.canonical.tool_row.verb.cancelled_wake.settled",running:"ui.chat.canonical.tool_row.verb.cancelled_wake.running"}},jobs:{list:{settled:"ui.chat.canonical.tool_row.verb.listed_jobs.settled",running:"ui.chat.canonical.tool_row.verb.listed_jobs.running"},peek:{settled:"ui.chat.canonical.tool_row.verb.peeked_at.settled",running:"ui.chat.canonical.tool_row.verb.peeked_at.running"},cancel:{settled:"ui.chat.canonical.tool_row.verb.cancelled_job.settled",running:"ui.chat.canonical.tool_row.verb.cancelled_job.running"}},network:{status:{settled:"ui.chat.canonical.tool_row.verb.checked_network_status.settled",running:"ui.chat.canonical.tool_row.verb.checked_network_status.running"},ls:{settled:"ui.chat.canonical.tool_row.verb.listed_networks.settled",running:"ui.chat.canonical.tool_row.verb.listed_networks.running"},show:{settled:"ui.chat.canonical.tool_row.verb.viewed_network.settled",running:"ui.chat.canonical.tool_row.verb.viewed_network.running"},peers:{settled:"ui.chat.canonical.tool_row.verb.listed_network_peers.settled",running:"ui.chat.canonical.tool_row.verb.listed_network_peers.running"},log:{settled:"ui.chat.canonical.tool_row.verb.read_network_log.settled",running:"ui.chat.canonical.tool_row.verb.read_network_log.running"},doctor:{settled:"ui.chat.canonical.tool_row.verb.diagnosed_network.settled",running:"ui.chat.canonical.tool_row.verb.diagnosed_network.running"},init:{settled:"ui.chat.canonical.tool_row.verb.created_network.settled",running:"ui.chat.canonical.tool_row.verb.created_network.running"},invite:{settled:"ui.chat.canonical.tool_row.verb.invited_device.settled",running:"ui.chat.canonical.tool_row.verb.invited_device.running"},join:{settled:"ui.chat.canonical.tool_row.verb.joined_network.settled",running:"ui.chat.canonical.tool_row.verb.joined_network.running"},member_rm:{settled:"ui.chat.canonical.tool_row.verb.removed_device.settled",running:"ui.chat.canonical.tool_row.verb.removed_device.running"},disconnect:{settled:"ui.chat.canonical.tool_row.verb.left_network.settled",running:"ui.chat.canonical.tool_row.verb.left_network.running"},panic:{settled:"ui.chat.canonical.tool_row.verb.raised_panic.settled",running:"ui.chat.canonical.tool_row.verb.raised_panic.running"}},console:{list:{settled:"ui.chat.canonical.tool_row.verb.listed_consoles.settled",running:"ui.chat.canonical.tool_row.verb.listed_consoles.running"},create:{settled:"ui.chat.canonical.tool_row.verb.opened_console.settled",running:"ui.chat.canonical.tool_row.verb.opened_console.running"},status:{settled:"ui.chat.canonical.tool_row.verb.checked_console.settled",running:"ui.chat.canonical.tool_row.verb.checked_console.running"},read:{settled:"ui.chat.canonical.tool_row.verb.read_console.settled",running:"ui.chat.canonical.tool_row.verb.read_console.running"},screenshot:{settled:"ui.chat.canonical.tool_row.verb.captured_console.settled",running:"ui.chat.canonical.tool_row.verb.captured_console.running"},input:{settled:"ui.chat.canonical.tool_row.verb.typed_in_console.settled",running:"ui.chat.canonical.tool_row.verb.typed_in_console.running"},keys:{settled:"ui.chat.canonical.tool_row.verb.sent_keys.settled",running:"ui.chat.canonical.tool_row.verb.sent_keys.running"},resize:{settled:"ui.chat.canonical.tool_row.verb.resized_console.settled",running:"ui.chat.canonical.tool_row.verb.resized_console.running"},secure:{settled:"ui.chat.canonical.tool_row.verb.updated_secure_input.settled",running:"ui.chat.canonical.tool_row.verb.updated_secure_input.running"},close:{settled:"ui.chat.canonical.tool_row.verb.closed_console.settled",running:"ui.chat.canonical.tool_row.verb.closed_console.running"}},lsp:{definitions:{settled:"ui.chat.canonical.tool_row.verb.found_definition.settled",running:"ui.chat.canonical.tool_row.verb.found_definition.running"},references:{settled:"ui.chat.canonical.tool_row.verb.found_references.settled",running:"ui.chat.canonical.tool_row.verb.found_references.running"},symbols:{settled:"ui.chat.canonical.tool_row.verb.listed_symbols.settled",running:"ui.chat.canonical.tool_row.verb.listed_symbols.running"},rename_preview:{settled:"ui.chat.canonical.tool_row.verb.previewed_rename.settled",running:"ui.chat.canonical.tool_row.verb.previewed_rename.running"}},sessions:{list:{settled:"ui.chat.canonical.tool_row.verb.listed_sessions.settled",running:"ui.chat.canonical.tool_row.verb.listed_sessions.running"},info:{settled:"ui.chat.canonical.tool_row.verb.viewed_session.settled",running:"ui.chat.canonical.tool_row.verb.viewed_session.running"},spawn:{settled:"ui.chat.canonical.tool_row.verb.spawned_session.settled",running:"ui.chat.canonical.tool_row.verb.spawned_session.running"},resume:{settled:"ui.chat.canonical.tool_row.verb.resumed_session.settled",running:"ui.chat.canonical.tool_row.verb.resumed_session.running"},stop:{settled:"ui.chat.canonical.tool_row.verb.stopped_session.settled",running:"ui.chat.canonical.tool_row.verb.stopped_session.running"},peek:{settled:"ui.chat.canonical.tool_row.verb.peeked_at_session.settled",running:"ui.chat.canonical.tool_row.verb.peeked_at_session.running"}}};function nE(e,t){const n=e.trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(n==="bridge"){const{settled:a,running:c}=cc(r);return{settled:a,running:c,named:!0}}const o=r?tm[n]?.[r]:void 0;if(o)return{...Uu(o),named:!0};const i=tE[n];return i?{...Uu(i),named:!0}:{settled:g("ui.chat.canonical.tool_row.generic_verb.settled"),running:g("ui.chat.canonical.tool_row.generic_verb.running"),named:!1}}function t$(e,t,n,r,o="",i=null){const a=nE(e,o),c=XS(t,e)?n??"":t;return{verb:r?a.running:i??a.settled,object:a.named?c:[Qh(e),c].filter(Boolean).join(" ")}}const rE=new Set(["write","edit"]);function nm(e){return rE.has(e.trim().toLowerCase())}function n$(e){return nm(e.toolName)&&e.diff!==null&&!e.isError}function r$(e){return nm(e.toolName)&&!e.isError&&(e.diff===null||e.diff.length===0)&&e.diffFull!==null&&e.diffFull!==void 0}function rm(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 oE(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 om(e,t){return e===null||oE(e,t)?t:e}function im(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:dc(n.added),removed:dc(n.removed)}}function sm(e,t){return!e||typeof e!="object"?t:dc(e.diff_truncated_rows)}function iE(e){return e.length>=2&&$r(e[0])==="---"&&$r(e[1])==="+++"?e.slice(2):e.slice()}const sE=/\s+$/;function $r(e){return e.replace(sE,"")}function am(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const Bu=40,aE="[output withheld: credential redaction requires a complete bounded diff]";function cE(e){return e.length===0||$r(e[0])!==aE?!1:e.slice(1).every(t=>$r(t)===""||$r(t)==="…")}function o$(e,t={}){const n=iE(e);if(cE(n))return{lines:[],hidden:0,expandable:!1,withheld:!0};const r=n.length>Bu,o=t.expanded?n:n.slice(0,Bu);return{lines:o.map(i=>{const a=$r(i);return{text:a,marker:a.slice(0,1),kind:am(a)}}),hidden:n.length-o.length,expandable:r,withheld:!1}}function i$(e){return g("ui.chat.canonical.tool_row.diff.more",{count:e})}function s$(){return g("ui.chat.canonical.tool_row.diff.show_less")}function a$(e){return g("ui.chat.canonical.tool_row.diff.truncated",{count:e})}function c$(){return g("ui.chat.canonical.tool_row.diff.withheld")}const uc=/\s+$/u,lE=new Set(["oversized","withheld","unavailable"]);function cm(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;if(t.v!==1)return{state:"unavailable"};if(t.state==="archived"){const n=t.rows;return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0?{state:"archived",rows:n}:{state:"unavailable"}}return typeof t.state=="string"&&lE.has(t.state)?{state:t.state}:{state:"unavailable"}}function lm(e,t){return!e||typeof e!="object"?t:cm(e.diff_full)}const zo="tool_call_diff_binding_v1",dE=new Set(["custom_type","details"]),uE=new Set(["v","session_id","outer_call_id","call_id","tool","diff_full"]),fE=new Set(["v","state","rows","digest"]),pE=256;function Hu(e){return typeof e=="string"&&e.length>0&&e.length<=pE&&e.trim()===e}function ha(e,t){return Object.keys(e).every(n=>t.has(n))}function _l(e,t){if(!t||!e||typeof e!="object"||Array.isArray(e))return null;const n=e;if(n.custom_type!==zo||!ha(n,dE))return null;const r=n.details;if(!r||typeof r!="object"||Array.isArray(r))return null;const o=r;if(!ha(o,uE)||o.v!==1||o.session_id!==t)return null;const i=o.outer_call_id,a=o.call_id;if(!Hu(i)||!Hu(a)||!a.startsWith(`${i}:`)||a.length===i.length+1)return null;const c=o.tool;if(c!=="write"&&c!=="edit")return null;const l=o.diff_full;if(!l||typeof l!="object"||Array.isArray(l))return null;const d=l;if(!ha(d,fE)||d.v!==1||typeof d.state!="string"||!d.state||"rows"in d&&!(typeof d.rows=="number"&&Number.isSafeInteger(d.rows)&&d.rows>=0)||"digest"in d&&typeof d.digest!="string")return null;const u=cm(d);return u?{callId:a,outerCallId:i,tool:c,descriptor:u}:null}const bl=new WeakSet;function hE(e){return!!e&&typeof e=="object"&&bl.has(e)}function dm(e){return e.type==="custom"&&!!e.payload&&typeof e.payload=="object"&&e.payload.custom_type===zo}function mE(e,t){let n=0;for(const r of e)dm(r)&&_l(r.payload,t)!==null&&(bl.add(r.payload),n+=1);return n}function l$(e,t){const n=[];for(const r of e){if(!dm(r))continue;const o=_l(r.payload,t);o&&n.push({payload:r.payload,binding:o})}return n}function d$(e,t){return t===null||t==="not_found"?!1:(bl.add(e),!0)}const gE=new Set(["archived","oversized","withheld","unavailable","evicted","not_recorded","inline"]);function _E(e,t){return e.start!==t.start?e.start-t.start:e.offset-t.offset}function bE(e){return e.nextStart===null||e.nextOffset===null?null:{start:e.nextStart,offset:e.nextOffset}}function br(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:null}function u$(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e;if(typeof n.state!="string"||!gE.has(n.state))return null;const r=br(n.start),o=br(n.total_rows);if(r===null||o===null||!Array.isArray(n.rows)||!n.rows.every(_=>typeof _=="string"))return null;const i=n.rows;if(i.length>Ho||r+i.length>o&&i.length>0)return null;const a=n.offset===void 0?0:br(n.offset);if(a===null)return null;const c=n.next_start??null,l=n.next_offset===void 0&&c!==null?0:n.next_offset??null;let d=null,u=null;if((c!==null||l!==null)&&(d=br(c),u=br(l),d===null||u===null||d>o))return null;if(n.state==="archived"){if(t&&(r!==t.start||a!==t.offset)||a>0&&i.length===0)return null;if(d===null){if(r+i.length!==o)return null}else if(u===0){if(i.length===0||d!==r+i.length)return null}else if(i.length===0||d!==r+i.length-1||i.length===1&&u<=a)return null}else if(d!==null)return null;const f=typeof n.hunk_header=="string"?n.hunk_header:null,h=Array.isArray(n.clipped_rows)?n.clipped_rows.filter(_=>br(_)!==null&&_>=r&&_<r+i.length):[];return{state:n.state,start:r,offset:a,totalRows:o,rows:i,hunkHeader:f,nextStart:d,nextOffset:u,clippedRows:h}}function f$(e){const t=e.start===0&&e.offset===0?vE(e.rows):0,n=new Set(e.clippedRows),r=e.rows.length-1,o=e.rows.slice(t).map((c,l)=>{const d=l+t,u=e.start+d,f=d===r&&(e.nextOffset??0)>0,h=f?c:c.replace(uc,"");return{index:u,text:h,kind:am(h),clipped:n.has(u),continued:d===0&&e.offset>0,continues:f}}),i=o[0],a=e.hunkHeader&&i&&i.kind!=="hunk"?e.hunkHeader:null;return{lines:o,hunkHeader:a}}function p$(e){return Math.max(0,e-Ho)}function h$(e){return Math.max(0,e-Ho)}function vE(e){return e[0]?.replace(uc,"")==="---"&&e[1]?.replace(uc,"")==="+++"?2:0}function m$(e,t){const n=Math.max(e.start,t)-t+1,r=e.start+e.rows.length-t;return{first:n,last:r,total:Math.max(0,e.totalRows-t)}}function g$(e,t){const n=bE(e);if(n&&_E(n,t)<=0)return e;const r=t.start-e.start;return r<=0?e:{...e,rows:e.rows.slice(0,r),nextStart:t.start,nextOffset:0,clippedRows:e.clippedRows.filter(o=>o<t.start)}}function _$(e){return g("ui.chat.canonical.tool_row.diff.full.view",{count:e})}function b$(){return g("ui.chat.canonical.tool_row.diff.full.back")}function v$(e,t,n){return g("ui.chat.canonical.tool_row.diff.full.range",{first:e,last:t,total:n})}function y$(){return g("ui.chat.canonical.tool_row.diff.full.nav")}function w$(){return g("ui.chat.canonical.tool_row.diff.full.first")}function k$(){return g("ui.chat.canonical.tool_row.diff.full.prev")}function S$(){return g("ui.chat.canonical.tool_row.diff.full.next")}function E$(){return g("ui.chat.canonical.tool_row.diff.full.last")}function I$(){return g("ui.chat.canonical.tool_row.diff.full.loading")}function A$(){return g("ui.chat.canonical.tool_row.diff.full.error")}function R$(){return g("ui.chat.canonical.tool_row.diff.full.retry")}function x$(){return g("ui.chat.canonical.tool_row.diff.full.empty")}function T$(e){return g("ui.chat.canonical.tool_row.diff.full.clipped",{count:e})}function C$(){return g("ui.chat.canonical.tool_row.diff.full.clipped_row")}function O$(){return g("ui.chat.canonical.tool_row.diff.full.continued")}function P$(){return g("ui.chat.canonical.tool_row.diff.full.continues")}function M$(e){switch(e){case"oversized":return g("ui.chat.canonical.tool_row.diff.full.oversized");case"withheld":return g("ui.chat.canonical.tool_row.diff.full.withheld");case"unavailable":return g("ui.chat.canonical.tool_row.diff.full.unavailable");case"evicted":return g("ui.chat.canonical.tool_row.diff.full.evicted");case"not_recorded":return g("ui.chat.canonical.tool_row.diff.full.not_recorded");case"inline":return g("ui.chat.canonical.tool_row.diff.full.inline");case"not_found":return g("ui.chat.canonical.tool_row.diff.full.not_found")}}const um="profile_save",yE="profile_revert",vl=["agent","team"],wE=["create","update","revert"],kE={agent:["label","description","tags","categories","model","instructions"],team:["label","description","manager","members","aliases","instructions","project"]},fc=s.string().max(1e5),In=e=>s.string().max(e),xn=s.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/),Ko=s.string().regex(/^sha256:[0-9a-f]{64}$/),Wu=s.union([s.string().max(1e5),s.array(s.string().max(512)).max(128),s.array(s.record(s.string(),s.unknown())).max(64),s.null()]);s.object({id:xn,name:s.string().min(1).max(128),label:In(256),description:In(16e3),tags:s.array(In(512)).max(128),categories:s.array(In(128)).max(32),model:In(512).nullable(),instructions:fc}).strict();s.object({id:xn,name:s.string().min(1).max(128),label:In(256),description:In(16e3),manager:s.string().min(1).max(128),members:s.array(s.object({role:s.string().min(1).max(128),count:s.number().int().min(1).max(16).optional(),kind:s.enum(["agent","team"]).optional(),tier:s.enum(["lo","med","hi"]).nullable().optional(),effort:s.string().max(64).nullable().optional(),saver:s.boolean().nullable().optional()}).strict()).max(64),aliases:s.array(In(128)).max(32),instructions:fc,project:fc}).strict();const fm=s.object({version:s.literal(1),operation:s.literal(um),approval_id:s.string().min(1).max(64),profile_kind:s.enum(vl),scope:s.literal("global"),profile_operation:s.enum(wE),target_id:xn,profile_name:s.string().min(1).max(128),session_id:xn,tool_call_id:xn,receipt_id:xn,changed_fields:s.array(s.string().max(64)).max(32),before:s.record(s.string(),Wu).nullable(),after:s.record(s.string(),Wu),base_commitment:Ko,after_commitment:Ko,expires_at:s.number().finite(),signing_principal:s.string().min(1).max(160)}).strict(),SE=s.object({action:s.string().min(1).max(64),operation:s.literal(um),request_digest:Ko,assurance:s.string().max(64).optional(),unproven_human:s.boolean().optional(),disclosure:fm.nullable().optional(),disclosure_digest:Ko.optional(),signable_here:s.boolean(),refusal:s.string().max(64).optional(),refusal_message:s.string().max(2e3).optional(),apply_outcome:s.object({code:s.string().max(64),retryable:s.boolean(),reason:s.string().max(2e3),remedy:s.string().max(2e3)}).strict().nullable().optional(),upgrade:s.object({available:s.boolean(),helper:s.string().max(64)}).strict().optional()}).strict(),EE=["queued","applied","proposed"],IE=s.object({status:s.enum(EE),proposal_id:s.string().regex(/^pp_[a-f0-9]{16}$/).optional(),approval_id:s.string().min(1).max(64).optional(),request_digest:Ko.optional(),expires_at:s.number().finite().optional(),receipt_id:xn.optional(),profile_kind:s.enum(vl),profile_name:s.string().min(1).max(128),scope:s.literal("global"),fields:s.array(s.string().max(64)).max(32).optional(),diff:s.array(s.string().max(2e3)).max(64).optional(),profile_action:s.unknown().optional(),revert:s.unknown().optional()}).strict(),AE=s.object({kind:s.string().max(64).optional(),name:s.string().min(1).max(128),scope:s.literal("global"),fields:s.array(s.string().max(64)).max(32).optional(),diff:s.array(s.string().max(2e3)).max(64).optional(),backup_id:s.string().max(160).optional(),revision:s.string().max(200).optional(),authorized_by:s.string().max(160).optional(),class:s.string().max(64).optional(),profile_action:s.unknown().optional(),revert:s.unknown().optional()}).strict();function RE(e){const t=AE.safeParse(e);return t.success?t.data:null}const pm=s.object({schema:s.literal(1),kind:s.literal(yE),action_id:s.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),label:s.string().min(1).max(64),profile_kind:s.enum(vl),profile_name:s.string().min(1).max(128),receipt_id:xn}).strict();function xE(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:"",i=typeof e.effort=="string"?e.effort:"",a=e.saver===!0?"saver":e.saver===!1?"saver off":"",c=[r==="team"?"team":"",o,i,a].filter(d=>d!==""),l=n>1?` x${n}`:"";return c.length?`${t}${l} (${c.join(", ")})`:`${t}${l}`}function TE(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:typeof t=="object"&&t!==null?xE(t):"").filter(t=>t!=="").join(", "):""}function Gu(e,t){return e===null?{presence:"absent",text:""}:Object.prototype.hasOwnProperty.call(e,t)?e[t]===null?{presence:"unset",text:""}:{presence:"set",text:TE(e[t])}:{presence:"absent",text:""}}function j$(e){const t=kE[e.profile_kind],n=[];for(const r of e.changed_fields){if(!t.includes(r))continue;const o=Gu(e.before,r),i=Gu(e.after,r);if(o.presence==="set"&&i.presence==="set"){if(o.text===i.text)continue}else if(o.presence===i.presence&&o.presence==="absent")continue;n.push({field:r,before:o,after:i})}return n}function $$(e){const t=pm.safeParse(e.descriptor);if(!e.descriptorVerified||!t.success)return{state:"unavailable",enabled:!1};if(e.alreadyAnswered)return{state:"saved",enabled:!1};if(e.outcome){const n=(e.outcome.state??"").toLowerCase();return n==="unconfirmed"||n==="pending"?{state:"unconfirmed",enabled:!1}:n==="expired"||n==="stale"?{state:"stale",enabled:!1}:e.outcome.approved===!1?{state:"failed",enabled:!1}:{state:"saved",enabled:!1}}return e.submitted?{state:"pending",enabled:!1}:e.reconstructed?{state:"unavailable",enabled:!1}:{state:"available",enabled:!0}}function CE(e){const t=fm.safeParse(e);return t.success?t.data:null}function D$(e){const t=SE.safeParse(e);return t.success?t.data:null}function Dr(e){const t=IE.safeParse(e);return t.success?t.data:null}function OE(e){const t=pm.safeParse(e);return t.success?t.data:null}const PE=new Set(["agent","team"]),ME=1048576;function yl(e,t){if(!PE.has(e)||!t||typeof t!="object"||Array.isArray(t))return null;try{const n=JSON.stringify(t);if(new TextEncoder().encode(n).byteLength>ME)return null}catch{return null}return!RE(t)&&!Dr(t)&&!CE(t)?null:t}function hm(e,t,n){return yl(e,t)??Xh(t,n)}const jE=`Continue working toward this goal:
25
-
26
- `,$E=`
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.`,DE=`Work toward this goal:
29
-
30
- {goal}
31
-
32
- Make concrete progress with the tools available, then briefly state what advanced and what remains. If the goal is already fully met, say so plainly.`,[NE="",LE=""]=DE.split("{goal}"),FE="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.",UE="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.",BE="Harness recovery notice: the last three tool batches repeated the same arguments and errors. Inspect the error and change approach; do not repeat the unchanged failing calls. If an external condition must change, use a supported wait operation or explain the blocker.";function mm(e){const t=e.trim();return t===FE||t===UE||t===BE||t.startsWith(jE)&&t.endsWith($E)||t.startsWith(NE.trim())&&t.endsWith(LE.trim())}const HE=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function WE(e,t){const n=t?.match(HE)?.[0]??null;if(!e||typeof e!="object")return n;const r=e,o=r.cost_usd,i=r.billing_basis;if(typeof o!="number"||!Number.isFinite(o)||o<0)return n;if(i!=="billed"&&i!=="estimated")return null;const a=Number(o.toFixed(4));return`Cost ${a===0&&o>0?"<$0.0001":`$${a}`} (${i}).`}const Si=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function GE(e){if(!Si(e)||e.material!=="music"||!Array.isArray(e.tracks))return;const t=Array.isArray(e.artifacts)?e.artifacts.filter(Si):[];return{...typeof e.job=="string"&&e.job.length>0?{job:e.job}:{},attribution:typeof e.attribution=="string"?e.attribution:"",tracks:e.tracks.filter(Si).filter(n=>typeof n.id=="string"&&n.id.length>0).map(n=>({id:n.id,title:typeof n.title=="string"?n.title:"",variantIndex:typeof n.variant_index=="number"?n.variant_index:0,error:typeof n.error_type=="string"||typeof n.registration_error=="string",cost:Si(n.cost)?n.cost:null,images:t.filter(r=>r.track_id===n.id&&typeof r.digest=="string"&&/^[a-f0-9]{32}$/.test(r.digest)).map(r=>({id:`music:${n.id}:${r.artifact_id}:${r.role}`,attachment:r.digest,data:null,mimeType:typeof r.content_type=="string"?r.content_type:"audio/mpeg",kind:"audio",...typeof r.name=="string"?{name:r.name}:{},...typeof r.size_bytes=="number"?{sizeBytes:r.size_bytes}:{},...typeof r.duration_s=="number"?{durationS:r.duration_s}:{}}))}))}}function Cs(e){switch(e.id){case"interrupted":return g("ui.chat.canonical.notice.interrupted");case"stopped_with_error":return g("ui.chat.canonical.notice.stopped_with_error");case"compaction_not_run":return e.sentence.includes(":")?g("ui.chat.canonical.notice.compaction_not_run_after_colon",{detail:e.sentence}):g("ui.chat.canonical.notice.compaction_not_run",{detail:e.sentence})}}function N$(e){return e.copy?Cs(e.copy):e.text}function kr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}const zE=32,KE=32*1024,VE=256*1024;function ZE(e,t,n=[]){const r=new Map(e.filter(_=>_.type==="message").map(_=>[_.id,_])),o=new Map,i=new Map,a=new Map,c=new Set(n.filter(_=>_.conflict).map(_=>_.entry.payload.target));for(const _ of[...n.map(y=>y.entry),...e]){if(_.type!=="prune"||!kr(_.payload))continue;const{target:y,replacement:v}=_.payload;if(typeof y!="string"||!Number.isFinite(_.ts)||!kr(v)||v.kind!=="message"||v.role!=="tool"||!Array.isArray(v.content)||!kr(v.provider_payload)||Object.keys(v).some(W=>!["kind","role","content","tool_call_id","tool_name","provider_payload"].includes(W))||v.content.length===0||v.content.some(W=>!kr(W)||typeof W.text!="string"||W.text.length>1e5||W.type!==void 0&&W.type!=="text"))continue;const b=v.tool_name;if(typeof b!="string"||typeof v.tool_call_id!="string"||v.tool_call_id.length===0)continue;const p=yl(b,v.provider_payload.details),A=Dr(p),k=OE(A?.profile_action);if(!A||A.status!=="applied"||A.profile_kind!==b||!k||k.receipt_id!==A.receipt_id||k.profile_kind!==A.profile_kind||k.profile_name!==A.profile_name)continue;const M=a.get(y),P=c.has(y)||!!(M&&JSON.stringify(M.entry.payload.replacement)!==JSON.stringify(v));a.set(y,{entry:M?.entry??_,...P||M?.conflict?{conflict:!0}:{}})}const l=[];let d=2;const u=_=>{if(new TextEncoder().encode(JSON.stringify(_.entry)).length>KE)return;const y=new TextEncoder().encode(JSON.stringify(_)).length+(l.length?1:0);l.length<zE&&d+y<=VE&&(l.push(_),d+=y)};for(const _ of a.values()){const{entry:y}=_,{target:v,replacement:b}=y.payload,p=b.tool_name,A=Dr(b.provider_payload.details);if(!A)continue;const k=r.get(v),M=k?void 0:t.find(N=>N.kind==="tool"&&N.sourceEntryId===v);if(_.conflict||!k&&(!M||M.kind!=="tool")){u(_);continue}const P=k?.payload,W=P&&kr(P.provider_payload)?P.provider_payload.details:M?.kind==="tool"?M.details:null,R=Dr(W),m=P?.tool_call_id??(M?.kind==="tool"?M.toolCallId:null),w=P?.tool_name??(M?.kind==="tool"?M.toolName:null),S=k?.ts??(M?M.ts/1e3:0);if(k&&(P?.role!=="tool"||k.type!=="message")||!R||w!==p||m!==b.tool_call_id||y.ts<S||!R.receipt_id||!R.approval_id||!R.request_digest||R.receipt_id!==A.receipt_id||R.approval_id!==A.approval_id||R.request_digest!==A.request_digest||R.profile_kind!==A.profile_kind||R.profile_name!==A.profile_name||R.scope!==A.scope)continue;const T=k?{...k,payload:b}:{id:v,type:"message",ts:S,payload:b,...M?.journalSeq!==void 0?{journal_seq:M.journalSeq}:{}};k?o.set(v,T):i.set(y.id,T)}const f=e.map(_=>o.get(_.id)??i.get(_.id)??_);for(const[_,y]of i)e.some(v=>v.id===_)||f.push(y);const h=n.length===l.length&&l.every((_,y)=>_.entry===n[y].entry&&_.conflict===n[y].conflict);return{entries:f,pending:h?n:l}}function YE(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||!kr(e.payload.provider_payload))return!1;const n=Dr(e.payload.provider_payload.details),r=Dr(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 gm(e){return e}const pc="supplement_v1",XE="superseded",as=120,wl=480,JE=20,L$=500,QE=10,qE=["outside","sensitive","missing","too-large"];function _m(e,t){const n=[];let r=0;if(Array.isArray(e))for(const i of e.slice(0,QE)){if(!i||typeof i!="object")continue;const a=i,c=a.reason;if(!qE.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 kl(e){return`supplement:${e}`}function eI(e){const t=e.payload??{};if(String(t.custom_type??"")!==pc)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?kl(r):null}function cs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function tI(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:cs(t.size_bytes)??0,mtime:cs(t.mtime)??0,why:typeof t.why=="string"?t.why:"",...t.pinned===!0?{pinned:!0}:{}}}function bm(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=tI(n);r&&t.push(r)}return t}function nI(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!wm(n))return null;const r=cs(t.height_hint);return{attachment:n,title:typeof t.title=="string"?t.title:"",source:typeof t.source=="string"?t.source:"",mime:typeof t.mime=="string"?t.mime:"text/html",heightHint:r===null?as:Math.min(wl,Math.max(as,Math.round(r)))}}function vm(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=nI(n);r&&t.push(r)}return t}function rI(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return wm(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:cs(t.duration_s),...t.origin==="file"?{origin:"file"}:{},...t.origin==="file"&&typeof t.path=="string"&&t.path?{path:t.path}:{},...t.pinned===!0?{pinned:!0}:{}}:null}function ym(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=rI(n);r&&t.push(r)}return t}const oI=/^[a-f0-9]{32}$/,iI=/\s+/;function wm(e){return typeof e=="string"&&oI.test(e)}const sI={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function zu(e){switch(e){case"decided":return 0;case"queued":return 1;case"running":return 2;case"cancelling":return 3;case"done":case"failed":case"cancelled":case"skipped":return 4;default:return 0}}function F$(e,t){const n=e.state;if(e.error===XE||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?sI[r]??r:r}const U$="Preparing highlights…",B$="Highlights cancelled",H$="Couldn't prepare highlights",W$="Adjust…",G$="Cancel",z$="Retry",aI=64,cI={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 K$(e){return typeof e=="string"&&e?cI[e]??"":""}function ma(e){return typeof e!="string"?"":e.replace(Dh,"").split(iI).filter(Boolean).join(" ")}function V$(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function lI(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return wo(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 wo(o,n,{maximumFractionDigits:1})}return""}function Z$(e){const t=ma(e.name)||ma(e.path),n=ma(e.path);return{name:t,path:n===t?"":n,size:lI(e.sizeBytes)}}function ga(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function Y$(e,t,n=e){return t?`Hide ${ga(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${ga(e,"graphic")}`:`Show ${ga(e,"graphic")}`}function X$(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const dI="supplement",uI=1,fI=["ready","resize","error","pong"],pI=["resize","error","pong"],hI=64,Sl=300,J$=5e3,Q$=2e4;function q$(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==dI||n.v!==uI)return null;const r=n.t;if(typeof r!="string"||!fI.includes(r))return null;const o=r;if(pI.includes(o)&&(!t||t.length>hI||n.n!==t))return null;if(o==="error"){const i=n.msg;if(typeof i!="string"||i.length>Sl)return null}if(o==="resize"){const i=n.h;if(typeof i!="number"||!Number.isFinite(i)||i<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 eD(){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 mI=["--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"],gI=120;function _I(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 mI){const i=t.getPropertyValue(o).trim();i&&(n[o]=i.slice(0,gI))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function tD(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(_I()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function nD(e){return`data:text/html;base64,${bI(e)}`}function bI(e){const t=vI(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let o=0;o<t.length;o+=3){const i=t[o]??0,a=t[o+1]??0,c=t[o+2]??0;r+=n[i>>2],r+=n[(i&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 vI(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 rD(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function yI(e){return Math.min(wl,Math.max(as,e.heightHint))}function wI(e){return Math.min(wl,Math.max(as,e))}function oD(e,t,n){let r=0;const o=[];for(let i=0;i<e.length;i+=1){const a=e[i],c=n?.get(a.attachment),l=c!==void 0?wI(c):yI(a);if(i>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 kI=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,km=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,SI=/kind=(auth|quota)\b/,EI=/kind=(transient|timeout)\b/;function Sm(e){const t=a=>typeof a=="string"&&kI.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"&&(km.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,i=typeof e.cause=="string"?e.cause.slice(0,aI):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...o?{detail:o}:{},...i?{cause:i}:{}}}function iD(e){if(!km.exec(e))return"";const n=e.split(" "),r=n[1].replace(":",""),o=n[3].slice(7),i=n[4].slice(5);return`Attempt ${r}: ${i}${o==="None"?"":` (HTTP ${o})`}`}function sD(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return SI.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":EI.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 II(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return Em(n)?{anchor:t,job:typeof e.job=="string"?e.job:"",version:typeof e.version=="number"&&Number.isInteger(e.version)?e.version:0,state:n,...n==="decided"||n==="done"?{files:bm(e.files),..."withheld"in e||"withheld_more"in e?_m(e.withheld,e.withheld_more):{}}:{},...n==="done"?{components:vm(e.components),sounds:ym(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Sl)}:{},...Sm(e),live:!Im(n)}:null}function AI(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!Em(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,JE):[];return{anchor:t,job:typeof e.job=="string"?e.job:"",version:typeof e.version=="number"&&Number.isInteger(e.version)?e.version:0,state:n,files:bm(e.files),filesMore:r,more:o,components:vm(e.components),sounds:ym(e.sounds),..._m(e.withheld,e.withheld_more),...Sm(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Sl)}:{}}}function Ku(e,t,n){const r=AI(t);if(!r)return null;const o=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return Am(o,r,e)}function Em(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Im(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function RI(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 xI(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 TI(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 CI(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 Am(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&zu(t.state)<zu(e.state)))return null;const r=!e||t.version>e.version,o=t.files!==void 0?t.files:e?.files??[],i=t.components!==void 0?t.components:e?.components??[],a=t.sounds!==void 0?t.sounds:e?.sounds??[],c=t.withheld!==void 0?t.withheld:e?.withheld??[],l=t.withheldMore!==void 0?t.withheldMore:e?.withheldMore??0,d=t.filesMore!==void 0?t.filesMore:e?.filesMore??0,u=t.more!==void 0?t.more:e?.more??[],f=t.error??(r?"":e?.error??""),h=t.cause??(r?"":e?.cause??""),_=t.dismissed??(r?!1:e?.dismissed??!1),y=t.live!==void 0?t.live===!0?!0:Im(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:kl(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:RI(o,e?.files??[])?e?.files??[]:o,filesMore:d,more:OI(u,e?.more??[])?e?.more??[]:u,components:xI(i,e?.components??[])?e?.components??[]:i,sounds:TI(a,e?.sounds??[])?e?.sounds??[]:a,withheld:CI(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:_,live:y}}function OI(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const aD=e=>e.kind===void 0||e.kind==="image",Ut={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function Rm(e){return e==="skipped"||e==="aborted"}function Vu(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Zu(e,t,n,r){return Vu(n.args)??(r?.kind==="tool"?r.args:null)??Vu(e.argsByCall.get(t)?.arguments)}function xm(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function Tm(e){if(!e)return null;const t=e.kind;return t!=="image"&&t!=="video"&&t!=="audio"?null:typeof e.content_type=="string"||typeof e.attachment=="string"||typeof e.source_url=="string"?t:null}function Ei(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Qt(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!xm(n)&&Tm(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Xn(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Nr;const o=[];for(const i of r){const a=Tm(i);if(i.type==="document"||a===null&&!xm(i))continue;const c={id:`${t}:${o.length}`,data:typeof i.data=="string"&&i.data?i.data:null,attachment:typeof i.attachment=="string"&&i.attachment?i.attachment:null,mimeType:typeof i.content_type=="string"&&i.content_type||typeof i.mime_type=="string"&&i.mime_type||"image/png"};a!==null&&(c.kind=a,c.width=Ei(i.width),c.height=Ei(i.height),c.sizeBytes=Ei(i.size_bytes),c.durationS=Ei(i.duration_s),c.name=typeof i.name=="string"&&i.name?i.name:null,c.sourceUrl=typeof i.source_url=="string"&&i.source_url?i.source_url:null),o.push(c)}return o.length===0?Nr:n&&El(n,o)?n:o}const Nr=[],hc=[];function Cm(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:hc;const o=[];for(const i of r){const a=typeof i.filename=="string"&&typeof i.mime_type=="string"&&typeof i.attachment=="string"&&i.type===void 0;i.type!=="document"&&!a||o.push({id:`${t}:doc:${o.length}`,attachment:typeof i.attachment=="string"&&i.attachment?i.attachment:null,filename:typeof i.filename=="string"&&i.filename?i.filename:i.name??"Attached file",mimeType:i.mime_type??"application/octet-stream",path:typeof i.path=="string"&&i.path?i.path:null,storedPath:typeof i.stored_path=="string"&&i.stored_path?i.stored_path:null,bytes:typeof i.bytes=="number"?i.bytes:0,...i.injection?{injection:i.injection}:{}})}return o.length===0?n?.length?n:hc:n&&PI(n,o)?n:o}function PI(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 Yu(e){let t=0;for(const n of e)n.kind!==void 0&&(t+=1),n.width!=null&&(t+=1),n.height!=null&&(t+=1),n.sizeBytes!=null&&(t+=1),n.durationS!=null&&(t+=1),n.name!=null&&(t+=1),n.sourceUrl!=null&&(t+=1);return t}function Om(e,t,n){if(t.length===0)return e;if(e.length===0||El(e,t))return t;const r=Yu(e),o=Yu(t);return r!==o?r>o?e:t:n==="incoming"?e:t}function MI(e,t){return Om(e,t,"incoming")}function El(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n].id!==t[n].id||e[n].data!==t[n].data||e[n].attachment!==t[n].attachment||e[n].mimeType!==t[n].mimeType||e[n].kind!==t[n].kind||e[n].width!==t[n].width||e[n].height!==t[n].height||e[n].sizeBytes!==t[n].sizeBytes||e[n].durationS!==t[n].durationS||e[n].name!==t[n].name||e[n].sourceUrl!==t[n].sourceUrl)return!1;return!0}function St(e){const t=new Map;return e.forEach((n,r)=>t.set(n.id,r)),t}function jI(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const vn=new Set;function Il(e){return e.kind==="user"&&e.provisional===!0}function Pm(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{Il(n)&&r<t&&(t=r)}),t}function Vo(e,t=vn,n){if(n?.journalMode)return Sh(n,e).map(gm);const r=e.map((a,c)=>({record:a,position:c})),o=Pm(e),i=a=>Il(a.record)||a.position>o&&!t.has(a.record.id);return r.sort((a,c)=>{const l=i(a),d=i(c);return l!==d?l?1:-1:l?a.position-c.position:a.record.ts!==c.record.ts?a.record.ts-c.record.ts:a.position-c.position}).map(a=>a.record)}function $I(e,t,n){if(!n||t<=0)return vn;let r=null;for(const o of e){if(!Il(o)||!(t>o.ts))continue;let i=!1,a=!1;for(const c of e)if(c.ts>o.ts?i=!0:c.ts<o.ts&&Tl(c)&&(a=!0),i&&a)break;i&&a&&(r??=new Set,r.add(o.id))}return r??vn}function DI(e){const{provisional:t,...n}=e;return n}function mc(e,t){const n=e,r=t,o=Object.keys(n);if(o.length!==Object.keys(r).length)return!1;for(const i of o)if(n[i]!==r[i]){if(i==="images"){const a=n[i],c=r[i];if(Array.isArray(a)&&Array.isArray(c)&&El(a,c))continue}if(i==="frame"){const a=n[i],c=r[i];if(a!==void 0&&c!==void 0&&a.epoch===c.epoch&&a.seq===c.seq)continue}if(i==="skill"){const a=n[i],c=r[i];if(a!==void 0&&c!==void 0&&NI(a,c))continue}return!1}return!0}function NI(e,t){return e.name===t.name&&e.token===t.token&&e.request===t.request&&e.purpose===t.purpose&&e.body===t.body}function De(e,t){const n=e.index.get(t.id);if(n!==void 0){const i=e.records[n];if(mc(i,t))return e;const a=e.records.slice();if(a[n]=e.journalMode?{...t,...i.sourceEntryId?{sourceEntryId:t.sourceEntryId??i.sourceEntryId}:{},...i.sourceAdmissionAnchor&&!t.sourceAdmissionAnchor?{sourceAdmissionAnchor:i.sourceAdmissionAnchor}:{},...i.sourcePrecedes&&!t.sourcePrecedes?{sourcePrecedes:i.sourcePrecedes}:{},...i.journalGeneration?{journalGeneration:t.journalGeneration??i.journalGeneration,journalSeq:t.journalSeq??i.journalSeq}:{}}:t,!e.journalMode)return{...e,records:a};const c=Vo(a,vn,e);return{...e,records:c,index:St(c)}}const r=e.journalMode?Vo([...e.records,t],vn,e):[...e.records,t],o=St(r);return{...e,records:r,index:o}}function Al(e,t){if(!e.records.some(t))return e;const n=e.records.filter(r=>!t(r));return{...e,records:n,index:St(n)}}function _a(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")?Al(e,i=>i.id===n):e}function LI(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 i=e.records.slice();return i[r]=n,{...e,records:i,index:St(i)}}const FI=new Set(["frontend_state_checkpoint_v1","music_job_v1","session_state","hub_communication","wake_schedule","prune"]);function Mm(e){const t=e.trim()||"compaction did not run",n={id:"compaction_not_run",sentence:t};return{text:Cs(n),copy:n,level:t.startsWith("compaction failed")?"error":"warning"}}function UI(e,t){const n=sf(e),r=sf(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const jm="Context compacted",BI=12e4;function $m(e){const t=[],n=[];for(const d of e)d.kind==="compaction"&&(d.id.startsWith("compaction:")?t.push(d):n.push(d));if(t.length===0||n.length===0)return e;const r=new Set,o=new Set,i=new Map,a=(d,u)=>{r.add(u.id),o.add(d.id),i.set(u.id,d.text)},c=[...t].sort((d,u)=>d.ts-u.ts);for(const d of c){if(d.before===void 0)continue;const u=n.find(f=>!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>BI||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=i.get(d.id);return u===void 0||d.kind!=="compaction"&&d.kind!=="notice"||u===d.text?d:{...d,text:u}})}function HI(e){const t=$m(e.records);return t===e.records?e:{...e,records:t,index:St(t)}}const WI="peer_message",GI="ask_response",zI="ask_timeout",Dm="Completed — runtime retired/disposed",Nm="Retired for an update — a turn was in flight and was cut; its earlier output is kept",KI="wake_prompt",VI="session_mcp_unavailable",ZI=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),YI=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,Xu=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,XI=new Set(["this changes your instructions. apply it from now on, and drop work it makes pointless.","answer it now with the `hub` tool — a short, direct reply — then carry on with what you were doing. do not restructure your work around the question.","this is a note, not a question. no reply is needed unless it changes what you should do."]),Lm=/^\[[^\]]{1,32}\]\s*/,ls="Reason:",JI=/[\n;,(]| [—–] /,QI=/^\d+\.$/,qI=/[A-Z]/,eA=/\s/,So=160;function Ui(e,t,n){if(e==="audio_settle_v1")return{level:"info",headline:t,detail:null,category:"Audio settlement",provider:null};if(e==="session_incident")return{level:"error",...iA(t,n)};let r;return e===VI?r=tA(t):ZI.has(e)?r=rA(t.trim().replace(Lm,"")):r=sA(t),{level:"info",category:null,provider:null,...r}}function tA(e){const t=e.trim().replace(Lm,"").split(`
33
- `).map(c=>c.trim()),n=t[0]??"",r=t[1]?.startsWith(ls)?t[1]:null,o=t.slice(r?2:1).filter(Boolean).join(`
34
- `),i=(r?`${n} ${r}`:n).trim();if(i.length<=So)return{headline:i,detail:o||null};const a=r===null?null:nA(r);if(a!==null){const c=(f,h)=>`${ls} ${[f,h].filter(Boolean).join(" ")}`,l=f=>[f,o].filter(Boolean).join(`
35
- `)||null,d=`${n} ${c(a.leading,a.clause)}`;if(d.length<=So)return{headline:d,detail:l(a.rest)};const u=`${n} ${c("",a.clause)}`;if(u.length<=So)return{headline:u,detail:l([a.leading,a.rest].filter(Boolean).join(" "))}}return{headline:Um(i),detail:[r,o].filter(Boolean).join(`
36
- `)||null}}function nA(e){const t=e.startsWith(ls)?e.slice(ls.length):e,n=t.indexOf("/mcp");if(n<0)return null;const r=t.slice(n),o=r.search(JI),i=(o<0?r:r.slice(0,o)).trim();return i?{leading:t.slice(0,n).trim(),clause:i,rest:(o<0?"":r.slice(o)).trim()}:null}function rA(e){const t=e.trim(),n=oA(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 oA(e){for(let t=0;t<e.length-1;t++)if(".!?…".includes(e[t])&&eA.test(e[t+1])&&!QI.test(e.slice(0,t+1))&&qI.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(YI),i=(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:i,detail:a||null}}function Fm(e){if(typeof e!="object"||e===null)return null;const t=e.hub_receipt;if(typeof t!="object"||t===null)return null;const n=t,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 i={...n};for(const a of["expects_reply","steer"])typeof i[a]!="boolean"&&(i[a]=null);for(const a of["label","job_id"])a in i&&typeof i[a]!="string"&&delete i[a];return i}function sA(e){const t=aA(e),n=e.split(`
39
- `).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function aA(e){const t=e.split(`
40
- `).map(c=>c.trim()).filter(Boolean),n=c=>!Xu.test(c)&&!cA(c),r=t.find(n),o=t.find(c=>Xu.test(c)&&!c.startsWith("</"));let i=r??o??e.trim();const a=t.indexOf(i);if(a>=0&&i.endsWith(":")){const c=t.slice(a+1).find(n);c&&(i=`${i} ${c}`)}return Um(i)}function cA(e){return XI.has(e.replace(/\s+/g," ").trim().toLowerCase())}function Um(e){const t=e.trim();if(t.length<=So)return t;const n=t.slice(0,So),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const lA="harness_injected",Bm=e=>!e||typeof e!="object"?!1:e[lA]===!0;function Hm(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function Wm(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const dA="ask";function Ju(e,t){return t===!0&&String(e??"")===dA}function uA(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function fA(e,t,n){const r=e.payload;if(!hE(r))return null;const o=r.details,i=_l(r,typeof o?.session_id=="string"?o.session_id:null);if(!i)return null;if(n?.kind==="tool"&&n.toolCallId===i.callId){if(!n.captureOnly)return n.diffFull?n:{...n,diffFull:i.descriptor};if(n.diffFull&&pA(n.diffFull,i.descriptor))return n}return{kind:"tool",id:`tool:${i.callId}`,ts:t,toolCallId:i.callId,toolName:i.tool,intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:Nr,added:0,removed:0,diff:null,diffTruncatedRows:0,diffFull:i.descriptor,captureOnly:!0,stopped:!1}}function pA(e,t){return e.state===t.state&&(e.state!=="archived"||t.state==="archived"&&e.rows===t.rows)}function Gm(e){const t=e.payload;if(e.type==="custom"&&t?.custom_type===zo){const n=t.details;return`tool:${typeof n?.call_id=="string"?n.call_id:""}`}return`tool:${String(t?.tool_call_id??"")}`}function zm(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:jm,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:r,text:a,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const a=n.details??{},c=Mm(String(a.detail??""));return{kind:"notice",id:e.id,ts: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:Dm,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:Nm,level:"warning"};if(a.kind==="error"||a.kind==="interrupted"){const c=a.kind==="error"?{id:"stopped_with_error"}:{id:"interrupted"};return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:Cs(c),copy:c,level:a.kind==="error"?"error":"warning"}}}}if(e.type==="custom"&&n.custom_type===pc){const a=n.details??{};return Ku(r,a,t)}if(e.type==="custom"&&n.custom_type===zo)return fA(e,r,t);if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(FI.has(a)||a===zo)return null;const c=n.details??{};if(a==="hub_message"){const f=ac(c);if(!f.body.trim())return null;const h=t?.kind==="custom"?t.receipt:void 0;return h&&fa(h.sender,f.sender)&&(f.sender=h.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:f.envelope,attribution:"user",...Ui(a,f.envelope||f.body,c),receipt:h&&Object.keys(f).every(_=>h[_]===f[_])?h:f,images:Xn(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===WI){const{body:f,sender:h}=Fh(c);return{kind:"peer",id:e.id,ts:r,body:f,sender:t?.kind==="peer"&&fa(t.sender,h)?t.sender:h}}if(a===KI){if(Zk(c)||Yk(c))return null;const f=String(c.text??"");return f.trim()?{kind:"wake",id:e.id,ts:r,text:f}:null}if(a===GI){const f=c.answers,h={};if(f&&typeof f=="object")for(const[v,b]of Object.entries(f))h[String(v)]=Array.isArray(b)?b.map(p=>String(p)):[];const _=c.questions,y=Array.isArray(_)?_.flatMap(v=>{if(!v||typeof v!="object")return[];const b=v;return[{id:String(b.id??""),question:String(b.question??""),secret:b.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts: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:y,answers:h,secretLost:c.secret_lost===!0}}if(a===zI){const f=Number(c.waited_s);return{kind:"ask_timeout",id:e.id,ts:r,askId:String(c.ask_id??""),waitedS:Number.isFinite(f)&&f>0?f:0,urgent:c.urgent===!0}}if(a===pc)return Ku(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?WE(c):null)??String(c.text??c.detail??"");if(!d.trim())return null;const u=a==="job_result"?GE(c):void 0;return{kind:"custom",id:e.id,ts:r,customType:a,text:d,...u?{music:u,images:u.tracks.flatMap(f=>f.images)}:{},...a==="job_result"&&typeof c.job_id=="string"&&c.job_id.length>0?{jobId:c.job_id}:{},...a==="team_bridge_message"?{bridgeReceipt:Xk(c)}:{},attribution:n.attribution??"system",...Ui(a,d,c)}}const i=String(n.role??"");if(i==="user"){const a=Fm(n.provider_payload);if(a){const u=ac({...a,text:Qt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&fa(f.sender,u.sender)&&(u.sender=f.sender);const h=t?.kind==="custom"||t?.kind==="user"?t.images:void 0;return{kind:"custom",id:e.id,ts:r,customType:"hub_message",text:u.envelope,attribution:"user",...Ui("hub_message",u.envelope||u.body,{...a,text:Qt(n)}),receipt:f&&Object.keys(u).every(_=>f[_]===u[_])?f:u,images:Xn(n,e.id,h)}}}if(Bm(n.provider_payload))return null;const c=Qt(n);if(mm(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=Rs(c),d=Cm(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Xn(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(i==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=Qt(n);return!c&&a.length>0?{kind:"assistant",id:e.id,ts: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(i==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(Wm(l))return null;const d=Rm(l.__fault);return{kind:"tool",id:`tool:${a}`,ts:r,toolCallId:a,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:Qt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Xn(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...im(c.details,t?.kind==="tool"?t:null),diff:om(rm(c.details),t?.kind==="tool"?t.diff:null),diffTruncatedRows:sm(c.details,t?.kind==="tool"?t.diffTruncatedRows??0:0),diffFull:lm(c.details,t?.kind==="tool"?t.diffFull??null:null),stopped:d,delivery:Yh(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:Vh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:Zh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:hm(String(n.tool_name??""),c.details,t?.kind==="tool"?t.details??null:null)}}return null}function 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=eI(t);if(n)return e.records[e.index.get(n)??-1]}function Rl(e){const t=Sh(e,e.records);if(t===e.records)return e;const n=t.map(gm);return{...e,records:n,index:St(n)}}const Zo=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Km(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:i,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&&Zo(r.journalSeq)&&n.add(o))}return{carried:t,admitted:n}}function xl(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function Qu(e,t){const n=new Set;for(const a of t)typeof a=="string"&&a.length>0&&a.length<=128&&n.add(a);if(n.size===0)return e;let 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=xl(a);return l!==a&&(r=!0),l});let i=r?{...e,records:o}:e;return i=Vm(i,n),i}function Vm(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=bA(e),o=e.orderRevision??0,i=e.journalBodyOwed;let a=null;const c=e.journalSourceVoid;let l=null;for(const d of t)typeof d!="string"||d.length<1||d.length>128||!n.has(d)||r.has(d)||(a||(a=new Map(i??[])),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 ds(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 i=null;const a=r.journalSourceVoid;let c=null;for(const l of t)o?.has(l)&&(i||(i=new Map(o)),i.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!i&&!c?r:{...r,...i?{journalBodyOwed:i}:{},...c?{journalSourceVoid:c}:{}}}function si(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function Zm(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function vA(e,t,n){let r=Gr(e,t,t.entries.map(i=>({id:i.id,journal_seq:i.journal_seq,role:i.payload?.role,tool_call_id:i.payload?.tool_call_id})),!0,n);for(const i of t.entries)r=cl(r,{...i.payload,id:i.id});const o=si(r,!1);return Rl(o.journalPeerSource===void 0&&!o.journalBodyOwed&&!o.journalSourceVoid&&o.journalSourceUnavailable===void 0?o:{...o,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function qu(e,t,n){let r=Gr(e,t,(t.entries??[]).map(i=>({id:i.id,journal_seq:i.journal_seq,role:i.payload?.role,tool_call_id:i.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=si(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const i=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];i.length>0&&(r=Vm(r,i));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=ds(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=Zm(r,t),Rl(r)}function yA(e,t,n,r){let o=Gr(e,t,[],!1,n,{peer:!0});o=si(o,!0);const i=o.journalBodyOwed,a=_=>r!==void 0&&(i?.get(_)??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 _=new Map;for(const y of l){if(typeof y.id!="string"||y.id===""||a(y.id))continue;const v=Gm(y),b=f.get(y.id)??f.get(v),p=b===void 0?void 0:u[b];if(!p)continue;let A=zm(y,p);A&&(A={...A,sourceEntryId:y.id,...p.sourcePrecedes?{sourcePrecedes:p.sourcePrecedes}:{}},Zo(y.journal_seq)?(A=Km(A,y.id,t.journal_generation,y.journal_seq),d.push(y.id)):A=xl(A),_.set(p.id,A))}_.size>0&&(u=u.map(y=>_.get(y.id)??y),f=St(u))}let h=u===o.records?o:{...o,records:u,index:f};if(c){h=ds(h,d,!1);const _=(t.source_missing_ids??[]).filter(y=>typeof y=="string"&&y.length>0&&y.length<=128&&!a(y));if(_.length>0){h=ds(h,_,!1);const y=new Set(h.journalSourceVoid??[]);for(const v of _)y.add(v);h={...h,journalSourceVoid:y}}}return h=Zm(h,t),Rl(h)}function Ii(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function Eo(e,t,n={}){let r=e;const o=r,i=[];let a=e.profileHistoryPending;const c=E=>si(ds(E.profileHistoryPending===a?E:{...E,profileHistoryPending:a},i,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Gr(r,t,t.entries.map(E=>({id:E.id,journal_seq:E.journal_seq,role:E.payload?.role,tool_call_id:E.payload?.tool_call_id})),n.authoritative===!0,n.orderRead,{peer:n.peerSource===!0}),t.journal_generation&&t.journal_generation!==r.journalGeneration)return c(r);const l=n.peerSource===!0&&typeof t.journal_generation=="string"&&t.journal_generation.length>0&&t.journal_generation===r.journalGeneration;for(const E of t.entries)r=cl(r,{...E.payload,id:E.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=ZE(t.entries,r.records,d||o.journalGeneration!==r.journalGeneration?[]:r.profileHistoryPending);a=!d&&f.pending.length?f.pending:void 0;const h=[];for(const E of f.entries){if(d&&!LA(E,r.clearedAt))continue;const V=r.records[r.index.get(E.id)??-1]??r.records[r.index.get(Gm(E))??-1]??_A(r,E);let G=zm(E,V);if(YE(E,V)&&V&&(G=V),G&&(r.journalMode||G.kind==="tool"&&yl(G.toolName,G.details))&&(G={...G,sourceEntryId:E.id}),G&&r.journalMode){const me=V?.sourcePrecedes??(n.pagedBefore!==void 0&&!V?u:void 0);me!==void 0&&G.sourcePrecedes!==me&&(G={...G,sourcePrecedes:me})}G&&l&&Zo(E.journal_seq)?(G=Km(G,E.id,t.journal_generation,E.journal_seq),i.push(E.id)):G&&n.peerSource===!0&&(G=xl(G)),!(G&&V&&uA(V,n.readWitness))&&G&&h.push(G)}let _=r.argsByCall,y=!1;for(const E of t.entries){const V=E.payload?.tool_calls;if(!Array.isArray(V))continue;const G=Math.round((E.ts??0)*1e3);for(const me of V)!me||typeof me.id!="string"||_.has(me.id)||(y||(_=new Map(_),y=!0),_.set(me.id,{...me,anchoredAt:G,anchorId:E.id}))}for(let E=0;E<h.length;E++){const V=h[E];if(V.kind!=="tool")continue;const G=_.get(V.toolCallId);if(!G)continue;const me=G.arguments??null;h[E]={...V,args:me,intent:typeof me?.i=="string"?me.i:null}}const v=y?r.records.map(E=>{if(E.kind!=="tool"||E.args)return E;const G=_.get(E.toolCallId)?.arguments??null;return G?{...E,args:G,intent:E.intent??(typeof G.i=="string"?G.i:null)}:E}):r.records,b=new Set(t.entries.map(E=>E.id)),p=n.peerSource===!0&&n.replace===!0?r.records.filter(E=>E.kind==="user"&&(E.provisional===!0||E.local===!0)&&!b.has(E.id)):[],A=n.replace?p.length>0?{...Ut,records:p,index:St(p)}:Ut:{...r,records:v},k=new Map(A.records.map(E=>[E.id,E]));let M=r!==o||n.replace||!n.replace&&v!==r.records;for(const E of h){const V=k.get(E.id);if(!V){M=!0,k.set(E.id,E);continue}if(V.kind==="tool"&&E.kind==="tool"){const G={...E,args:E.args??V.args,intent:E.intent??V.intent,images:Om(E.images,V.images,"current")};mc(V,G)||(M=!0,k.set(E.id,G));continue}mc(V,E)||(M=!0,k.set(E.id,E))}const P=r.compacting&&t.entries.some(E=>r.index.has(E.id)||Math.round((E.ts??0)*1e3)<r.compactingSince?!1:E.type==="compaction"||E.type==="message"&&E.payload?.custom_type==="compaction_refused"),W=t.entries[0],R=W?Math.round((W.ts??0)*1e3):0,m=r.journalMode?vn:$I(A.records,R,n.statedByOwner!==!1);let w=A.oldestId,S=A.oldestTs,T=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(W&&(w=W.id,S=R),T=t.has_more):n.pagedBefore!==void 0?W?(w=W.id,S=R,T=t.has_more):T=!1:W&&(r.journalMode?(r.journalPositions?.get(W.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):R>0&&R<r.oldestTs)&&(w=W.id,S=R,T=t.has_more));const N=w!==r.oldestId||S!==r.oldestTs;if(!M&&!N&&r.hasMore===T&&!P&&m.size===0)return c(r);const Y=m.size===0?[...k.values()]:[...k.values()].map(E=>m.has(E.id)?DI(E):E),X=$m(Vo(Y,n.statedByOwner===!1?vn:new Set(h.map(E=>E.id)),r));return n.keepPaging?c({...r,records:X,index:St(X),argsByCall:_}):c({...r,records:X,index:St(X),oldestId:w,oldestTs:S,hasMore:T,argsByCall:_,compacting:P?!1:r.compacting,compactingSince:P?0:r.compactingSince})}const wA=/^(?:local|notice|retry|subagent|compaction):/;function Tl(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!wA.test(e.id)}}function kA(e,t,n=vn){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(o=>!(o.ts<t.ts&&Tl(o)&&!n.has(o.id)));return r.length===e.records.length?e:{...e,records:r,index:St(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const an={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function ba(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function gc(e,t,n=Date.now(),r={}){let o=e;const i=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=Gr(o,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=Vo(d.records,vn,d);return d===o&&u===o.records?o:{...d,records:u,index:St(u)}}i&&(o=cl(o,i));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=De(d,{...u,streaming:!1,settledAt:n,callsTools:!1,stopReason:t.aborted?"aborted":u.stopReason})),u.kind==="tool"&&u.phase!=="done"){const f=u.phase==="composing"||u.phase==="queued";d=De(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=ba(i);if(i===void 0||l===null)return an.idlessFrameRefused+=1,o;const d=o.records[o.index.get(l)??-1];if(i.role==="user"){const u=Fm(i.provider_payload);if(u){const v=Qt(i),b=ac({...u,text:v});if(b.body.trim()){const p=d?.kind==="user"&&d.provisional===!0;return De(o,{kind:"custom",id:l,ts:p?us(o,n):n,customType:"hub_message",text:b.envelope,attribution:"user",...Ui("hub_message",b.envelope||b.body,{...u}),receipt:b,images:Xn(i,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(Bm(i.provider_payload))return o;const f=Qt(i);if(mm(f))return o;const h=d?.kind==="user"&&d.provisional===!0,_=Cm(i,l,d?.kind==="user"?d.documents:void 0),y=Rs(f);return De(o,{kind:"user",id:l,ts:h?us(o,n):n,text:f,images:Xn(i,l,d?.kind==="user"?d.images:void 0),..._.length?{documents:_}:{},...h?{provisional:!0}:{},...y?{skill:y}:{}})}return i.role!=="assistant"||d?o:De(o,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=ba(i);if(i===void 0||l===null)return an.idlessFrameRefused+=1,o;const d=o.index.get(l),u=String(t.delta??""),f=Qt(i);if(d===void 0)return!f&&!u?o:De(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 an.settledAssistantUpdate+=1,o;if(r.seed!==!0&&a&&h.frame&&a.epoch===h.frame.epoch&&a.seq<=h.frame.seq)return an.staleUpdateFrameDropped+=1,o;const _=jI(h.frame,a);if(r.seed===!0&&!f)return!h.text&&!u?o:(an.seededDeltaWithheld+=h.text?1:0,De(o,{...h,text:h.text||u,..._?{frame:_}:{},truncated:h.text?"interrupted":"prefix"}));let y;if(f){if(y=f+u,y.length<=h.text.length)return o}else{if(!u)return o;y=h.text+u}return De(o,{...h,text:y,..._?{frame:_}:{},truncated:f?void 0:h.truncated})}case"message_end":{const l=ba(i);if(i===void 0)return an.idlessFrameRefused+=1,o;if(l===null){if(i.role!=="assistant")return an.idlessFrameRefused+=1,o;let y;for(const p of o.records)if(!(p.kind!=="assistant"||!p.streaming)){if(y!==void 0)return an.idlessFrameRefused+=1,o;y=p}if(y===void 0)return an.idlessFrameRefused+=1,o;const v=Array.isArray(i.tool_calls)?i.tool_calls:[],b={...y,streaming:!1,settledAt:y.settledAt??n,callsTools:v.length>0,...y.text||v.length===0?{complete:!0}:{}};return De(o,b)}if(i.role!=="assistant")return o;const d=o.index.get(l),u=Qt(i),f=d===void 0?void 0:o.records[d],h=Array.isArray(i.tool_calls)?i.tool_calls:[],_={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:i.stop_reason??null,error:!!i.is_error,...a?{frame:a}:{}};return De(o,_)}case"history_delta":{const d=(Array.isArray(t.messages)?t.messages:[]).filter(k=>String(k.id??"")!==""),u=typeof t.journal_generation=="string"&&t.journal_generation.length>0?t.journal_generation:void 0,f=t.journal_ordinals&&typeof t.journal_ordinals=="object"&&!Array.isArray(t.journal_ordinals)?t.journal_ordinals:void 0,h=t.entry_times&&typeof t.entry_times=="object"&&!Array.isArray(t.entry_times)?t.entry_times:void 0,_="journal_generation"in t||"journal_ordinals"in t||"entry_times"in t,y=o.journalPeerSource===!0||_,v=y&&u!==void 0&&u===o.journalGeneration,b=d.map(k=>String(k.id??"")).filter(k=>k.length>0&&k.length<=128),p={entries:d.map(k=>{const M=String(k.id??""),P=f?.[M],W=h?.[M];return{id:M,ts:v&&typeof W=="number"&&Number.isFinite(W)?W:n/1e3,type:"message",payload:{kind:k.custom_type?"custom":"message",...k},...v&&Zo(P)?{journal_seq:P}:{}}}),has_more:o.hasMore,...v?{journal_generation:u}:{}};let A=Eo(o,p,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:y});if(y&&b.length>0)if(v){const k=b.filter(M=>!Zo(f?.[M]));k.length>0&&(A=Qu(A,k))}else A=Qu(A,b),u!==void 0&&(A=Gr(A,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),A=si(A,!0));return A}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return 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,_=f?.kind==="tool"?f:h?.kind==="tool"?h:void 0;if(_&&_.phase!=="composing"&&_.phase!=="queued")return d&&f?.kind==="tool"?_a(o,d):o;const v=String(t.not_run_reason??"").trim()||null,b=String(t.not_run_kind??"").trim()||null;if(Ju(t.tool_name,c)&&!v&&!_)return d?_a(o,d):o;const p=Number(t.argument_bytes??0),A={kind:"tool",id:u,ts:_?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:v?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:p>0?p:_?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:Nr,added:0,removed:0,diff:null,diffTruncatedRows:0,diffFull:null,stopped:!1,notRunReason:v,notRunKind:v?b:null,neverSent:v!==null};return d&&h?.kind==="tool"&&f?.kind!=="tool"?LI(o,d,A):De(d&&f?.kind==="tool"?_a(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=Zu(o,l,t,u),h=f&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:f,anchoredAt:Lr(t)??n}):o.argsByCall,_=h===o.argsByCall?o:{...o,argsByCall:h};return Ju(t.tool_name,c)&&!u?_:De(_,{kind:"tool",id:d,ts:u?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??(typeof f?.i=="string"?f.i:null),args:f,phase:"running",notRunReason:null,notRunKind:null,neverSent:!1,argumentBytes:0,output:null,isError:!1,durationS:null,startedAt:Lr(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:Nr,added:0,removed:0,diff:u?.kind==="tool"?u.diff:null,diffTruncatedRows:u?.kind==="tool"?u.diffTruncatedRows??0:0,diffFull:u?.kind==="tool"?u.diffFull??null:null,details:u?.kind==="tool"?u.details??null:null,stopped:!1})}case"tool_execution_update":{const l=String(t.tool_call_id??"");if(!l)return 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:De(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(Wm(f.details))return Jm(o,d);const h=Zu(o,l,t,u),_=u&&u.kind==="tool"?u:{kind:"tool",id:d,ts:n,toolCallId:l,toolName:String(t.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:Nr,added:0,removed:0,diff:null,diffTruncatedRows:0,diffFull:null,stopped:!1},y=h&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:h,anchoredAt:Lr(t)??n}):o.argsByCall,v=y===o.argsByCall?o:{...o,argsByCall:y},b=r.userStoppedAt??null,p=!!(t.is_error??f.is_error),A=Rm(f.details?.__fault),k=b!==null&&(typeof _.startedAt=="number"?_.startedAt<=b:p);return De(v,{..._,args:h,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:Qt(f)||null,isError:k||A?!1:p,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof _.startedAt=="number"?_.startedAt+t.duration_s*1e3:null,startedAt:null,images:MI(Xn(f,d,_.images),_.images),...im(f.details,_),diff:om(rm(f.details),_.diff),diffTruncatedRows:sm(f.details,_.diffTruncatedRows??0),diffFull:lm(f.details,_.diffFull??null),stopped:_.stopped||k||A,delivery:Yh(f.details,_.delivery,_.toolName),bridge:Vh(_.toolName,f.details,_.bridge),bridgeLabel:Zh(_.toolName,f.details,_.bridgeLabel),details:hm(_.toolName,f.details,_.details)})}case"supplement_progress":{const l=II(t);if(!l)return o;const d=kl(l.anchor),u=o.records[o.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,h=Am(f,l,n);return h?De(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:De(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:Mm(String(t.detail??"")),h=f?f.text:l&&d?UI(l,d):jm,_=`compaction:${o.generation}:${l}:${d}`,y=o.compacting?{...o,compacting:!1,compactingSince:0}:o;return y.index.has(_)?y:f?De(y,{kind:"notice",id:_,ts:n,text:h,copy:f.copy,level:f.level}):HI(De(y,{kind:"compaction",id:_,ts:n,text:h,before:l}))}case"retry_start":{const l=`Retrying after an error (attempt ${String(t.attempt??"?")})${t.fallback_model?`, falling back to ${String(t.fallback_model)}`:""}`,d=`retry:${o.generation}:${String(t.attempt??"")}`;return o.index.has(d)?o:De(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:De(o,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return o}}function Lr(e){return Hw(e.started_at_epoch)}function Cl(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function SA(e){const t=Cl(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function EA(e,t){const n=Lr(e);if(n!==null)return n;const r=Cl(e);if(!r)return null;const o=t.argsByCall.get(r)?.anchoredAt;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}function IA(e,t){if(Lr(e)!==null)return!1;const n=Cl(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<=Pm(t.records)}function Ol(e){return e.type!=="tool_call_compose"?!1:typeof e.not_run_reason=="string"&&e.not_run_reason.trim().length>0?!0:e.dictation_complete===!0}function Os(e){return e.type==="tool_execution_end"}function 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 i=t.streaming===!0,a=Hm(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let h=n;const _=SA(f);if(_!==null&&!o.index.has(_)){const y=EA(f,o);if(y!==null)h=y,c=!0,IA(f,o)&&l.add(_);else if(Os(f)||Ol(f)||!i)continue}o=gc(o,f,h,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return o;const d=Vo(o.records,l,o);return{...o,records:d,index:St(d)}}function ef(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!Os(r)&&!Ol(r))continue;const o=String(r.tool_call_id??"");if(!o)continue;const i=Lr(r);i!==null&&t.set(o,i)}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 i=String(r.tool_call_id??"");i&&t.add(i)}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 i=o.payload.tool_call_id;if(typeof i!="string"||!n.has(i))continue;const a=o.ts;typeof a!="number"||!Number.isFinite(a)||r.set(i,Math.round(a*1e3))}return r}function CA(e,t,n,r=new Map,o=new Set){const i=e[0]?.ts;if(typeof i!="number"||!Number.isFinite(i))return!1;let a=null;for(const l of t){const d=n.get(l);if(d===void 0){if(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(i*1e3)<=a-xA}function tf(e,t){const n=[];for(const r of e??[]){if(!r)continue;const o=r;if(!Os(o)&&!Ol(o))continue;const i=String(o.tool_call_id??"");!i||n.includes(i)||t.has(i)||n.push(i)}return n}function nf(e,t,n,r){const o=[],i=new Set;for(const a of t)i.has(a)||(i.add(a),!n.has(a)&&((e.get(a)??0)>=r||o.push(a)));return o}const OA=3.25,_c=100,Pl=500;function rf(e){return e<=0?_c:Math.min(Pl,_c+Math.ceil(OA*e))}function va(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 i of o)i&&typeof i.id=="string"&&t.has(i.id)&&n.push(i.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 i of e){const a=i.payload?.tool_calls;if(Array.isArray(a))for(const c of a)c&&typeof c.id=="string"&&n.add(c.id)}const r=[],o=new Set;for(const i of e){if(i.payload?.role!=="tool")continue;const a=i.payload.tool_call_id;typeof a!="string"||n.has(a)||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,i=r.type==="tool_call_compose"&&typeof o=="string"&&o.trim().length>0;if(r.type!=="tool_execution_start"&&!Os(r)&&!i)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function Ym(e,t,n){const r=new Set(e),o=[];for(const i of t)!r.has(i)&&!n.has(i)&&o.push(i);for(const i of e){if(n.has(i))return o;t.has(i)&&o.push(i)}return o}function DA(e,t,n){return Ym(e,t,n).length}function of(e){let t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;for(const n of e.records)n.kind!=="assistant"||!n.streaming||n.truncated||(t=De(t,{...n,truncated:"interrupted"}));return t}function NA(e,t=Date.now()){return e.records.length===0&&!e.profileHistoryPending?.length?e:{...Ut,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function 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 sf(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 Al(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function us(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function Xm(e,t,n,r,o=Date.now(),i=hc){if(e.index.has(t))return e;const a=Rs(n);return De(e,{kind:"user",id:t,ts:us(e,o),text:n,images:r,...i.length?{documents:i}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function Jm(e,t){return Al(e,n=>n.id===t)}let af=0;function UA(e,t,n,r=Date.now()){return af+=1,De(e,{kind:"notice",id:`local:${r}:${af}`,ts:us(e,r),text:t,level:n})}function cD(e,t,n,r){const o=t?.anchor_id,i=t?.kind;if(!o||i!=="error"&&i!=="interrupted"&&i!=="closed"&&i!=="retired"||n||e.index.has(o)||!t?.unseen&&!r?.has(o))return e;r?.add(o);const a=i==="error"?{id:"stopped_with_error"}:i==="interrupted"?{id:"interrupted"}:void 0;return De(e,{kind:"notice",id:o,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:i==="closed"?Dm:i==="retired"?Nm:Cs(a),...a?{copy:a}:{},level:i==="closed"?"info":i==="retired"?"warning":i==="error"?"error":"warning"})}const BA=5*60,HA="session_temporary",WA="session_temporary_deleted",GA=["running","on_screen","open_ask","armed_wake","armed_monitor","unread_mail","operator_hold","unseen_result","unsaved_files","linked","cannot_verify"];function cf(e,t){if(!t||!e)return null;const n=e.temporary;return n===null||typeof n!="object"||typeof n.marked_at!="number"||!Number.isFinite(n.marked_at)?null:n}function Qm(e,t){if(!t)return{normal:e,temporary:[]};let n=!1;for(const i of e)if(cf(i,!0)!==null){n=!0;break}if(!n)return{normal:e,temporary:[]};const r=[],o=[];for(const i of e)(cf(i,!0)!==null?o:r).push(i);return{normal:r,temporary:o}}function lD(e,t){return e?t.some(n=>n.session_id===e):!1}function zA(e,t){return e.hold!==null&&e.hold!==void 0||typeof e.deletes_at!="number"||!Number.isFinite(e.deletes_at)?null:Math.max(1,Math.floor((e.deletes_at-t)/60))}function dD(e,t){return typeof e!="number"||!Number.isFinite(e)?!1:e-t<=BA}function uD(e,t){if(e.hold!==null&&e.hold!==void 0)return{key:"hold",code:qm(e.hold)};const n=zA(e,t);return n===null?{key:"hold",code:"cannot_verify"}:{key:"deletes_in",minutes:n}}function qm(e){return GA.includes(e)?e:"cannot_verify"}const KA={running:"ui.chat.sidebar_view.temporary.hold.running",on_screen:"ui.chat.sidebar_view.temporary.hold.on_screen",open_ask:"ui.chat.sidebar_view.temporary.hold.open_ask",armed_wake:"ui.chat.sidebar_view.temporary.hold.armed_wake",armed_monitor:"ui.chat.sidebar_view.temporary.hold.armed_monitor",unread_mail:"ui.chat.sidebar_view.temporary.hold.unread_mail",operator_hold:"ui.chat.sidebar_view.temporary.hold.operator_hold",unseen_result:"ui.chat.sidebar_view.temporary.hold.unseen_result",unsaved_files:"ui.chat.sidebar_view.temporary.hold.unsaved_files",linked:"ui.chat.sidebar_view.temporary.hold.linked",cannot_verify:"ui.chat.sidebar_view.temporary.hold.cannot_verify"};function fD(e){return KA[qm(e)]}function pD(e,t,n){return!e||t?null:n!==null?"keep":"make"}function hD(e,t){return e!==HA?null:t==="pin"?"keep_and_pin":"keep_and_link"}function mD(e,t){return Qm(e,t).normal}function gD(e,t,n){const{normal:r,temporary:o}=Qm(e,t);if(!n||o.length===0)return r;const i=o.find(a=>a.session_id===n);return i?[i,...r]:r}function VA(e,t){return t&&e?.temporary===!0&&!e.peer}function _D(e){return e===!0?"ui.chat.composer.placeholder.temporary":null}function ZA(e){return e===WA}const YA="compacting context…";function bD(e){return typeof e=="string"&&e.trim()===YA}const XA=[1500,5e3];async function vD(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of XA){await t(n);try{if(await e())return}catch{}}}function JA(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 QA=["store","routed","request","snapshot","content","painted","sendable"],qA=6e4,eR="[open-trace]",tR=/^[A-Za-z0-9_-]{1,80}$/,nR=["sidebar","open","native"];function rR(e,t,n){const r=tR.test(e.sessionId)?e.sessionId:"?",o=nR.includes(e.entrance)?e.entrance:"open",i=u=>u===void 0?"-":String(Math.max(0,Math.round(u-e.start))),{painted:a,sendable:c}=e.stages,l=a!==void 0&&c!==void 0?Math.max(a,c):void 0,d=[eR,`t=${e.token}`,`clickEpochMs=${e.clickEpochMs??"-"}`,`session=${r}`,`via=${o}`,`outcome=${t}`,...QA.map(u=>`${u}=${i(e.stages[u])}`),`settled=${i(l)}`];return n!==void 0&&d.push(`by=t${n}`),d.join(" ")}function oR(e){let t=0,n=null;const r=(i,a)=>{const c=n;if(c){n=null,e.clearTimer(c.timer);for(const l of Object.keys(c.fallbacks))c.stages[l]===void 0&&(c.stages[l]=c.fallbacks[l]);e.log(rR(c,i,a));for(const l of c.endListeners.splice(0))l()}},o=(i,a)=>{i.stages[a]===void 0&&(i.stages[a]=e.now(),i.stages.painted!==void 0&&i.stages.sendable!==void 0&&r("settled"))};return{begin(i,a){t+=1;const c=t;n&&r("superseded",c);const l={token:c,sessionId:i,entrance:a,start:e.now(),clickEpochMs:performance.timeOrigin+performance.now(),stages:{},fallbacks:{},timer:void 0,frameRequested:!1,endListeners:[]};return l.timer=e.setTimer(()=>{n===l&&r("timeout")},qA),n=l,c},note(i,a,c,l){const d=n;if(!(!d||!i||d.sessionId!==i)&&!(c!==void 0&&c!==d.token)){if(l?.fallback===!0){d.stages[a]===void 0&&d.fallbacks[a]===void 0&&(d.fallbacks[a]=e.now());return}if(a==="content"&&!d.frameRequested){d.frameRequested=!0,o(d,"content"),e.nextFrame(()=>{n===d&&o(d,"painted")});return}a==="painted"||a==="content"||o(d,a)}},fail(i,a){!n||!i||n.sessionId!==i||r(a)},activeSessionId(){return n?.sessionId??null},currentToken(){return n?.token??null},onEnd(i,a){n?.token===i?n.endListeners.push(a):a()}}}const iR=typeof window<"u";function sR(e,t,n){t(()=>n(e))}const aR=e=>{const t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)},Fr=oR({now:()=>performance.now(),nextFrame:e=>{iR&&typeof requestAnimationFrame=="function"&&typeof MessageChannel=="function"?sR(e,t=>requestAnimationFrame(()=>t()),aR):setTimeout(e,0)},log:e=>console.warn(e),setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e)});function cR(e,t,n,r){let o=!1;const i=()=>{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(i);e.onEnd(t,a),i()}const lf=new Set(["openrouter","radient","radient-key"]),lR=new Set(["auto","openrouter/auto"]),dR=()=>g("ui.chat.session_readout.model.router_auto");function eg(e){return e.slice(e.lastIndexOf("/")+1)||e}function uR(e,t){return e===t||e===eg(t)}function bc(e){if(!e)return null;const t=typeof e.provider=="string"?e.provider:"";if(!t)return null;const n=typeof e.model_id=="string"?e.model_id:"";return n?`${t}/${n}`:null}function fR(e,t){return t?bc(e?.selected_model)===t||bc(e?.effective_model)===t:!1}function yD(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=lf.has(t)||!r||uR(r,e.model_id)||r.toLowerCase()==="unknown";return{name:lf.has(t)&&lR.has(e.model_id)?dR():o?eg(n):r,selector:n}}function wD(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 kD(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function SD(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function ED(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 ID(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,"\\$&")),i=new RegExp(`(^|[\\s(])(${o.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(i,(a,c,l)=>`${c}${r.get(l)}`)}function AD(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function pR(e){const t=e.trim();return t&&(tg(t)??t)}const df=new Map;function tg(e){const t=sn();let n=df.get(t);return n===void 0&&(n={auto:g("ui.chat.session_readout.effort.level.auto"),none:g("ui.chat.session_readout.effort.level.none"),minimal:g("ui.chat.session_readout.effort.level.minimal"),low:g("ui.chat.session_status.effort_level.low"),medium:g("ui.chat.session_status.effort_level.medium"),high:g("ui.chat.session_status.effort_level.high"),xhigh:g("ui.chat.session_readout.effort.level.xhigh"),max:g("ui.chat.session_readout.effort.level.max"),unknown:g("ui.chat.session_readout.effort.level.unknown"),reasoning:g("ui.chat.session_readout.effort.level.reasoning")},df.set(t,n)),n[e.toLowerCase()]}const _o=e=>pR(e).toLowerCase(),Ai=e=>{const t=tg(e.trim());return t===void 0?e:t.toLowerCase()};function ng(e){if(!e)return!1;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim():"",n=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim():"";return typeof e.model_id=="string"&&e.model_id!==""&&!t&&!n&&!e.reasoning&&Array.isArray(e.reasoning_efforts)&&e.reasoning_efforts.length===0&&typeof e.display_name=="string"&&e.display_name.trim()===""}function RD(e,t){const n=(e??t)?.effective_model;return ng(n)?null:n?.model_id??null}function xD(e){if(!e)return null;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim().toLowerCase():"",n=Array.isArray(e.reasoning_efforts)?e.reasoning_efforts.filter(i=>typeof i=="string"):null,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",o=ng(e);return t?{label:t,adjustable:n===null||n.length>0,knownLadder:!!(n&&n.length>0),levelKnown:!0,detail:n&&n.length>0?g("ui.chat.session_readout.effort.detail.offers",{levels:Ni(n.map(_o))}):g("ui.chat.session_readout.effort.detail.session")}:n&&n.length>0?{label:"auto",adjustable:!0,knownLadder:!0,levelKnown:!0,detail:r?g("ui.chat.session_readout.effort.detail.auto_with_default",{default:_o(r),levels:Ni(n.map(_o))}):g("ui.chat.session_readout.effort.detail.auto",{levels:Ni(n.map(_o))})}:o?{label:"unknown",adjustable:!0,knownLadder:!1,levelKnown:!1,detail:g("ui.chat.session_readout.effort.detail.not_reported",{command:"/effort <level>"})}:n&&e.reasoning?{label:"reasoning",adjustable:!1,knownLadder:!0,levelKnown:!0,detail:g("ui.chat.session_readout.effort.detail.no_levels")}:n===null&&r?{label:r,adjustable:!1,knownLadder:!1,levelKnown:!0,detail:g("ui.chat.session_readout.effort.detail.default_only")}:null}function TD(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:g("ui.chat.session_readout.effort.detail.offers",{levels:Ni(n.map(_o))})}}function hR(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=so(n.provider);if(!a)return null;const c=so(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:so(n.label)||a,effectiveState:d,owner:so(n.owner_label)||so(n.owner_device)||g("ui.chat.session_readout.access.owner_fallback"),observedAt:ya(n.observed_at),lastGrantAt:ya(n.last_grant_at),lastGrantExpiresAt:ya(n.last_grant_expires_at)}}if(!n||n.state!=="signed_out"&&n.state!=="temporarily_unavailable")return null;const r=typeof n.provider=="string"?n.provider:"";if(!r)return null;const o=e?.effective_model?.provider;if(o&&o!==r)return null;const i=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:i,state:n.state}:{provider:r,label:i}}function CD(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function OD(e){return e&&e.draft!==!0?hR(e.frontend,e.servingLocality):null}function so(e){return typeof e=="string"?e.trim():""}function ya(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function wa(e){return K_(new Date(e*1e3),{dateStyle:"medium",timeStyle:"short"})}function PD(e){const{label:t,effectiveState:n}=e,r=e.owner||g("ui.chat.session_readout.access.owner_fallback"),o={local:[g("ui.chat.session_readout.access.local.title",{label:t}),g("ui.chat.session_readout.access.local.description")],pending:[g("ui.chat.session_readout.access.pending.title",{label:t}),g("ui.chat.session_readout.access.pending.description")],eligible_borrow_unverified:[g("ui.chat.session_readout.access.eligible_borrow_unverified.title",{owner:r}),g("ui.chat.session_readout.access.eligible_borrow_unverified.description",{label:t,owner:r})],effective_borrow:[g("ui.chat.session_readout.access.effective_borrow.title",{label:t,owner:r}),g("ui.chat.session_readout.access.effective_borrow.description")],expired:[g("ui.chat.session_readout.access.expired.title",{label:t}),g("ui.chat.session_readout.access.expired.description",{owner:r})],withdrawn:[g("ui.chat.session_readout.access.withdrawn.title",{label:t}),g("ui.chat.session_readout.access.withdrawn.description")],owner_unavailable:[g("ui.chat.session_readout.access.owner_unavailable.title",{owner:r}),g("ui.chat.session_readout.access.owner_unavailable.description",{label:t,owner:r})],device_bound:[g("ui.chat.session_readout.access.device_bound.title",{label:t}),g("ui.chat.session_readout.access.device_bound.description")],absent:[g("ui.chat.session_readout.access.absent.title",{label:t}),e.connectHere===!0?g("ui.chat.session_readout.access.absent.description_connect"):g("ui.chat.session_readout.access.absent.description_remote")]},i=e.state==="temporarily_unavailable",[a,c]=n?o[n]:[i?g("ui.chat.session_status.temporarily_unavailable",{label:t}):g("ui.chat.session_status.not_signed_in",{label:t}),i?g("ui.chat.session_status.temporarily_unavailable_description"):g("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];n&&e.observedAt!==void 0&&l.push(g("ui.chat.session_readout.access.history.last_checked",{time:wa(e.observedAt)})),n&&e.lastGrantAt!==void 0&&l.push(g("ui.chat.session_readout.access.history.last_resolved",{time:wa(e.lastGrantAt)})),n&&e.lastGrantExpiresAt!==void 0&&l.push(g("ui.chat.session_readout.access.history.grant_expiry",{time:wa(e.lastGrantExpiresAt)}));const d=[...l];return n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push(g("ui.chat.session_readout.access.history.only")),{title:a,description:c,history:l.join(" "),historyLines:d,tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!i,canSwitchModel:n!=="effective_borrow"}}function MD(e){switch(e?.effectiveState){case"effective_borrow":case"pending":case"eligible_borrow_unverified":return!0;default:return!1}}function jD(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="not-cleared"||e.kind==="settled"&&e.canRetry}function $D(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function DD(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function mR(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function gR(e,t){return!!e.streams[t]}function rg(e,t){return e.attached[t]?.turns.at(-1)}function ND(e,t){const n=rg(e,t);return n?e.streams[n.asideId]:void 0}function LD(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 _R(){return{text:"",streaming:!0,settled:!1,error:null}}function bR(e){return{text:e,streaming:!1,settled:!0,error:null}}function vR(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const yR=oi(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]:_R()},attached:{...o.attached,[t]:{turns:[...o.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const o=mR(r.streams[t],n);return o?{streams:{...r.streams,[t]:o}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:bR(n)}}:r),failAside:(t,n)=>e(r=>gR(r,t)?{streams:{...r.streams,[t]:vR(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 i=o.attached[t];return i?{attached:{...o.attached,[t]:{...i,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:o}),unqueueAdoption:(t,n,r)=>e(o=>{const i=o.attached[t];if(i?.queued?.asideId!==n)return o;const{queued:a,...c}=i;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 i={...n.streams};for(const a of r.turns)delete i[a.asideId];return{streams:i,attached:o}})}));function FD(e,t){return rg(e,t)?.asideId}const wR=4*1024*1024,uf=1024*1024,vc={pinned:!0},Ot=new Map,qt=new Map,kR=32;function ff(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function SR(e){const t=e.slice(-200),n=ff(t);if(n<=uf)return{records:t,bytes:n};let r=0,o=t.length,i=0;for(;o-r>1;){const a=Math.floor((r+o)/2),c=ff(t.slice(a));c>uf?r=a:(o=a,i=c)}return{records:t.slice(o),bytes:i}}function ER(e,t){const{records:n,bytes:r}=SR(FA(t.transcript).records);if(n.length===0){Ot.delete(e),qt.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},i={transcript:o,savedAt:Date.now(),bytes:r,owedLabels:pf(n,t.owedLabels),markLabels:pf(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>o.index.has(a))),scroll:IR(t.scroll??qt.get(e)??Ot.get(e)?.scroll??vc,o.index),busy:t.busy===!0};qt.delete(e),Ot.delete(e),Ot.set(e,i),RR()}function pf(e,t){if(!t||t.size===0)return hf;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:hf}const hf=new Set;function IR(e,t){return e.pinned?vc:t.has(e.id)?e:vc}function og(e){const t=Ot.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function AR(e){Ot.delete(e),qt.delete(e)}function UD(e,t){const n=Ot.get(e);if(n){n.scroll=t;return}for(qt.delete(e),qt.set(e,t);qt.size>kR;){const r=qt.keys().next().value;if(r===void 0)break;qt.delete(r)}}function RR(){let e=0;for(const t of Ot.values())e+=t.bytes;for(;e>wR&&Ot.size>0;){const t=Ot.keys().next().value;if(t===void 0)break;const n=Ot.get(t);Ot.delete(t),qt.delete(t),e-=n?.bytes??0}}const xR=8,TR=128,ig=new Set,CR="",ln=new Map,Ml=e=>e??CR;function BD(e){return ln.get(Ml(e))??ig}function HD(e,t,n){const r=Ml(e),o=ln.get(r)??new Set,i=new Set(o);if(n)for(i.delete(t),i.add(t);i.size>TR;){const a=i.values().next().value;if(a===void 0)break;i.delete(a)}else i.delete(t);for(ln.delete(r),i.size>0&&ln.set(r,i);ln.size>xR;){const a=ln.keys().next().value;if(a===void 0)break;ln.delete(a)}return ln.get(r)??ig}function OR(e){ln.delete(Ml(e))}const PR=128,fs=4096,ka=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),mf=e=>e.startsWith("qg:")&&e.length>3;function WD(e,t,n=null,r=[]){const o=new Map,i=new Map;for(let c=0;c<e.length;c+=1){const l=e[c];for(let d=0;d<l.segmentIds.length;d+=1){const u=l.segmentIds[d];if(o.has(u))return ka("duplicate-prior-id");if(o.size===fs)return ka("prior-id-limit");o.set(u,{ordinal:c,order:d})}l.eligible!==!1&&mf(l.key)&&t.has(l.key)&&i.size<PR&&i.set(c,l.key)}for(const c of r)if(!o.has(c)){if(o.size===fs)return ka("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&&mf(c.key)&&i.set(a.ordinal,c.key)}return{complete:!0,owners:o,keys:i,reason:null}}function GD(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>fs)return r("prior-id-limit");const o=new Set,i=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,h,_)=>{const y=a.get(f);y===void 0?a.set(f,{current:h,many:!1,lastOrder:_,reordered:!1,outside:!1}):(y.current!==h&&(y.many=!0),_<=y.lastOrder&&(y.reordered=!0),y.lastOrder=_)};for(let f=0;f<t.length;f+=1){const h=t[f];let _=null,y=!1;for(const b of h.segmentIds){if(i!==null){if(i.has(b))return r("duplicate-current-id");if(i.size===fs)return r("current-uniqueness-unproved");i.add(b)}const p=e.owners.get(b);if(p!==void 0){if(o.has(b))return r("duplicate-current-id");o.add(b),l(p.ordinal,f,p.order),_===null?_=p.ordinal:_!==p.ordinal&&(y=!0)}}if(h.eligible===!1||y||_===null||_<0)continue;const v=e.keys.get(_);v!==void 0&&c.set(f,{owner:_,key:v})}for(const f of n.outsideCurrentIds??[]){const h=e.owners.get(f);if(h===void 0||o.has(f))continue;const _=a.get(h.ordinal);_!==void 0&&(_.outside=!0)}for(const[f,h]of c){const _=a.get(h.owner),y=h.key.slice(3);(_===void 0||_.many||_.reordered||_.outside||!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 _=c.get(h);return _===void 0?f:{...f,key:_.key}}),reason:null}}const MR=8,jR="",Yn=new Map,jl=e=>e??jR;function zD(e){return Yn.get(jl(e))??null}function KD(e,t){const n=jl(e);for(Yn.delete(n),Yn.set(n,t);Yn.size>MR;){const r=Yn.keys().next().value;if(r===void 0)break;Yn.delete(r)}}function $R(e){Yn.delete(jl(e))}function DR(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const o=n.getTranscript().orderRevision??0,i=()=>(n.getTranscript().orderRevision??0)===o;try{let a=r,c=await n.readPage(a);if(!n.isCurrent()||!i())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()||!i())return{kind:"stale"};if(c.cursor_missing)return{kind:"failed",reason:"cursor-missing"}}let l=n.getTranscript();const d=n.commit(u=>(l=u,(u.orderRevision??0)!==o?u:Eo(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 i={key:n,promise:t(r,o.oldestId)};e=i;const a=()=>{e===i&&(e=null)};return i.promise.then(a,a),i.promise}}}const NR={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"},LR={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function $l(e){return{kind:e,statement:g(NR[e]),action:LR[e]}}function gf(e){return $l(zw(e))}const FR=()=>$l("historyUnreadable"),UR=new Set(["subagent_start","subagent_progress","subagent_end"]),BR=(e,t)=>({...e,[t]:(e[t]??0)+1}),HR=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=sg(n);r&&(t[r]=(t[r]??0)+1)}return t},sg=e=>{if(!e||typeof e!="object")return null;const t=e;return UR.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},WR=(e,t)=>{const n=sg(t);return n?BR(e,n):e};function _f(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 GR(e){for(const t of e)t.type==="aside_delta"&&yR.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function zR(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const zn=new Set,bo=new Set;function KR(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 VR=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),ZR=15e3,yc=[500,1e3,2e3,4e3,8e3,8e3],YR=yc.length,XR=2e4,JR=1e4,QR=1e4;function bf(e){const t=Math.max(1,Math.min(e,yc.length));return yc[t-1]??8e3}const qR=3,ex=250,tx=32*1024,vf=512,yf=new Set(["turn_end","agent_end"]),nx=3,wf=2,rx=500,kf=Pl,ox=6,Sa=ih("sessions.history"),ix=2e3,Sf={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},tr=new Map,Bi=new Map,sx=8,ax=2048,Ef=1024,cx=1024,lx="",Hn=new Map;function If(e){const t=e??lx,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>sx;){const o=Hn.keys().next().value;if(o===void 0||o===t)break;Hn.delete(o)}return r}function Ea(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function dx(e,t){return e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0||e.paintBusy===!0?!0:t}function Ia(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function ux(e,t){return Bi.set(e,t),()=>{Bi.get(e)===t&&Bi.delete(e)}}function VD(e){const t=Bi.get(e);return t?(t(),!0):!1}const Qe=new Map,fx=4,px=16;function ag(e,t){e(n=>Xm(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function hx(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 i=e.records.slice(),{skill:a,...c}=o,l=Rs(n);return i[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:i}}function wc(e,t){let n=Qe.get(e);if(!n){if(Qe.size>=px){const i=Qe.keys().next();i.done||Qe.delete(i.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>fx;){const i=n.keys().next();if(i.done)break;n.delete(i.value)}const o=tr.get(e);o&&ag(o,r)}function mx(e){if(!e)return null;const t=Qe.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function kc(e,t){const n=Qe.get(e);n&&(n.delete(t),n.size===0&&Qe.delete(e))}function Sc(e,t){const n=Qe.get(e)?.get(t);n&&(n.settled=!0)}function Af(e,t){return e?Qe.get(e)?.has(t)===!0:!1}function ZD(e){return e?(Qe.get(e)?.size??0)>0:!1}function gx(e,t,n){const r=Qe.get(e)?.get(t);if(!r)return;r.text=n;const o=tr.get(e);o&&o(i=>hx(i,t,n))}function _x(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,i]of n)i.identity=t,r.set(o,i);Qe.set(t,r)}function Ri(e){Qe.delete(e)}function bx(e,t){const n=Qe.get(e);if(n)for(const r of[...n.keys()]){const o=t.index.get(r),i=o===void 0?void 0:t.records[o];i?.kind==="user"&&i.local!==!0&&kc(e,r)}}function vx(e,t){tr.set(e,t);const n=Qe.get(e);if(n)for(const r of n.values())ag(t,r);return()=>{tr.get(e)===t&&tr.delete(e)}}function yx(e,t){const n=Qe.get(e);if(!n)return t;let r=t;for(const o of n.values())r=Xm(r,o.id,o.text,o.images,void 0,o.documents);return r}function wx(e,t,n,r=!0){return e===t||!r?!0:!n}function kx(e,t){const n=tr.get(e);if(!n)return kc(e,t),"queued";let r="queued";return n(o=>{const i=o.records[o.index.get(t)??-1];return!i||i.kind!=="user"?o:i.local?(r="retracted",Jm(o,t)):(r="owner",o)}),kc(e,t),r}function cg(e,t){const n=tr.get(e);if(!n)return"unseen";let r="unseen";return n(o=>{const i=o.records[o.index.get(t)??-1];return!i||i.kind!=="user"||(r=i.local?"local":"owner"),o}),r}function Sx(e){const t=og(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels,scroll:t.scroll,busy:t.busy}:{transcript:Ut,stale:!1,owedLabels:zn,markLabels:bo,scroll:null,busy:!1}}function Ex(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function Aa(e,t){if(e.size!==0)for(const n of t)e.delete(Ft(n))}function xi(e,t){for(const n of t)e.add(Ft(n))}const Rf=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function Ti(e,t,n){return n&&t&&mE(e.entries??[],t),e}function YD(e,t,n=!0,r=e,o={}){const i=o.openFrame===!0,a=o.journalOrder===!0,c=x.useRef(a);c.current=a;const l=x.useRef(i);l.current=i;const d=x.useRef(null),u=o.peerJournalSource===!0,f=x.useRef(u);f.current=u;const h=x.useRef(null),_=x.useRef(0),y=x.useRef(0),v=x.useRef(0),b=x.useRef(null),p=x.useRef(null),A=x.useCallback(()=>{if(!e||!c.current||!f.current)return!1;const $=Je.getState();return Tg($.sessions,$.placementFacts,e)},[e]),k=x.useCallback(()=>{const $=h.current;return A()&&$!==null&&$.sessionId===e&&$.peer},[A,e]),M=x.useCallback(()=>{const $=h.current;return $!==null&&$.sessionId===e&&$.peer},[e]),[P,W]=x.useState(()=>{const $=t&&e?Sx(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?yx(r,$?.transcript??Ut):Ut,stale:$?.stale??!1,paintScroll:$?.scroll??null,paintBusy:$?.busy??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:$?.owedLabels??zn,labelMarked:$?.markLabels??bo,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),R=x.useRef(P),m=x.useCallback($=>{const J=$(R.current);return J===R.current||(R.current=J,W(J)),J},[]);x.useEffect(()=>W_(()=>{m($=>{const{failure:J}=$;if(!J?.kind)return $;const he=$l(J.kind);return he.statement===J.statement&&he.action===J.action?$:{...$,failure:he}})}),[m]);const w=x.useRef(e),S=x.useRef(n),T=x.useRef([]),N=x.useRef(Ut.index),Y=x.useRef(new Set),X=x.useRef(new Set),E=x.useRef(If(e)),V=x.useRef(new Set),G=x.useRef(null),me=x.useRef({}),z=x.useRef(null),ye=x.useRef(null),be=x.useRef(null),Ce=x.useRef(0),$e=x.useRef(0),_t=x.useRef(0);x.useEffect(()=>{if(!e||!t)return;const $=++$e.current,J=new WeakMap;let he=null;const Le=(te,re)=>{const Se=J.get(te);if(Se===void 0||xt(re)===Se.revision)return!1;const we=te.payload.history.journal_generation;return!(typeof we=="string"&&we.length>0&&we===re.journalGeneration)};let Q=null,ht=!1,ze=0,Ee=0,Ke=0,U=0,Oe=0;const Fe=new Map;let Ve=0,Pe=0,Xe=!1;const Un=()=>{Ve&&(window.clearTimeout(Ve),Ve=0)},M_=te=>{for(const re of te)E.current.attempts.set(re,(E.current.attempts.get(re)??0)+1)},Gs=te=>{m(re=>{const Se=new Set;for(const Ue of re.labelPending)re.labelPending.has(Ue)&&(Ia(E.current,re.transcript.argsByCall,Ue,Ea(re))||Se.add(Ue));let we=null;for(const Ue of re.labelMarked)Ia(E.current,re.transcript.argsByCall,Ue,Ea(re))||(we=we??new Set(re.labelMarked),we.delete(Ue));if(Se.size===0&&!we)return re;const ie=new Set(re.labelPending);for(const Ue of Se)ie.delete(Ue);return{...re,labelPending:ie.size?ie:zn,labelMarked:we&&we.size===0?bo:we??re.labelMarked}})},j_=te=>{m(re=>{let Se=null,we=null;for(const ie of te)re.labelPending.has(ie)&&(Se=Se??new Set(re.labelPending),Se.delete(ie),we=we??new Set(re.labelMarked),we.add(ie));return!Se||!we?re:{...re,labelPending:Se.size?Se:zn,labelMarked:we}})},ui=async(te,re,Se=Sf,we=1,ie,Ue=re,qe=null)=>{Ce.current+=1,$e.current===te&&m(Me=>Me.historyReadPending?Me:{...Me,historyReadPending:!0});for(const Me of Se.targets)E.current.inFlight.add(Me),V.current.add(Me);let pe=!1;try{pe=await $_(te,re,Ue,qe,Se,we,ie)}finally{if(Ce.current=Math.max(0,Ce.current-1),Ce.current===0&&m(Me=>Me.historyReadPending?{...Me,historyReadPending:!1}:Me),!pe){for(const Me of Se.targets)E.current.inFlight.delete(Me);E.current.refused&&j_(Se.targets),Gs()}}},$_=async(te,re,Se,we,ie,Ue,qe)=>{const pe={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:Se.size===0},Me=R.current.transcript.viewEpoch,at=await D_(te,re,Se,we,ie,Ue,pe,qe);if(at||$e.current!==te||pe.reachedHeld||R.current.transcript.viewEpoch!==Me)return at;const It=re!==Se&&[...re].some(Nt=>Se.has(Nt));if(It&&pe.joined)return at;let tt;if(pe.oldest){if(!pe.hasMore)return at;tt={id:pe.oldest.id,ts:Math.round((pe.oldest.ts??0)*1e3)}}else{if(It||!we)return at;tt=we}if(!tt)return at;const Dt=m(Nt=>{const Lt=kA(Nt.transcript,tt,pe.keys);return Lt===Nt.transcript?Nt:{...Nt,transcript:Lt}});return N.current=Dt.transcript.index,at},D_=async(te,re,Se,we,ie,Ue,qe,pe)=>{const Me=R.current.transcript.viewEpoch,at=()=>R.current.transcript.viewEpoch!==Me,It=new Set;let tt,Dt=0,Nt=0,Lt=!1,kn=Se.size===0,ur=!1;const qr=R.current.cold,fr=G.current,pr=fr?{epoch:fr.epoch,seq:fr.seq}:null,At=new Set(ie.found),Bn=()=>DA(ie.order,ie.targets,At),zs=()=>Ym(ie.order,ie.targets,At),O=()=>{const ne=new Map;for(const Re of Ie){if(At.has(Re))continue;const Rt=Be.get(Re);Rt!==void 0&&ne.set(Re,Rt)}return ne},C=new Set(ie.every);for(const ne of At)C.add(ne);const Ie=new Set,Be=new Map;let vt=1;const Z=ie.targets.size>0;let hr=Math.max(rf(Bn()),Z?E.current.depth:0),_e=0;for(;Dt<kf&&Nt<ox;){Nt+=1;let ne;const Re=ic(R.current.transcript),Rt=Re.revision;try{ne=await Ge({op:"sessions.history",sessionId:e,...tt?{beforeId:tt}:{},limit:Math.min(hr,kf-Dt),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Jt(R.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}}),Ti(ne,e,l.current)}catch{if(at())return!1;if(R.current.transcript.records.length>0){if(_e++>0)return E.current.refused=!0,!1;continue}return Ue<qR?(Oe=window.setTimeout(()=>{if(Oe=0,$e.current!==te||at()){Gs();return}ui(te,re,ie,Ue+1,pe,Se,we)},bf(Ue)),!0):(m(Te=>({...Te,status:"unavailable",failure:FR(),heldFrontend:null,...Te.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{Gs()}if($e.current!==te||at())return!1;if(xt(R.current.transcript)!==Rt){if(!R.current.hydrated)continue;return!1}E.current.refused=!1;const Zt=ne.entries[0];Dt+=ne.entries.length,pe?.(ne.entries.length),Aa(Y.current,ne.entries),xi(X.current,ne.entries),m(Te=>{if(xt(Te.transcript)!==Rt)return Te;const Yt=Eo(Te.transcript,ne,{authoritative:!0,orderRead:Re,peerSource:M(),readWitness:pr}),mr=va(ne.entries,C),Vs=new Set(Te.labelPending);for(const F_ of mr)Vs.delete(F_);return{...Te,hydrated:Te.hydrated||ne.entries.length>0||!qr,labelPending:Vs.size?Vs:zn,labelMarked:KR(Te.labelMarked,mr),transcript:Yt}}),e&&tt===void 0&&Je.getState().resolveHeldFromServer(e,ne.entries,!ne.cursor_missing);const fi=Bn();for(const Te of va(ne.entries,C))At.add(Te),C.add(Te);if(PA(ne.entries)&&(ur=!0),Z){const Te=MA(ne.entries,C);for(const Yt of Te)Ie.add(Yt),C.add(Yt);for(const[Yt,mr]of TA(ne.entries,Te))Be.set(Yt,mr);for(const Yt of[...Ie])At.has(Yt)&&Ie.delete(Yt);Ie.size>0&&vt--<=0&&Ie.clear()}Lt=Lt||re.size===0||ne.entries.some(Te=>re.has(Ft(Te))||It.has(Te.id)),kn=kn||ne.entries.some(Te=>Se.has(Ft(Te)));for(const Te of ne.entries)It.add(Te.id);for(const Te of ne.entries)qe.keys.add(Ft(Te));Zt&&(qe.oldest=Zt),qe.hasMore=ne.has_more,qe.joined=Lt,qe.reachedHeld=kn;const Ks=Bn()+Ie.size;Z&&Bn()<fi&&(E.current.depth=Math.min(Pl,Math.max(E.current.depth,Dt)));let kd=!1;if(Z){const Te=zs();kd=CA(ne.entries,Te,ie.starts,O(),new Set(Te.filter(mr=>ie.waiting.has(mr))))||ur}if(jA(Lt&&kn,kd?0:Ks)||!Zt||!ne.has_more)return!1;tt=Zt.id,hr=Ks>0?rf(Ks):_c}return!1},bd=()=>{if(ze&&cancelAnimationFrame(ze),Ee&&clearTimeout(Ee),ze=0,Ee=0,$e.current!==$)return;const te=T.current;if(T.current=[],te.length===0)return;const re=new Set,Se=new Map;for(const O of Y.current)R.current.transcript.index.has(O)||Y.current.delete(O);for(const O of X.current)R.current.transcript.index.has(O)||X.current.delete(O);for(const O of R.current.transcript.records)Tl(O)&&!Y.current.has(O.id)&&(re.add(O.id),Se.set(O.id,X.current.has(O.id)?O.ts:null));let we=null;for(const O of te){if(O.type!=="snapshot")continue;const C=O.payload.history,Ie=C.entries[0];if(!Ie||!C.has_more)continue;const Be=Math.round((Ie.ts??0)*1e3);Be>0&&(!we||Be<we.ts)&&(we={id:Ie.id,ts:Be})}GR(te);const ie=O=>{const C=O.payload.history.entries,Ie=C.at(-1);if(!Ie)return!1;if(Ex(O.payload)){if(re.size===0)return!0;const Be=new Set;for(const vt of C)Be.add(Ft(vt));return C.some(vt=>re.has(Ft(vt)))?!0:B0(O.payload.history,Se,Be)}return Ie.id===O.payload.frontend.snapshot.history_cursor?!1:re.has(Ft(Ie))},Ue=O=>O!=null&&N.current.has(O);let qe=!1;const pe=G0(te.flatMap(O=>O.type==="frontend.update"?[O.payload]:[]),R.current.frontend?.jobs??[],R.current.transcript.records,O=>N.current.has(O)).filter(O=>(Fe.get(O)??0)<nx);for(const O of pe)Fe.set(O,(Fe.get(O)??0)+1);const Me=pe.length>0||te.some(O=>O.type==="attention"?!Ue(O.payload.anchor_id):O.type==="snapshot"&&!ie(O)),at=R.current.cold&&!R.current.hydrated&&te.some(O=>O.type==="snapshot"||O.type==="frontend.replace"||O.type==="frontend.update"?O.payload.cold===!1:!1),It=new Set(R.current.transcript.argsByCall.keys()),tt=[],Dt=new Set;for(const O of te){if(O.type!=="snapshot")continue;const C=Le(O,R.current.transcript);C||xi(X.current,O.payload.history.entries);for(const Ie of O.payload.history.entries){C||Dt.add(Ft(Ie));const Be=Ie.payload?.tool_calls;if(Array.isArray(Be))for(const vt of Be)vt&&typeof vt.id=="string"&&It.add(vt.id)}for(const Ie of O.payload.frontend.snapshot.live_events??[]){const Be=Ie.message;!C&&typeof Be?.id=="string"&&Dt.add(Be.id)}tt.push(...O.payload.frontend.snapshot.live_events??[])}if(pe.length>0)for(const O of R.current.transcript.index.keys())Dt.add(O);const Nt=te.some(O=>O.type==="event"&&yf.has(String(O.payload.type??""))),Lt=nf(E.current.attempts,tf(tt,It),It,wf),kn=Nt?nf(E.current.attempts,[...E.current.attempts.keys(),...E.current.settled],It,wf):[],ur=[];for(const O of te){if(O.type!=="event")continue;const C=O.payload;String(C.type??"")==="tool_execution_end"&&String(C.tool_call_id??"")&&ur.push(C)}const qr=[];for(const O of ur){const C=String(O.tool_call_id??"");It.has(C)||E.current.settled.has(C)||qr.push(C)}for(const O of qr)E.current.settled.add(O);for(;E.current.settled.size>vf;){const O=E.current.settled.values().next().value;if(O===void 0)break;E.current.settled.delete(O)}for(const[O,C]of ef(ur))E.current.starts.set(O,C);for(;E.current.starts.size>Ef;){const O=E.current.starts.keys().next().value;if(O===void 0)break;E.current.starts.delete(O)}const fr=E.current.settleRows<rx?qr:[],pr=[...new Set([...Lt,...kn,...fr])],At=pr.filter(O=>!E.current.painted.has(O));if(tt.length>0){E.current.order=tf(tt,new Set);for(const[O,C]of ef(tt))E.current.starts.set(O,C);for(;E.current.starts.size>Ef;){const O=E.current.starts.keys().next().value;if(O===void 0)break;E.current.starts.delete(O)}for(const O of RA(tt))E.current.waiting.add(O);for(const O of $A(tt))E.current.waiting.delete(O);for(;E.current.waiting.size>cx;){const O=E.current.waiting.values().next().value;if(O===void 0)break;E.current.waiting.delete(O)}}for(const O of[...E.current.attempts.keys()])It.has(O)&&E.current.attempts.delete(O);for(M_([...Lt,...kn]);E.current.attempts.size>vf;){const O=E.current.attempts.keys().next().value;if(O===void 0)break;E.current.attempts.delete(O)}if(performance.mark("lop:transcript:flush:start"),m(O=>{let C={...O},Ie=C.frontend!==null;qe=!1;let Be=null;const vt=Date.now();for(const Z of te){if(Z.type==="heartbeat")continue;if(Z.type==="gap"){he=null,C={...C,frontend:null,heldFrontend:C.frontend??C.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:of(C.transcript)},Ie=!1;continue}if(Z.type==="open")he=null;else if("seq"in Z){const _e={epoch:Z.epoch,seq:Z.seq},ne=Rf(Z);if(!ne&&!Ww(he,_e,{allowEqual:Z.type==="snapshot"}))continue;ne||(he=_e)}const hr=G.current;if((Z.type==="open"||"seq"in Z)&&!Rf(Z)&&(G.current={epoch:Z.epoch,seq:Z.seq},C={...C,receipt:G.current}),Z.type==="open"){if(C={...C,subscriptionId:Z.payload.subscription_id},Z.payload.gap){const _e=C.frontend??C.heldFrontend;C={...C,frontend:null,heldFrontend:_e,history:null,transcript:of(C.transcript)},_e&&C.status==="live"&&(C={...C,status:"reconnecting"}),Ie=!1}continue}if(!Ie){if(Z.type==="event"&&(Be=gc(Be??C.transcript,Z.payload,vt,{frame:{epoch:Z.epoch,seq:Z.seq}})),Z.type==="snapshot"){const _e=J.get(Z),ne=Le(Z,C.transcript);ne&&(qe=!0);const Re=Z.payload,Rt=!Re.history.cursor_missing&&!ne;let Zt=Be??C.transcript;Rt&&(performance.mark("lop:open:history:start"),Ti(Re.history,d.current,d.current!==null),Zt=Eo(Zt,Re.history,{authoritative:!0,orderRead:_e,peerSource:M(),readWitness:{epoch:Z.epoch,seq:Z.seq}}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),Aa(Y.current,Re.history.entries),xi(X.current,Re.history.entries)),e&&Je.getState().resolveHeldFromServer(e,Re.history.entries,Rt),performance.mark("lop:open:seed:start"),Zt=AA(Zt,Re.frontend.snapshot,vt,{epoch:Z.epoch,seq:Z.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const fi=_f(C.frontend??C.heldFrontend,Re.frontend.snapshot,Re.cold===!0||Re.attaching===!0);C={...C,contextCarried:Object.keys(fi).length>0,subagentPulses:HR(Re.frontend.snapshot.live_events),status:"live",stale:!1,paintBusy:!1,paintScroll:null,frontend:{...Re.frontend.snapshot,...fi,attention:Tr(C.frontend?.attention,Re.frontend.snapshot.attention,e)},history:ne?C.history:Re.history,cold:Re.cold,ownerEpoch:Re.frontend.epoch,failure:null,hydrated:C.hydrated||Rt&&Re.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:Zt},Ie=!0,Be=null}continue}if(Z.type==="attention"){C.frontend&&(C={...C,frontend:{...C.frontend,attention:Tr(C.frontend.attention,Z.payload,e)}});continue}if(Z.type==="frontend.update"){const _e=Z.payload,ne=_e.changes??{};if((_e.degraded===!0||_e.paused===!0)&&(C={...C,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!C.frontend)continue;const Re=_e.epoch!==C.ownerEpoch&&ne.epoch===_e.epoch,Rt=_e.changes!==void 0&&ne.epoch===_e.epoch;(Re||_e.epoch===C.ownerEpoch&&(C.frontend.sequence<_e.sequence||C.frontend.sequence===_e.sequence&&Rt))&&(C={...C,contextCarried:!1,ownerEpoch:Re?_e.epoch:C.ownerEpoch,frontend:{...C.frontend,...ne,...ne.jobs==null&&_e.job_deltas?{jobs:gh(C.frontend.jobs??[],_e.job_deltas)}:{},attention:Tr(C.frontend.attention,ne.attention,e),sequence:_e.sequence},...typeof _e.cold=="boolean"?{cold:_e.cold}:{}},Rt&&C.liveUpdatesNotice==="update"&&C.liveUpdatesPaused&&(C={...C,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(Z.type==="frontend.replace"){if(C.frontend&&Gw(hr,e,Z)){const _e=Z.payload.frontend,ne=_f(C.frontend,_e.snapshot,Z.payload.cold===!0);C={...C,contextCarried:Object.keys(ne).length>0,frontend:{..._e.snapshot,...ne,attention:Tr(C.frontend.attention,_e.snapshot.attention,e)},ownerEpoch:_e.epoch,cold:Z.payload.cold,...C.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(Z.type==="event"){const _e=String(Z.payload.type??"");if(Z.payload.action==="reload"){C={...C,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}VR.has(_e)&&(C={...C,terminal:_e}),yf.has(_e)&&(C={...C,turnsCompleted:C.turnsCompleted+1});const ne=gc(C.transcript,Z.payload,vt,{frame:{epoch:Z.epoch,seq:Z.seq},userStoppedAt:e?Je.getState().stoppedTurns[e]??null:null,queuedAskEngine:Hm(C.frontend)});ne!==C.transcript&&(C={...C,transcript:ne});const Re=WR(C.subagentPulses,Z.payload);Re!==C.subagentPulses&&(C={...C,subagentPulses:Re})}}if(!Ie&&Be){for(const Z of Be.index.keys())C.transcript.index.has(Z)||Y.current.add(Z);C={...C,transcript:Be}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),N.current=C.transcript.index,!zR(te))return O;if(At.length>0){const Z=new Set(C.labelPending);for(const hr of At)Z.add(hr);C={...C,labelPending:Z}}return C.frontend!==null&&C.frontend!==C.heldFrontend&&(C={...C,heldFrontend:C.frontend}),C}),At.length>0){for(const O of At)E.current.painted.add(O);for(;E.current.painted.size>ax;){const O=E.current.painted.values().next().value;if(O===void 0)break;E.current.painted.delete(O)}}const Bn=Me||qe,zs=fr.length>0&&Lt.length===0&&kn.length===0&&!Bn&&!at;if(Bn||pr.length>0||at){const O=new Set(pr),C=E.current.order;ui($,Dt,pr.length>0?{targets:O,order:C,starts:E.current.starts,waiting:E.current.waiting,every:new Set([...C,...O]),found:new Set(va(te.flatMap(Ie=>Ie.type==="snapshot"?Ie.payload.history.entries:[]),new Set(C))),pending:At}:Sf,1,zs?Ie=>{E.current.settleRows+=Ie}:void 0,re,we)}if(M0())for(const O of te)"epoch"in O&&"seq"in O&&j0({carrier:"canonical-sse",sessionId:e,epoch:O.epoch,seq:O.seq,disposition:"processed"})},Jr=()=>{const te=Q;if(Q=null,h.current=null,_.current+=1,y.current&&(window.clearTimeout(y.current),y.current=0),v.current+=1,!!te){ht=!0;try{te()}finally{ht=!1}}},Qr=()=>{const te=ic(R.current.transcript),re=Fr.currentToken(),Se=++_t.current;Un(),Ve=window.setTimeout(()=>{Ve=0,$e.current===$&&(Jr(),m(ie=>({...ie,subscriptionId:null,status:"unavailable",failure:gf(ko.ended),...ie.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Xe&&(Xe=!0,Pe=window.setTimeout(()=>{Pe=0,$e.current===$&&yd()},JR)))},XR);const we=A();d.current=l.current?e??null:null,Q=f0({sessionId:e,epoch:me.current.epoch,afterSeq:me.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:Jt(R.current.transcript).slice(0,512),...we?{peerJournalSource:!0}:{}}:{}},ie=>{if($e.current===$&&_t.current===Se){if(ie.kind==="error"||ie.kind==="end"){if(ht)return;if(Un(),Jr(),ie.kind==="error"&&ie.status===404){if(!n){e&&Je.getState().retireDraftWarm(e),m(pe=>({...pe,subscriptionId:null}));return}e&&(AR(e),OR(e),$R(e),Je.getState().retireDraftsForSession(e)),m(pe=>({...pe,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...pe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),e&&Je.getState().temporaryChats&&Ge({op:"sessions.get",sessionId:e}).catch(pe=>{$e.current===$&&(!(pe instanceof Ae)||!ZA(pe.code)||m(Me=>Me.missing?{...Me,temporaryDeleted:!0}:Me))});return}const Ue=ie.kind==="error"?ie.detail??g("ui.common.errors.event_stream_failed"):g("ui.common.errors.event_stream_closed");if(m(pe=>({...pe,subscriptionId:null})),Ke>=YR){m(pe=>({...pe,status:"unavailable",failure:gf(Ue),...pe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}Ke+=1;const qe=G.current;qe&&(me.current={epoch:qe.epoch,afterSeq:qe.seq}),m(pe=>pe.status==="unavailable"&&Ke>1?pe:{...pe,status:"reconnecting",failure:null}),U=window.setTimeout(()=>{U=0,$e.current===$&&Qr()},bf(Ke));return}if(ie.data!==void 0)try{const Ue=ie.data,qe=ie.receipt?performance.now():0,pe=Ue.length>=tx;pe&&performance.mark("lop:open:parse:start");const Me=JSON.parse(Ue),at=ie.receipt?performance.now():0;Me.type==="snapshot"&&J.set(Me,te),pe&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),Me.type==="snapshot"&&(ie.receipt&&console.warn(Xw(ie.receipt,re,qe,at)),Fr.note(e,"snapshot",re),Ke=0,Un(),Xe=!1),T.current.push(Me),ze||(ze=requestAnimationFrame(bd)),Ee||(Ee=window.setTimeout(bd,ex))}catch{}}},ie=>{ie==="requested"&&Fr.note(e,"request",re)}),h.current={sessionId:e,peer:we},_.current+=1},vd=()=>{U!==0&&(window.clearTimeout(U),U=0),me.current={},G.current=null,Jr(),Qr()},yd=()=>{Ke=0,Pe&&(window.clearTimeout(Pe),Pe=0),U&&(window.clearTimeout(U),U=0),Oe&&(window.clearTimeout(Oe),Oe=0),m(te=>({...te,failure:null,status:te.status==="unavailable"?"connecting":te.status,transcript:Ii(te.transcript,!1)})),R.current.hydrated||ui($,new Set(R.current.transcript.index.keys())),!Q&&Qr()};Qr(),z.current=yd,ye.current=()=>{R.current.liveUpdatesReloading||(m(te=>({...te,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Ke=0,U&&(window.clearTimeout(U),U=0),Pe&&(window.clearTimeout(Pe),Pe=0),vd())},be.current=()=>{!R.current.hydrated&&Ce.current===0&&ui($,new Set(R.current.transcript.index.keys()))};const N_=ux(e,vd),wd=()=>{if(!t||!e||b.current===e)return;const te=h.current;te===null||te.sessionId!==e||te.peer||A()&&(b.current=e,Jr(),Qr())};p.current=wd;const L_=Je.subscribe(()=>{wd()});return()=>{$e.current+=1,z.current=null,be.current=null,ye.current=null,p.current=null,L_(),y.current&&(window.clearTimeout(y.current),y.current=0),N_(),Jr(),ze&&cancelAnimationFrame(ze),Ee&&clearTimeout(Ee),U&&clearTimeout(U),Oe&&clearTimeout(Oe),le.current&&(window.clearTimeout(le.current),le.current=0),ke.current&&(window.clearTimeout(ke.current),ke.current=0),Pe&&window.clearTimeout(Pe),Un(),T.current=[]}},[m,e,t,n,a,A,k,M]),x.useEffect(()=>{!e||!t||p.current?.()},[e,t,u]),x.useEffect(()=>{me.current={},G.current=null,N.current=Ut.index;const $=wx(w.current,e,n,S.current);w.current=e,S.current=n;const J=e?og(e):null;N.current=$?R.current.transcript.index:(J?.transcript??Ut).index;const he=new Set($?Y.current:[]);for(const Q of J?.replayBorn??[])he.add(Q);const Le=$?R.current.transcript.index:(J?.transcript??Ut).index;for(const Q of he)Le.has(Q)||he.delete(Q);Y.current=he,$||(X.current=new Set),m(Q=>({...Q,frontend:null,heldFrontend:$?Q.heldFrontend:null,contextCarried:$?Q.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:$?Q.turnsCompleted:0,transcript:$?Q.transcript:J?.transcript??Ut,stale:$?Q.stale:J!==null,paintScroll:$?null:J?.scroll??null,paintBusy:$?Q.paintBusy:J?.busy===!0,missing:$?Q.missing:!1,temporaryDeleted:$?Q.temporaryDeleted:void 0,status:"connecting",subagentPulses:{},labelPending:J?.owedLabels??zn,labelMarked:J?.markLabels??bo,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),E.current=If(e)},[e,n]);const jt=x.useRef(r);jt.current=r,x.useEffect(()=>{if(e)return()=>{const $=R.current.transcript;$.records.length>0&&ER(e,{transcript:$,owedLabels:new Set([...R.current.labelPending].filter(J=>Ia(E.current,R.current.transcript.argsByCall,J,Ea(R.current)))),markLabels:new Set(R.current.labelMarked),replayBorn:new Set(Y.current),busy:dx(R.current,mx(jt.current)!==null)});for(const J of V.current)E.current.inFlight.delete(J);V.current.clear()}},[e]);const le=x.useRef(0);x.useEffect(()=>{if(P.labelPending.size===0&&P.labelMarked.size===0){le.current&&(window.clearTimeout(le.current),le.current=0);return}if(le.current)return;const $=()=>{le.current=0;const J=R.current.labelPending,he=R.current.labelMarked;if(J.size===0&&he.size===0)return;const Le=E.current;for(const Q of J)if(Le.inFlight.has(Q)){le.current=window.setTimeout($,Sa);return}for(const Q of he)if(Le.inFlight.has(Q)){le.current=window.setTimeout($,Sa);return}m(Q=>Q.labelPending.size===0&&Q.labelMarked.size===0?Q:{...Q,labelPending:zn,labelMarked:bo})};le.current=window.setTimeout($,Sa)},[m,P.labelPending,P.labelMarked]);const ke=x.useRef(0);x.useEffect(()=>{if(P.labelPending.size===0){ke.current&&(window.clearTimeout(ke.current),ke.current=0),m($=>$.labelHoldLate?{...$,labelHoldLate:!1}:$);return}P.labelHoldLate||ke.current||(ke.current=window.setTimeout(()=>{ke.current=0,m($=>$.labelPending.size===0||$.labelHoldLate?$:{...$,labelHoldLate:!0})},ix))},[m,P.labelPending,P.labelHoldLate]);const et=x.useRef(e);et.current=e;const Ne=x.useRef({id:e,epoch:0});Ne.current.id!==e&&(Ne.current={id:e,epoch:Ne.current.epoch+1});const Et=x.useRef(null);Et.current===null&&(Et.current=DR());const ge=x.useRef(!1),xe=x.useRef(null),[pt,$t]=x.useState(0);x.useEffect(()=>{const $=P.transcript,J=Jt($);if(!e||!a||!$.orderNeedsReconcile&&(!$.journalGeneration||J.length===0)||ge.current)return;const he=U=>({fields:JSON.stringify([pt,e,U.viewEpoch,xt(U),U.orderNeedsReconcile,U.orderWantedGeneration,Jt(U)]),demand:U.orderDemand}),Le=he($);if(xe.current?.fields===Le.fields&&xe.current.demand===Le.demand)return;xe.current=Le;const Q=e,ht=$.viewEpoch;ge.current=!0;let ze=null,Ee=$;const Ke=U=>{if(!U.peer||et.current!==Q||R.current.transcript.viewEpoch!==ht||_.current!==U.streamEpoch)return;const Oe=U.kind==="authority"?U.frame.payload.history:U.page,Fe=Oe.journal_order_state;if(Fe==="ready"){y.current&&(window.clearTimeout(y.current),y.current=0),m(Pe=>{const Xe=Ii(Pe.transcript,!1);return Xe===Pe.transcript?Pe:{...Pe,transcript:Xe}});return}if(Fe==="unavailable"){if(y.current&&(window.clearTimeout(y.current),y.current=0),Oe.reconcile===!0)return;m(Pe=>{const Xe=Ii(Pe.transcript,!0);return Xe===Pe.transcript?Pe:{...Pe,transcript:Xe}});return}if(Fe!=="building")return;y.current&&(window.clearTimeout(y.current),y.current=0);const Ve=++v.current;y.current=window.setTimeout(()=>{y.current=0,v.current===Ve&&et.current===Q&&R.current.transcript.viewEpoch===ht&&_.current===U.streamEpoch&&m(Pe=>{const Xe=Ii(Pe.transcript,!0);return Xe===Pe.transcript?Pe:{...Pe,transcript:Xe}})},QR)};F0({getTranscript:()=>R.current.transcript,isCurrent:()=>et.current===Q&&R.current.transcript.viewEpoch===ht,sweep:(U,Oe)=>{if(!k())return;if(U.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${Q}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const Fe=U.journalGeneration;if(typeof Fe!="string"||Fe.length===0)return{kind:"none",path:`/v1/desktop/sessions/${Q}/history`,query:new URLSearchParams};if(Eh(U,Oe?.("lookup")).length>0){const Xe=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:Fe});return{kind:"lookup",path:`/v1/desktop/sessions/${Q}/history`,query:Xe}}if(ll(U).length>0){const Xe=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:Fe});return{kind:"payload",path:`/v1/desktop/sessions/${Q}/history`,query:Xe}}return{kind:"none",path:`/v1/desktop/sessions/${Q}/history`,query:new URLSearchParams}},read:async(U,Oe)=>{Ee=R.current.transcript,xe.current=he(Ee);const Fe=k(),Ve=_.current;if(Oe==="lookup"||Oe==="payload"){const Xe=R.current.transcript.journalGeneration,Un=await Ge({op:"sessions.history",sessionId:Q,limit:100,journalOrder:!0,orderIds:U,peerJournalSource:!0,sourceRead:Oe==="payload"?"payload":"metadata",...typeof Xe=="string"&&Xe.length>0?{expectedJournalGeneration:Xe}:{}});return Oe==="payload"?{kind:"payload",page:Un,peer:Fe,streamEpoch:Ve}:{kind:"lookup",page:Un,peer:Fe,streamEpoch:Ve}}return{kind:"authority",frame:await Ge({op:"sessions.get",sessionId:Q,journalOrder:!0,orderIds:U,...Fe?{peerJournalSource:!0}:{}}),peer:Fe,streamEpoch:Ve}},page:U=>U.kind==="authority"?U.frame.payload.history:U.page,lookupPath:`/v1/desktop/sessions/${Q}`,commit:(U,Oe,Fe)=>{U.peer&&_.current!==U.streamEpoch||(m(Ve=>et.current!==Q||xt(Ve.transcript)!==Oe||Ve.transcript.viewEpoch!==ht?Ve:{...Ve,transcript:U.kind==="authority"?U.peer?qu(Ve.transcript,U.frame.payload.history,{authoritative:!0,orderRead:Fe}):vA(Ve.transcript,U.frame.payload.history,Fe):U.kind==="payload"?yA(Ve.transcript,U.page,Fe,Oe):qu(Ve.transcript,U.page,{authoritative:!1})}),Ke(U))}}).then(U=>{ze=U.kind==="complete"?U.transcript:null}).catch(U=>{console.warn("[canonical] source-order reconcile refused",U)}).finally(()=>{ge.current=!1;const U=R.current.transcript,Oe=ze??Ee;ze&&et.current===Q&&U.viewEpoch===ht&&!U.orderNeedsReconcile&&(xe.current=he(Oe)),(et.current!==Q||U.viewEpoch!==ht||xt(U)!==xt(Oe)||U.orderWantedGeneration!==Oe.orderWantedGeneration||U.orderNeedsReconcile!==Oe.orderNeedsReconcile||U.orderDemand!==Oe.orderDemand||JSON.stringify(Jt(U))!==JSON.stringify(Jt(Oe)))&&$t(Fe=>Fe+1)})},[m,e,a,k,P.transcript,pt]);const bt=x.useCallback(async()=>{const $=Et.current;if(!e||!$)return{kind:"nothing-to-load"};const J=e,he=Ne.current.epoch,Le=()=>Ne.current.epoch===he,Q=R.current.transcript.viewEpoch,ht=()=>R.current.transcript.viewEpoch===Q,ze=await $.load(`${J}#${he}`,{getTranscript:()=>R.current.transcript,readPage:Ee=>{const Ke=l.current;return Ge({op:"sessions.history",sessionId:J,beforeId:Ee,limit:100,openFrame:Ke,...c.current?{journalOrder:!0,orderIds:Jt(R.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}}).then(U=>Ti(U,J,Ke))},isCurrent:()=>Le()&&ht(),commit:Ee=>m(Ke=>{const U=Ee(Ke.transcript);return U===Ke.transcript?Ke:{...Ke,transcript:U}}).transcript,setLoading:Ee=>{Le()&&m(Ke=>Ke.loadingOlder===Ee?Ke:{...Ke,loadingOlder:Ee})},peerSource:M});return Le()&&(ze.kind==="failed"?m(Ee=>Ee.olderFailed?Ee:{...Ee,olderFailed:!0}):ze.kind==="applied"&&m(Ee=>Ee.olderFailed?{...Ee,olderFailed:!1}:Ee)),ze},[m,e,k,M]),Xr=x.useCallback(async()=>(await bt()).kind==="applied",[bt]),Fn=x.useRef(!1),dd=x.useCallback(async($,J)=>{if(!e||Fn.current)return!1;const he=e;Fn.current=!0;const Le=xt(R.current.transcript),Q=G.current,ht=Q?{epoch:Q.epoch,seq:Q.seq}:null;try{const ze=await Ge({op:"sessions.history",sessionId:he,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Jt(R.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}});return Ti(ze,he,l.current),et.current!==he||xt(R.current.transcript)!==Le||R.current.transcript.viewEpoch!==J?!1:(m(Ee=>xt(Ee.transcript)!==Le?Ee:{...Ee,transcript:Eo(Ee.transcript,ze,{keepPaging:!0,peerSource:M(),readWitness:ht})}),Aa(Y.current,ze.entries),xi(X.current,ze.entries),JA(ze.entries,$))}catch{return!1}finally{Fn.current=!1}},[m,e,k,M]);x.useEffect(()=>r?vx(r,J=>{m(he=>{const Le=J(he.transcript);return Le===he.transcript?he:{...he,transcript:Le}})}):void 0,[m,r]),x.useEffect(()=>{r&&bx(r,P.transcript)},[r,P.transcript]);const ud=x.useCallback(()=>{m($=>({...$,transcript:NA($.transcript),olderFailed:!1,heldFrontend:null}))},[m]),fd=x.useCallback(()=>{z.current?.()},[]),pd=x.useCallback(()=>{ye.current?.()},[]),hd=x.useCallback(()=>{be.current?.()},[]),md=x.useCallback(($,J="info")=>{m(he=>({...he,transcript:UA(he.transcript,$,J)}))},[m]),gd=x.useCallback($=>{m(J=>({...J,pendingModel:$}))},[m]),_d=x.useCallback(()=>{m($=>$.pendingModel===null?$:{...$,pendingModel:null})},[m]);return x.useEffect(()=>{const $=P.pendingModel;if(!$)return;const J=bc($);if(!J)return;const he=P.frontend;fR(he,J)&&m(Le=>({...Le,pendingModel:null}))},[m,P.frontend,P.pendingModel]),x.useEffect(()=>{if(!P.pendingModel)return;const $=window.setTimeout(()=>m(J=>({...J,pendingModel:null})),ZR);return()=>window.clearTimeout($)},[m,P.pendingModel]),x.useMemo(()=>({...P,awaitingHydration:t&&!!e&&n&&!P.hydrated,loadOlder:Xr,loadOlderDetailed:bt,refreshTail:dd,clearView:ud,addNote:md,paintPendingModel:gd,clearPendingModel:_d,retry:fd,rehydrate:hd,reloadFromHistory:pd}),[P,t,e,n,Xr,bt,dd,ud,md,gd,_d,fd,hd,pd])}function Ps(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
41
-
42
- `)?e:`${t}
43
-
44
- ${e}`}const Ra={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function Hi(e,t,n){const r=[...e.attachments??[]],o=[],i=[],a=new Set;for(const h of t.attachments){const _=r.find(v=>v.path===h&&!a.has(v.id));if(_){a.add(_.id),i.push(_.id);continue}const y={id:n(),path:h};o.push(y),i.push(y.id)}const c=[...e.replies??[]],l=t.replies.filter(h=>!c.some(_=>_.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:Ps(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:i,replyIds:t.replies.map(h=>f.find(_=>_.id===h.id)?.id).filter(h=>h!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function Ix(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 Ax(e){return{text:Ps(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function Rx(e,t){if(!e||!t)return!1;const n=Ax(e),r=e.attachments??[],o=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((i,a)=>i.id===t.chipIds[a])&&o.length===t.replyIds.length&&o.every((i,a)=>i.id===t.replyIds[a])}function xx(e,t=()=>crypto.randomUUID()){const n={};for(const[r,o]of Object.entries(e??{}))n[r]=o.inFlight?Hi(o,o.inFlight,t):o;return n}function Tx(e,t){const n=t.text,r=Ps(e.currentInput??"",e.pendingText??"");let o=r,i="overlap";n===""?i="draft-only":r.startsWith(n)&&(o=r.slice(n.length).replace(/^\n+/,""),i="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:i}}const Cx=300,lg="conversation-input-store";let Yo=null,dg=lg,yt=null,xa=!1;const Ec=()=>{try{return globalThis.localStorage??null}catch{return null}},Io=()=>{yt!==null&&(clearTimeout(yt),yt=null);const e=Yo;if(!e)return;const t=dg,n=Ec();if(n){try{n.setItem(t,JSON.stringify(e))}catch(r){xa||(xa=!0,console.warn("[composer] the draft could not be persisted; it stays in memory for this session",r));return}Yo=null,xa=!1}},XD=()=>{Io()},JD=()=>{Yo=null,yt!==null&&(clearTimeout(yt),yt=null)},Ox={getItem:e=>{const t=Ec();if(!t)return null;const n=t.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}},setItem:(e,t)=>{Yo=t,dg=e,yt!==null&&clearTimeout(yt),yt=setTimeout(()=>{yt=null,Io()},Cx)},removeItem:e=>{Yo=null,yt!==null&&(clearTimeout(yt),yt=null),Ec()?.removeItem(e)}};typeof window<"u"&&typeof window.addEventListener=="function"&&(window.addEventListener("pagehide",Io),window.addEventListener("beforeunload",Io),window.document?.addEventListener("visibilitychange",()=>{window.document.visibilityState==="hidden"&&Io()}));const lt=oi()(Is((e,t)=>({inputByConversation:{},addReply:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(o.replies)?o.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...o,replies:[...i,r]}}})},removeReply:(n,r)=>{const o=t().inputByConversation[n];o&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,replies:o.replies.filter(i=>i.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:[]},i=Array.isArray(o.attachments)?o.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...o,attachments:[...i,r]}}})},removeAttachment:(n,r)=>{const o=t().inputByConversation[n];o&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,attachments:o.attachments.filter(i=>i.id!==r)}}})},clearAttachments:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[]}}})},setCurrentInput:(n,r,o=0)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...i,lateDelivered:i.lateDelivered==="overlap"&&!Ix(i,r)?void 0:i.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:[]},i=o.submittedMessages[o.submittedMessages.length-1],a=r&&r!==i?[...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:[]},i=o.submittedMessages;let a=null;typeof r=="number"&&i.length>0&&(a=Math.max(0,Math.min(r,i.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 i=t().inputByConversation[n]??Ra,a=new Set(r.attachments.map(d=>d.id)),c=new Set(r.replies.map(d=>d.id)),l=i.currentInput===r.text;e({inputByConversation:{...t().inputByConversation,[n]:{...i,currentInput:l?"":i.currentInput,unredactedChars:l?0:i.unredactedChars,textRevision:l?(i.textRevision??0)+1:i.textRevision,attachments:(i.attachments??[]).filter(d=>!a.has(d.id)),replies:(i.replies??[]).filter(d=>!c.has(d.id)),inFlight:o?{text:r.text,attachments:r.attachments.map(d=>d.path),replies:[...r.replies],unredactedChars:l?i.unredactedChars:0,volatileText:r.volatileText}:i.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const r={...t().inputByConversation};let o=!1;for(const i of n){const a=r[i];!a||!a.inFlight&&!a.returned||(r[i]={...a,inFlight:void 0,returned:void 0},o=!0)}o&&e({inputByConversation:r})},returnInFlight:(n,r)=>{const o={...t().inputByConversation},i=o[n],a=i?.inFlight??o[r]?.inFlight;let c=o[r]??Ra;n!==r&&i&&(c=Hi(c,{text:i.currentInput??"",attachments:(i.attachments??[]).map(l=>l.path),replies:i.replies??[],unredactedChars:i.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:o[r]?.returned},delete o[n]),a&&(c=Hi(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=Ps(r.currentInput??"",r.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:o,pendingText:void 0,textRevision:(r.textRevision??0)+1}}}),o},returnPayload:(n,r)=>{const o=t().inputByConversation[n]??Ra;o.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:Hi(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,i=r.returned!==void 0||r.inFlight!==void 0,a=r.returned?Rx(r,r.returned):o(r),c=r.returned?Tx(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:i&&r.returned?.text?"overlap":i?"delivered":void 0,lateDeliveredText:i?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:lg,storage:Ox,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:xx(e?.inputByConversation)})}));function ug(e){if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null}function QD(e,t){return t?e.filter(n=>n.session_id===t&&fg(n)).length:0}function fg(e){if(ug(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function Px(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function qD(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 eN={cwd:""};function Mx(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,Px(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function jx(e){return(await Ge({op:"sessions.preview",requestId:crypto.randomUUID(),cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}})).frontend}function tN(e,t){const n=e.trim();if(!n)return{checked:!0,rung:null,confirmation:o=>g("ui.chat.session_readout.draft.confirm_model",{selector:o})};if(!t.ladderKnown)return{checked:!1,rung:null,refusal:g("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=>g("ui.chat.session_readout.draft.confirm_model_effort",{selector:o,effort:Ai(r)})}:{checked:!0,rung:null,confirmation:o=>t.level?g("ui.chat.session_readout.draft.confirm_effort_changed",{selector:o,level:Ai(t.level),wanted:Ai(n)}):g("ui.chat.session_readout.draft.confirm_effort_unset",{selector:o,wanted:Ai(n)})}}function nN(e,t){return e!==!0?null:t==="on"?g("ui.chat.fast_mode.stays_on"):t==="off"?g("ui.chat.fast_mode.turned_off"):g("ui.chat.fast_mode.unsupported_stays_off")}const rN=()=>g("ui.chat.fast_mode.service_cannot_carry"),oN="fast_unavailable";function Dl(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function iN(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function sN(e){const t=e instanceof Ae?e:null;return t?.code==="fast_mode_unsupported"?g("ui.chat.fast_mode.pick_unsupported"):t?.status===422?g("ui.chat.fast_mode.service_unavailable"):g("ui.chat.fast_mode.not_changed")}function aN(e,t){const n={...e,model:Dl(e.model,t)};return{queryKey:Mx(n),queryFn:()=>jx(n),placeholderData:tb,staleTime:3e4,retry:!1}}function ae(e){return typeof e=="string"?e.trim():""}function Sr(e){const t=ae(e);return t||null}function Nn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function vo(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function pg(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function nr(e,t){return typeof e=="boolean"?e:t}function Ic(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Vr(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 Vr(t)}return[]}function $x(e){if(!Cn(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:pg(e.attempts),last_frame_at:Nn(e.last_frame_at),next_retry_at:Nn(e.next_retry_at),last_error:ae(e.last_error)}}function Cn(e){return typeof e=="object"&&e!==null}const Dx=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function Nx(e,t){const n=ae(e);return Dx.includes(n)?n:t?"reachable":"unreachable_legacy"}const Lx=["running","not_listening","unknown"];function Fx(e){const t=ae(e);return Lx.includes(t)?t:void 0}function Ux(e){if(Array.isArray(e))return e.filter(Cn).map(t=>({endpoint:ae(t.endpoint),connected:t.connected===!0,detail:ae(t.detail),latency_ms:Nn(t.latency_ms)})).filter(t=>t.endpoint!=="")}function cN(e){const t=new Set,n=[];for(const a of Vr(e)){const c=ae(a.device_id);if(!c||t.has(c)||typeof a.reachable!="boolean")continue;t.add(c);const l=Fx(a.remote_relay),d=Ux(a.attempts),u=a.reachable?void 0:$x(a.redial);n.push({device_id:c,name:ae(a.name),reachable:a.reachable,link_state:Nx(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:Sr(a.unreachable_reason??a.reason),last_seen_at:Nn(a.last_seen_at),session_count:vo(a.session_count),rtt_ms:Nn(a.rtt_ms)})}const r=Cn(e)?e:{},o=ae(r.self_device_id),i=Ic(r.degraded);return{peers:n,...o?{self_device_id:o}:{},...i.length?{degraded:i}:{}}}function Bx(e){const t=ae(e.device_id);return t?{device_id:t,name:ae(e.name),role:ae(e.role),capabilities:Ic(e.capabilities),active:nr(e.active,!0),suspect:nr(e.suspect,!1),endpoints:Ic(e.endpoints),last_seen_at:Nn(e.last_seen_at),reachable:nr(e.reachable,!0),reason:ae(e.reason??e.unreachable_reason),scope:ae(e.scope)}:null}function Hx(e){const t=ae(e.network_id);return t?{network_id:t,name:ae(e.name),epoch:pg(e.epoch),trust:ae(e.trust),members:Vr(e.members).map(Bx).filter(n=>n!==null)}:null}function lN(e){const t=Cn(e)?e:{},n=ae(t.self_device_id);return{networks:Vr(t.networks).map(Hx).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function Wx(e){return e.live_state.trim().toLowerCase()==="busy"}function dN(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const o of Vr(r)){const i=ae(o.id);if(!i||n.has(i))continue;const a=o.locality==="remote"?"remote":ae(o.locality)==="local"?"local":null;if(!a)continue;n.add(i);const c=Cn(o.status)?{code:ae(o.status.code),label:ae(o.status.label)}:null,l=Cn(o.binding)?{agent:Sr(o.binding.agent),team:Sr(o.binding.team)}:null,d=Cn(o.opened_by)?{agent:Sr(o.opened_by.agent),label:Sr(o.opened_by.label),session:Sr(o.opened_by.session)}:null;t.push({id:i,name:ae(o.name),mtime:Nn(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:Nn(o.created_at),pinned:nr(o.pinned,!1),...typeof o.active=="boolean"?{active:o.active}:{},waiting_on:vo(o.waiting_on),jobs_running:vo(o.jobs_running),subagents_running:vo(o.subagents_running),subagents_queued:vo(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 uN(e){const{id:t,name:n,mtime:r,...o}=e;return{...o,session_id:t,title:n,updated_at:r}}function fN(e){if(!Cn(e))return null;const t=ae(e.session_id);if(!t)return null;const n=e.mode==="keep"?"keep":"move",r=ae(e.new_session_id)||(n==="move"?t:"");return r?{locality:e.locality==="local"?"local":"remote",owner_device:ae(e.owner_device),source_retired:nr(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:Vr(e.phases).map(o=>({phase:ae(o.phase),peer:ae(o.peer),progress:typeof o.progress=="number"?o.progress:0}))}:null}const Gx=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function pN(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)||g("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||Gx.has(n)}}function hN(e){const t=ae(e.name);return t||g("ui.mesh.mesh_types.device_suffix",{suffix:ae(e.device_id).slice(-6)})}function zx(e){const t=ae(e.name);return t?JSON.stringify(t):g("ui.mesh.mesh_types.unnamed_device")}function Kx(e,t){const n=ae(e);if(!t)return n;const r=t.map(ae).filter(i=>i.length>0&&i!==n);let o=Math.min(10,n.length);for(;o<n.length&&r.some(i=>i.startsWith(n.slice(0,o)));)o+=1;return o<n.length?`${n.slice(0,o)}…`:n}function mN(e,t,n=!1){const r=n?Kx(e.id,t):ae(e.id);return`${zx(e)} ${r}`}function gN(e){const t=ae(e.name);return t||g("ui.mesh.mesh_types.network_suffix",{suffix:ae(e.network_id).slice(-6)})}const Vx=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function Zx(e){const t=e.trim();return t!==""&&Vx.includes(t)}function hg(e){return e.state==="self"?"self":e.reachable?"reached":e.state==="relay_down"?"relay-down":e.state==="handshake_refused"?"handshake-refused":e.linkState==="address_unreachable"?"address-unreachable":e.linkState==="no_endpoint"?"no-endpoint":e.linkState==="not_a_member"?"not-a-member":e.linkState==="not_attempted"||Zx(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const _N=()=>g("ui.mesh.mesh_graph.identity_suspect");function mg(e){switch(e){case"self":return g("ui.mesh.mesh_drop.this_device");case"reached":return g("ui.mesh.mesh_reach.reached");case"relay-down":return g("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return g("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return g("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return g("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return g("ui.mesh.mesh_reach.not_a_member");case"unanswered":return g("ui.mesh.mesh_reach.no_answer");case"not-attempted":return g("ui.mesh.mesh_reach.not_asked");default:return g("ui.mesh.mesh_reach.unknown")}}function bN(e){const t=hg(e),n=mg(t);return e.reason?`${n} — ${e.reason}`:n}const vN={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"},yN={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function wN(e){const t=e.trim();switch(t){case"ok":return g("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return g("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return g("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return g("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return g("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?g("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function kN(e){return e.reachable?"":e.remoteRelay==="not_listening"?g("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?g("ui.mesh.mesh_reach.peer_closed_handshake"):""}function SN(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>Wx(r))?"working":"idle",source:"derived"}}function Yx(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 Xx(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=hg({state:"unreachable",reachable:n.reachable,reason:n.reason??"",sessionCount:n.session_count??null}),o=r==="unanswered",i=o&&n.redial_state==="reconnecting";return e.peer_reach===r&&e.link_down===o&&(e.link_reconnecting??!1)===i&&e.reachable===n.reachable&&e.last_seen_at===n.last_seen_at&&e.link_down_reason===n.reason?e:{...e,reachable:n.reachable,link_down:o,link_reconnecting:i,peer_reach:r,last_seen_at:n.last_seen_at,link_down_reason:n.reason}}function EN(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${g("ui.chat.canonical.transcript.reconnecting")} · ${Ac(n,t)}`:g("ui.presence.link_down_last_seen",{age:Ac(n,t)})}function Ac(e,t){if(e===null)return g("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?g("ui.presence.just_now"):n<3600?g("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?g("ui.presence.hours_ago",{count:Math.floor(n/3600)}):g("ui.presence.days_ago",{count:Math.floor(n/86400)})}function IN(e,t){if(e.link_reconnecting===!0)return g("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return g("ui.presence.link_down_compact",{age:Ac(n,t)})}function Jx(e,t,n,r){if(r<=n)return{facts:e,watermark:n,removed:[]};const o=Object.fromEntries(Object.entries(e).filter(([,i])=>i.at>r));for(const[i,a]of Object.entries(t))(!o[i]||a.at>=o[i].at)&&(o[i]=a);return{facts:o,watermark:r,removed:Object.keys(e).filter(i=>!o[i])}}function AN(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?mg(e.peer_reach):null}const Qx=Object.freeze({}),Nl=["model","effort","fast","cwd"],qx=new Set(["pending","applying","queued_next_step","waiting_idle"]);function gg(e){return!!(e&&qx.has(e.state))}function e1(e,t){return t?e.request_id===t.request_id?t.local?!0:e.generation>t.generation||e.generation===t.generation&&!xf(e,t):e.generation!==t.generation?e.generation>t.generation:t.local?!1:!xf(e,t):!0}function xf(e,t){return!e.updated_at||!t.updated_at?!1:Date.parse(e.updated_at)<Date.parse(t.updated_at)}let _g=0;const bg=new WeakMap;function t1(e){return bg.set(e,++_g),e}function RN(){return _g}function n1(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Xo(e,t,n){const r={...e};return Object.keys(n).length===0?delete r[t]:r[t]=n,r}function Rc(e,t,n,r){const o=e[t]??{},i=o[n];if(r===null){if(!i||i.local)return e;const{[n]:a,...c}=o;return Xo(e,t,c)}return r.kind!==n||!e1(r,i)||i&&!i.local&&n1(r,i)?e:Xo(e,t,{...o,[n]:t1(r)})}function vg(e,t,n,r){let o=e;for(const i of Nl){const a=n[i];if(a){o=Rc(o,t,i,a);continue}if(r===void 0)continue;const c=o[t]?.[i];c&&(bg.get(c)??0)>r||(o=Rc(o,t,i,null))}return o}function r1(e,t,n,r=Number.POSITIVE_INFINITY){const o=n?[n]:[...new Set([...Object.keys(e),...Object.keys(t)])];let i=e;for(const a of o)i=vg(i,a,t[a]??{},r);return i}function o1(e,t,n,r=Date.now()){const o=e[t]??{},i=o[n.kind],a=new Date(r).toISOString(),c={kind:n.kind,value:n.value,effort:n.effort??null,request_id:n.requestId,generation:(i?.generation??0)+1,base:i?.base??null,state:"pending",attempts:0,created_at:a,updated_at:a,error:null,local:!0};return Xo(e,t,{...o,[n.kind]:c})}function i1(e,t,n,r,o,i=Date.now()){const a=e[t],c=a?.[n];return!a||!c||c.request_id!==r?e:Xo(e,t,{...a,[n]:{...c,state:"failed",error:o,updated_at:new Date(i).toISOString()}})}function s1(e,t,n,r){const o=e[t],i=o?.[n];if(!o||!i||i.generation!==r)return e;const{[n]:a,...c}=o;return Xo(e,t,c)}function xN(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"),i=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 i?.value=="string"?i.value:null}}function TN(e){if(!e)return null;let t=null;for(const n of Nl){const r=e[n];if(r?.state==="failed")return r;!t&&r&&gg(r)&&(t=r)}return t}function CN(e){if(!e)return[];const t=[];for(const n of Nl){const r=e[n];r&&(gg(r)||r.state==="failed")&&t.push(r)}return t}function ON(e){const t=e.status??null;return{code:e.code??(t===null?"runtime_unreachable":"refused"),message:e.message??"",retryable:t===null||t>=500}}function PN(e,t){if(e===t)return[];const n=[];for(const[r,o]of Object.entries(t)){const i=o.cwd;if(i?.state!=="applied"||typeof i.value!="string")continue;const a=e[r]?.cwd;a?.state==="applied"&&a.request_id===i.request_id||n.push(i.value)}return n}function MN(e){return e.local?e.state==="failed"&&e.error?.retryable===!0:!0}const Tf=new Set;function jN(e){return Tf.has(e)?!1:(Tf.add(e),!0)}function $N(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?g("ui.chat.canonical.untitled"):n==="this chat"?g("ui.chat.canonical.this_chat"):n:t==="this_chat"?g("ui.chat.canonical.this_chat"):g("ui.chat.canonical.untitled")}function xc(e,t){return e.map((n,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 Ci=(e,t)=>e instanceof Ae?ns(e,t):e instanceof Error?e.message:t,Ms="session_unvalidated",a1=()=>g("ui.common.errors.session_unvalidated"),ps="leading_slash_message",yg=()=>g("ui.common.errors.leading_slash_message");function c1(e,t){return e instanceof Ae&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const wg="attachment_read_failed",kg="store_out_of_space",Sg="store_unavailable";function Cf(e){return e===kg||e===Sg}const l1="answer_not_sent",Eg="aside_not_answered",Ig="aside_still_answering";function yo(e){return e===ps||e===wg||e===kg||e===Sg||e===l1||e===Eg||e===Ig||e===Ms||e===Ss}function d1(e){return e instanceof Ae&&e.status===409&&Ll(e)===void 0}function Ag(e,t=!1){return p1(e)||d1(e)&&!t?"not_sent":e instanceof Ae&&e.status===404?"gone":"unknown"}function Ll(e){if(e instanceof Ae||e instanceof _n)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const mt={get unconfirmed(){return g("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return g("ui.chat.canonical.send_failure.unreachable")},get busy(){return g("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return g("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return g("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return g("ui.chat.canonical.send_failure.retiring")},get notReady(){return g("ui.chat.canonical.send_failure.not_ready")},get generic(){return g("ui.chat.canonical.send_failure.generic")},get gone(){return g("ui.chat.canonical.send_failure.gone")},get sendLock(){return g("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return g("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return g("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return g("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return g("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return g("ui.chat.canonical.send_failure.late_delivery_overlap")}};function DN(e){return e?mt.gateLock:mt.sendLock}const NN=()=>g("ui.common.actions.retry"),LN=()=>g("ui.common.actions.clear");function u1(e,t,n=!1){const r=Ag(e,n),o=t??Ll(e),i=ns(e,mt.generic);return r==="gone"?{message:mt.gone,retry:!1,code:o}:r==="not_sent"?o===Ss?{message:mt.busy,retry:!0,code:o}:o===th?{message:mt.retiring,retry:!0,code:o}:o===We.serverUpdating?{message:Qn(o),retry:!0,code:o}:o===Ms?{message:mt.notReady,retry:!yo(o),code:o}:o===Eg?{message:mt.asideNotAnswered,retry:!1,code:o}:o===Ig?{message:mt.asideStillAnswering,retry:!1,code:o}:o===ps?{message:yg(),retry:!1,code:o}:{message:i,retry:!1,code:o}:al(e)?{message:Qn(We.serverUpdating),retry:o===We.transportFailed,code:o}:o===We.transportFailed?{message:mt.unreachable,retry:!0,code:o}:Es(o)?{message:Qn(o),retry:!1,code:o}:o===il?{message:mt.unconfirmed,retry:!yo(o),code:o}:o===nw.runtimeUnreachable?{message:mt.unconfirmed,retry:!0,code:o}:o?{message:i,retry:!yo(o),code:o}:{message:mt.unconfirmed,retry:!yo(o),code:o}}function Tc(e){return e.trim()}function FN(e,t){if(t.length===0)return Tc(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
45
- `);return Tc(`${n}
46
- ${e}`)}function Cc(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function f1(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 i=e[0]?.ts;return i===void 0||i<=0?!1:i*1e3<=o}function UN(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,i])=>Cc(i,t));return(r.find(([,i])=>i.submittedText!==void 0||i.undelivered!==void 0||i.error!==void 0||i.admissionAttempted===!0||i.pending===!0)??r[0])?.[0]??`send:${t}`}function js(e,t){return t??e??void 0}function Rg(e,t,n){return e?t??void 0:n??void 0}function BN(e,t,n){return js(e,Rg(e,t,n))}function HN(e,t,n){const r=js(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,i=e.sessionId!==void 0&&n===e.sessionId;return o||i?e.key:r}function p1(e){return e instanceof Ae?e.status===413||e.status===422?!0:e.code===Ss||e.code===th||e.code===We.noCredential||e.code===We.serverUpdating||Cf(e.code):e instanceof _n&&(e.code===Ms||e.code===wg||Cf(e.code))}function ai(e,t){const n=e.startsWith("send:")?e.slice(5):null;return js(e.startsWith("draft:")?e:null,t??n)??e}function h1(e,t){const n=lt.getState(),r=ai(e,t),o=r===""||r===e?[e]:[e,r];n.settleInFlight(o),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function WN(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=ai(e,t.sessionId);return lt.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),Je.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:mt.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!yo(t.heldClaimCode),heldClaimCode:void 0}),!0}function GN(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 i=ai(e,t.sessionId);if(n){if(Af(i,n.recordId))return!1;const c=cg(i,n.recordId);return c!=="unseen"?(c==="owner"&&Je.getState().retractUndelivered(e,n.recordId),!1):(wc(i,{id:n.recordId,text:n.text,images:[],documents:xc(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const a=t.admissionRequestId;return Af(i,a)?!1:(wc(i,{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:xc(t.submittedFiles??[],a)}),!0)}function Of(e,t,n){kx(ai(e,t),n)}function m1(e,t,n){if(e.submittedText!==t)return!1;const r=e.submittedAttachments??[];return r.length!==n.length?!1:r.every((o,i)=>o===n[i])}function g1(e,t){return!!t&&e===t}const _1=3,b1=5e3,v1=2e3;async function y1(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=_1||!(n instanceof Ae)||n.code!==Ss)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??v1),b1);await new Promise(o=>setTimeout(o,r))}}async function w1(e){await y1(async()=>{await Ge(e)})}async function zN(e,t,n,r,o){const i=Je.getState();if(g1(i.validatingSessionId,n))throw new _n(a1(),Ms);const a=i.drafts[e];if(a?.pending)return null;const c=Tc(t.text),l=a?.submittedText!==void 0&&m1(a,c,t.attachments),d=a??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?a?.submittedImages??t.images:t.images,f=l?a?.submittedFiles??t.files:t.files,h=l?a?.submittedMode??t.mode:t.mode,_=l&&a?a.submittedInputMode:t.inputMode,y=l&&a?a.submittedInputPath:t.inputPath,v=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),b=Date.now();i.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:v,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:h,submittedInputMode:_,submittedInputPath:y,error:void 0,errorCode:void 0,submittedAt:b});const p=js(e.startsWith("draft:")?e:null,n??d.sessionId)??null;p&&wc(p,{id:v,submittedAt:b,text:c,images:u.map((P,W)=>({id:`${v}:${W}`,data:P.data_b64,attachment:null,mimeType:P.mime_type})),documents:xc(f??[],v),onPainted:r});let A=l,k=n??d.sessionId,M=null;try{if(!k){if(M="sessions.create",k=await i.createSession(t.cwd,d.target,d.createRequestId,Dl(d.model??null,i.draftFastCarries),d.warmId,d.peer,VA(d,i.temporaryChats)?!0:void 0)??void 0,!k)throw new _n(Je.getState().error??g("ui.common.errors.chat_start_simple"));i.updateDraft(e,{sessionId:k}),p&&_x(p,k),i.fetchSessions()}const P=l&&a?.submittedRendered!==void 0?a.submittedRendered:o?await o(k)??c:c;return A=!0,i.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:P}),k&&gx(k,v,P),M="sessions.message",await w1({op:"sessions.message",sessionId:k,requestId:v,text:P,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:h,inputMode:_,inputPath:y}),i.finishDraft(e,k),Je.setState({error:null}),k}catch(P){Je.setState({error:null});const W=l&&a?.admissionAttempted===!0,R=Ag(P,W),m=M==="sessions.message"&&c1(P,c),w=m?ps:Ll(P),S=u1(P,w,W);let T=!1;const N=k??p??void 0;if(N&&R==="unknown"&&(T=A&&cg(N,v)==="owner"),i.updateDraft(e,{pending:!1,admissionAttempted:R==="unknown"&&A,errorCode:w,error:S.message,errorRetry:S.retry}),T)return k?(i.finishDraft(e,k),k):null;const Y=ai(e,k??d.sessionId),X=p&&p!==Y?[p,Y]:[Y];throw lt.getState().settleInFlight(X),p&&p!==Y&&lt.getState().returnInFlight(p,Y),N&&Sc(N,v),e!==N&&Sc(e,v),m?new Ae(422,yg(),P,ps):P}}const xg=50,Pf="activity",k1=25,S1=500;function E1(e){return e?xg:S1}function Mf(e,t){return`${e}:${t}`}function I1(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function A1(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function R1(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 Tg(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 x1(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)),i=e.merge(e.sessions,e.page),a=new Set(i.map(c=>c.session_id));for(const c of o)a.has(c.session_id)||(a.add(c.session_id),i.push(c));return{rows:i,tailIds:e.tailIds.filter(c=>a.has(c))}}function T1(e){const t=[...e.previousIds],n=new Set(t);for(const i of e.page)n.has(i.session_id)||(n.add(i.session_id),t.push(i.session_id));const r=[...e.sessions],o=new Map(r.map((i,a)=>[i.session_id,a]));for(const i of e.page){const a=o.get(i.session_id);if(a===void 0){o.set(i.session_id,r.length),r.push(i);continue}r[a]=e.merge(r[a],i)}return{rows:r,ids:t}}function Kn(e,t){return{...e,...t,...P1(e,t),...M1(t,e),attention:Tr(e?.attention,t.attention,t.session_id)}}const KN=ug,C1=e=>e.filter(fg),jf=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const o=e[r],i=Tr(o.attention,n,t);if(i===o.attention)return e;const a=e.slice();return a[r]={...o,attention:i},a},O1=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function P1(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 M1(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 j1(e,t){const n={};let r=!1;for(const[o,i]of Object.entries(e)){if(i.at<t){r=!0;continue}n[o]=i}return r?n:e}function Ta(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(i=>i.session_id!==t),archiveFacts:n,placementFacts:r,answerSeq:o,forgotten:{...e.forgotten,[t]:{at:o,title:e.sessions.find(i=>i.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function Cg(e){return{...e,sessionId:void 0,pending:!1,error:void 0,errorCode:void 0,errorRetry:void 0,submittedText:void 0,submittedRendered:void 0,submittedAttachments:void 0,submittedImages:void 0,submittedMode:void 0,submittedInputMode:void 0,submittedInputPath:void 0,submittedAt:void 0,admissionAttempted:void 0,undelivered:void 0,warmId:void 0,migratedHeld:void 0,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}function Og(e){const t=e.submittedText??e.undelivered?.text,n=e.submittedAttachments??e.undelivered?.attachments??[];return t===void 0&&n.length===0?null:{text:t??"",attachments:[...n]}}function Pg(e,t,n){const r=lt.getState();if(t&&t!==e){r.adoptReturnedText(t);const o=lt.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 $1(e,t,n){const r=lt.getState(),o=n??(e?r.getCurrentInput(e):"");o&&r.setComposerText(t,o),e&&e!==t&&r.setComposerText(e,"")}function D1(e,t){let n=null;const r=[];for(const[o,i]of Object.entries(e))!i.sessionId||t[i.sessionId]===void 0||(n??={...e},n[o]=Cg(i),r.push({key:o,sessionId:i.sessionId,payload:Og(i)}));return{drafts:n??e,restored:r}}function Mg(e){return e.map(({id:t,name:n,mtime:r,...o})=>({...o,session_id:t,title:n,updated_at:r}))}function $f(e,t){return Mg(e).filter(n=>t[n.session_id]===void 0)}function Ca(e){return typeof e=="string"&&e.length>0?e:null}function N1(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),i=n(t.unbound);if(r===null||o===null||i===null||!Array.isArray(t.scopes))return null;const a=[];for(const c of t.scopes){if(c===null||typeof c!="object")return null;const l=c;if(l.kind!=="team"&&l.kind!=="agent"||typeof l.name!="string"||l.name.length===0)continue;const d=n(l.total),u=n(l.active);d===null||u===null||a.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:r,active:o,unbound:i,scopes:a}}function L1(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 Oa=0,vr=null;function F1(e,t,n){const r=vr;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 vr=o,o.promise=(async()=>{try{for(;;){o.invalidated=!1;let i;try{i=await n(o.limit,o.withCounts)}catch(a){if(o.invalidated)continue;throw a}if(!o.invalidated)return vr===o&&(vr=null),i}}finally{vr===o&&(vr=null)}})(),o.promise}function jg(){try{const e=window.api?.desktop;return e?e.initialSession?{kind:"session",sessionId:e.initialSession}:e.initialCatalogue?{kind:"catalogue"}:{kind:"restore"}:{kind:"restore"}}catch{return{kind:"restore"}}}function U1(){const e=jg();return e.kind==="session"?e.sessionId:null}function B1(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 H1(e,t){const n={...t,...e},{drafts:r,restored:o}=D1(n.drafts,n.forgotten),i=r===n.drafts?n:{...n,drafts:r};for(const l of o)Pg(l.key,l.sessionId,l.payload);const a=jg();if(a.kind==="session")return{...i,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...i,activeSessionId:null};const c=B1(i);return c?{...i,...c}:i}const Je=oi()(Is((e,t)=>({sessions:[],settingsIntents:Qx,hydrateSettingsIntents:(n,r,o)=>{e(i=>{const a=r1(i.settingsIntents,n,r,o);return a===i.settingsIntents?i:{settingsIntents:a}})},applySettingsIntentFrame:(n,r,o)=>{e(i=>{const a=Rc(i.settingsIntents,n,r,o);return a===i.settingsIntents?i:{settingsIntents:a}})},applySettingsIntentSlots:(n,r)=>{e(o=>{const i=vg(o.settingsIntents,n,r);return i===o.settingsIntents?o:{settingsIntents:i}})},paintSettingsIntent:(n,r)=>{e(o=>({settingsIntents:o1(o.settingsIntents,n,r)}))},failSettingsIntent:(n,r,o,i)=>{e(a=>{const c=i1(a.settingsIntents,n,r,o,i);return c===a.settingsIntents?a:{settingsIntents:c}})},removeSettingsIntent:(n,r,o)=>{e(i=>{const a=s1(i.settingsIntents,n,r,o);return a===i.settingsIntents?i:{settingsIntents:a}})},cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,temporaryChats:!1,activeSessionId:U1(),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(([,i])=>!i.sessionId)?{cwd:n,drafts:Object.fromEntries(o.map(([i,a])=>a.sessionId?[i,a]:[i,{...a,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=E1(t().cataloguePageable),r=!1)=>{const o=++Oa,i=t().answerSeq+1;e({answerSeq:i}),e({loading:!0,error:null});try{const a=await F1(n,r,(l,d)=>Ge({op:"sessions.list",limit:l,include_archived:!0,...t().temporaryChats?{include_temporary:!0}:{},...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:Pf}:{}}));if(o!==Oa)return;const c=Mg(a.sessions);e(l=>{const d={...l.pinFacts};for(const[m,w]of Object.entries(d))w.at>=i||delete d[m];const u=new Set(c.map(m=>m.session_id));let f=!1;const h={...l.forgotten};for(const[m,w]of Object.entries(h))w.at<i&&u.has(m)&&(delete h[m],f=!0);const _=f?h:l.forgotten,y=c.filter(m=>_[m.session_id]===void 0);let v=null;for(const m of y){const w=l.placementFacts[m.session_id];if(w===void 0||w.at>=i)continue;const S=m.locality==="remote"?"remote":m.locality==="local"?"local":null;S!==null&&(v??={...l.placementFacts},v[m.session_id]={locality:S,owner_device:typeof m.owner_device=="string"?m.owner_device:"",at:l.answerSeq+1})}const b=Ca(a.next_cursor),p=b===null&&a.truncated!==!0,A=y.map(m=>m.session_id),k=l.sessions.filter(m=>_[m.session_id]===void 0&&(l.pinFacts[m.session_id]?.at??-1)>=i),M=x1({sessions:l.sessions,scopeIds:I1(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...A1(l.placementFacts)],tailIds:p?[]:l.head.tailIds,page:y,merge:L1});let P=M.rows;for(const m of k){const w=l.pinFacts[m.session_id],S=P.findIndex(T=>T.session_id===m.session_id);S===-1?P=[...P,{...m,pinned:w.pinned}]:P[S]={...P[S],pinned:w.pinned}}const W=j1(l.archiveFacts,i),R=N1(a.counts);return{sessions:P,pinFacts:d,archiveFacts:W,...v===null?{}:{placementFacts:v,answerSeq:l.answerSeq+1},forgotten:_,loading:!1,truncated:a.truncated===!0,head:{pageIds:A,tailIds:M.tailIds,nextCursor:b,tailCursor:p?null:l.head.tailStarted?l.head.tailCursor:b,tailStarted:l.head.tailStarted,complete:p,loading:!1,error:null,at:i},...R===null?{}:{counts:R},statusUnavailable:Array.isArray(a.degraded)?a.degraded.filter(m=>typeof m=="string"):[]}})}catch(a){o===Oa&&e({loading:!1,error:Ci(a,g("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 Ge({op:"sessions.list",limit:xg,include_archived:!0,...t().temporaryChats?{include_temporary:!0}:{},cursor:r,...t().catalogueActivityHead?{sort:Pf}:{}}),i=$f(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 i){const h=c.get(f.session_id);if(h===void 0){c.set(f.session_id,l.length),l.push(f),d.push(f.session_id);continue}l[h]=Kn(l[h],f)}const u=Ca(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(i=>({head:{...i.head,loading:!1,error:Ci(o,g("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,o=null,i=k1)=>{const a=Mf(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 Ge({op:"sessions.list",limit:i,include_archived:!1,scope_kind:n,scope_name:r,...o===null?{}:{cursor:o}}),d=$f(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,_=T1({sessions:u.sessions,previousIds:h?f.ids:[],page:d,merge:Kn}),y=Ca(l.next_cursor);return{sessions:_.rows,scopes:{...u.scopes,[a]:{ids:_.ids,nextCursor:y,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[a];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[a]:{...u,loading:!1,error:Ci(l,g("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const o=Mf(n,r);e(i=>{const a=i.scopes[o];if(a===void 0)return{};const c={...i.scopes};delete c[o];const l=i.activeSessionId,d=new Set(a.ids),u=new Set(i.head.pageIds),f=i.sessions.filter(h=>!d.has(h.session_id)||u.has(h.session_id)||l!==null&&h.session_id===l);return{scopes:c,sessions:f}})},setCataloguePageable:n=>{t().cataloguePageable!==n&&e({cataloguePageable:n})},setCatalogueActivityHead:n=>{t().catalogueActivityHead!==n&&e({catalogueActivityHead:n})},setTemporaryChats:n=>{t().temporaryChats!==n&&e({temporaryChats:n})},setDraftTemporary:(n,r)=>e(o=>{const i=o.drafts[n];return i?i.temporary===!0===r?{}:{drafts:{...o.drafts,[n]:{...i,temporary:r?!0:void 0,...i.sessionId?{}:{createRequestId:crypto.randomUUID()}}}}:{}}),setSessionTemporary:async(n,r)=>{try{const o=await Ge({op:"sessions.temporary",sessionId:n,temporary:r}),i=o&&typeof o.temporary=="object"?o.temporary:null;return e(a=>({sessions:a.sessions.map(c=>c.session_id===n?{...c,temporary:i}:c)})),{ok:!0}}catch(o){return{ok:!1,code:o instanceof Ae?o.code:void 0,detail:ns(o,"")}}},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;lt.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 i=lt.getState();for(const[a,c]of Object.entries(r.composer)){const l=i.inputByConversation[a];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||i.restoreRow(a,c)}return{drafts:o,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,r,o)=>{const i=t().answerSeq+1,a=t().archiveFacts[n]??null,c=o??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:i,archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:i,answered:!1}}}));try{return await Ge({op:"sessions.archive",sessionId:n,archived:r}),e(l=>{const u=l.archiveFacts[n]?.at!==i;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:i,answered:!0}},archiveUndo:u?l.archiveUndo:r?{sessionId:n,title:c??void 0,archived:!0,at:i}:null,archiveFailure:l.archiveFailure?.sessionId===n?null:l.archiveFailure}}),!0}catch(l){return e(d=>{const u=d.archiveFacts[n]?.at!==i,f={...d.archiveFacts};return u||(a?.answered===!0?f[n]=a:(delete f[n],a!==null&&t().fetchSessions())),{archiveFacts:u?d.archiveFacts:f,answerSeq:d.answerSeq+1,archiveFailure:{sessionId:n,at:d.answerSeq+1,archived:r,title:c||"",detail:l instanceof Ae&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await Ge({op:"sessions.delete",sessionId:n,confirmed:!0}),e(r=>Ta(r,n)),t().retireDraftsForSession(n),{ok:!0}}catch(r){const o=r instanceof Ae?r.status:null,i=r instanceof Ae?r.code??null:null;return o===404?(e(a=>Ta(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:i==="session_delete_refused",detail:r instanceof Ae&&r.message?r.message:g("ui.common.errors.conversation_delete")}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,o=crypto.randomUUID(),i,a,c,l)=>{try{const d=await Ge({op:"sessions.create",requestId:o,cwd:n,...r?{target:r}:{},...i?{model:i}:{},...a?{draftId:a}:{},...c?{peer:c}:{},...l?{temporary:!0}:{}}),u=t().sessions.some(h=>h.session_id===d.session_id),f=Date.now()/1e3;return t().upsertSession({session_id:d.session_id,cwd:n,binding:d.binding,...u?{}:{created_at:f,updated_at:f},...l?{temporary:{marked_at:Date.now()/1e3,idle_minutes:30,deletes_at:null,hold:"running"}}:{}}),c&&t().settlePlacement(d.session_id,{locality:"remote",owner_device:c}),d.session_id}catch(d){throw e({error:Ci(d,g("ui.common.errors.chat_start"))}),d}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,r=Date.now())=>e(o=>({stoppedTurns:{...o.stoppedTurns,[n]:r}})),clearTurnStopped:n=>e(r=>{if(!(n in r.stoppedTurns))return r;const{[n]:o,...i}=r.stoppedTurns;return{stoppedTurns:i}}),openDraft:n=>{t().drafts[n]&&e({activeDraftKey:n,activeSessionId:null,validatingSessionId:null,error:null})},confirmSessionLive:n=>{n&&t().validatingSessionId===n&&e({validatingSessionId:null})},confirmSessionMissing:n=>{!n||t().validatingSessionId!==n||(e({validatingSessionId:null,...Ta(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:O1(r.readAckRearm,n)}))},publishReadAckNotice:(n,r,o)=>{e(i=>{const a=i.readAckNotice;return a?.sessionId===n&&a.kind===r?i:{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 i=jf(o.sessions,n,r);return i===o.sessions?o:{...o,sessions:i}})},applyAttentionMany:n=>{e(r=>{let o=r.sessions;for(const i of n){const a=i?.conversation_id;typeof a!="string"||!a.startsWith("session/")||(o=jf(o,a.slice(8),i))}return o===r.sessions?r:{...r,sessions:o}})},markAllRead:async()=>{const n=C1(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 Ge({op:"attention.seen",items:n});t().applyAttentionMany(r.read);const o=R1(t().sessions,t().placementFacts),i=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:i}},applySessionStatus:(n,r,o,i,a)=>{e(c=>{const l=c.sessions.findIndex(y=>y.session_id===n);let d=!1;const u=c.sessions.map(y=>{if(y.status_epoch===void 0&&y.status_revision===void 0||y.status_epoch===i)return y;d=!0;const{status_revision:v,status_epoch:b,...p}=y;return p});if(l<0)return d?{...c,sessions:u}:c;const f=u[l],_=!(a!==void 0&&Object.keys(a).some(y=>f[y]!==a[y]))&&f.status?.code===r.code&&f.status?.label===r.label&&f.status_revision===o&&f.status_epoch===i;return _&&!d?c:(_||(u[l]={...f,...a,status:r,status_revision:o,status_epoch:i}),{...c,sessions:u})})},openSession:async n=>t().activeSessionId===n&&!t().activeDraftKey?(t().rearmReadAck(n),!0):(e({activeSessionId:n,activeDraftKey:null,validatingSessionId:n,error:null}),t().rearmReadAck(n),!0),stageDraft:(n,r=!1)=>{const i=(!r&&n?`draft:${n.kind}:${n.name}`:null)??`draft:${crypto.randomUUID()}`,a=t().drafts[i],c=Rg(t().activeDraftKey,t().activeDraftKey?t().drafts[t().activeDraftKey]?.sessionId:void 0,t().activeSessionId);if(a?.sessionId&&!a.pending&&a.sessionId!==c){const d=t().drafts[`send:${a.sessionId}`]?`draft:${crypto.randomUUID()}`:`send:${a.sessionId}`;e(u=>{const f={...u.drafts};return delete f[i],f[d]={...a,key:d},{drafts:f}})}const l=t().drafts[i];return e(d=>({activeDraftKey:i,validatingSessionId:null,error:null,drafts:{...d.drafts,[i]:l??{key:i,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),i},restageDraft:(n,r)=>{const o=t().activeDraftKey,i=t().stageDraft(n);return $1(o,i,r),i},startNewChat:n=>{const r=t().stageDraft();return e({activeSessionId:null,validatingSessionId:null}),n&&(lt.getState().adoptReturnedText(n),lt.getState().inputByConversation[n]?.pendingText===void 0&&lt.getState().returnInFlight(n,r)),r},updateDraft:(n,r)=>e(o=>{const i=o.drafts[n],a=r.key!==void 0&&r.createRequestId!==void 0&&r.admissionRequestId!==void 0;return!i&&!a?{}:{drafts:{...o.drafts,[n]:{...o.drafts[n],...r}}}}),setDraftPeer:(n,r)=>e(o=>{const i=o.drafts[n];if(!i)return{};const a=r??void 0;return(i.peer??void 0)===a?{}:{drafts:{...o.drafts,[n]:{...i,peer:a,...i.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}}),setDraftModel:(n,r)=>e(o=>{const i=o.drafts[n];return i?{drafts:{...o.drafts,[n]:{...i,model:r,...i.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 i=o.draftRequestId??crypto.randomUUID();o.draftRequestId||t().updateDraft(n,{draftRequestId:i});const a=Dl(o.model??null,r.draftFastCarries);Ge({op:"sessions.draft",requestId:i,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===i&&t().updateDraft(n,{warmId:c.draft_id})}).catch(()=>{})},finishDraft:(n,r)=>e(o=>{h1(n,r);const i={...o.drafts};return delete i[n],{drafts:i,...o.activeDraftKey===n?{activeDraftKey:null,activeSessionId:r}:{}}}),retireDraftSession:n=>{const r=t().drafts[n];if(!r?.sessionId||r.pending)return;const o=r.sessionId,i=Og(r);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:Cg(c)}}}),Pg(n,o,i)},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,i])=>o.startsWith("draft:")&&i.warmId===n&&!i.sessionId);r.length!==0&&e(o=>{const i={...o.drafts};for(const[a]of r){const c=i[a];!c||c.warmId!==n||c.sessionId||(i[a]={...c,warmId:void 0,draftRequestId:crypto.randomUUID()})}return{drafts:i}})},discardDraft:n=>e(r=>{const o={...r.drafts},i=o[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),a=o[n],c=lt.getState().inputByConversation[n];Ri(n),i&&i!==n&&Ri(i),delete o[n],lt.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 i=!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);Ri(u),h&&h!==u&&Ri(h),a.push(u),c[u]=f;const _=lt.getState().inputByConversation[u];_&&(l[u]=_),delete o[u],lt.getState().clearAll(u),r.activeDraftKey===u&&(i=!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},...i?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,r,o)=>e(i=>{const a=r.map(S=>S.id),c=Object.entries(i.drafts).filter(([,S])=>Cc(S,n)&&S.undelivered!==void 0&&a.includes(S.undelivered.recordId));let l=i.drafts;if(c.length>0){l={...l};for(const[S,T]of c){const N=T.undelivered?.recordId,{undelivered:Y,...X}=T;l[S]=X,N!==void 0&&Of(S,T.sessionId,N)}}const d=Object.entries(l).find(([,S])=>Cc(S,n)&&S.admissionAttempted===!0&&S.pending!==!0&&S.submittedText!==void 0);if(!d)return c.length>0?{drafts:l}:{};const[u,f]=d,h=f.admissionRequestId,_=a.includes(h);if(!_&&!o)return c.length>0?{drafts:l}:{};if(!_&&!f1(r,f,i.placementFacts[n],i.sessions.find(S=>S.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:y,submittedText:v,submittedAttachments:b,submittedImages:p,submittedMode:A,submittedInputMode:k,submittedInputPath:M,heldClaimCode:P,error:W,errorCode:R,errorRetry:m,...w}=f;return _||Sc(n,h),{drafts:{...l,[u]:{...w,..._?{}:{undelivered:{recordId:h,text:v??"",attachments:b??[]}},admissionRequestId:crypto.randomUUID()}}}}),retractUndelivered:(n,r)=>{const o=t().drafts[n];!o||o.undelivered?.recordId!==r||(e(i=>{const{undelivered:a,...c}=i.drafts[n];return{drafts:{...i.drafts,[n]:c}}}),Of(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 i=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&&(i=i??{...o.pinFacts},delete i[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 i===null&&a===null&&c===null?{}:{...i===null?{}:{pinFacts:i},...a===null?{}:{sessions:a},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,r,o)=>{const i=t().sessions.find(h=>h.session_id===n),a=t().pinFacts[n]??null,c=i===void 0?a?.pinned??!1:i.pinned===!0,l=i===void 0&&o!==void 0?{session_id:n,title:o.title||"",updated_at:o.updated_at,pinned:r}:null,d=t().beginAnswer(),u=i?.title??o?.title,f=i?.updated_at??o?.updated_at;e(h=>({sessions:l===null?h.sessions.map(_=>_.session_id===n?{..._,pinned:r}:_):[...h.sessions,l],pinFacts:{...h.pinFacts,[n]:{pinned:r,at:d,title:u,updated_at:f}},pinFailure:null}));try{const h=await Ge({op:"sessions.pin",sessionId:n,pinned:r});let _=!1;return e(y=>{const v=y.pinFacts[n];return v===void 0||v.at!==d?{}:(_=!0,{sessions:y.sessions.map(b=>b.session_id===n?{...b,pinned:h.pinned===!0}:b),pinFacts:{...y.pinFacts,[n]:{...v,pinned:h.pinned===!0}}})}),_}catch(h){return e(_=>{const y=_.pinFacts[n];if(y!==void 0&&y.at!==d)return{};const v={..._.pinFacts};return a===null&&i===void 0?delete v[n]:v[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:_.sessions.map(b=>b.session_id===n?{...b,pinned:c}:b),pinFacts:v,pinFailure:{sessionId:n,pinned:r,title:i?.title||"",detail:ns(h,""),...h instanceof Ae&&h.code?{code:h.code}:{}}}}),!1}},upsertSession:n=>e(r=>({sessions:r.sessions.some(i=>i.session_id===n.session_id)?r.sessions.map(i=>i.session_id===n.session_id?Kn(i,n):i):[...r.sessions,n]})),settlePlacement:(n,r)=>{const o=t().beginAnswer();e(i=>({sessions:i.sessions.map(a=>a.session_id===n?Kn(a,{session_id:n,locality:r.locality,owner_device:r.owner_device}):a),placementFacts:{...i.placementFacts,[n]:{locality:r.locality,owner_device:r.owner_device,at:o}}}))},settlePeerCatalogue:(n,r,o={},i=void 0)=>{e(a=>{const c={...a.forgotten};for(const m of n)c[m.session_id]?.at<r&&delete c[m.session_id];const l=n.filter(m=>{if(c[m.session_id]||m.locality==="remote"&&a.peerDeviceSnapshotAt>r&&typeof m.owner_device=="string"&&!a.peerDeviceFacts[m.owner_device])return!1;const w=a.placementFacts[m.session_id];return!w||w.at<r}),d={...a.placementFacts},u=new Set;let f=!1,h=0;for(const m of l){const w=m.locality==="remote"?"remote":m.locality==="local"?"local":null;if(w===null)continue;const S=a.placementFacts[m.session_id];if(S!==void 0){if(S.at>=r)continue}else if(w!=="remote")continue;h=h===0?a.answerSeq+1:h,u.add(m.session_id),d[m.session_id]={locality:w,owner_device:w==="remote"&&typeof m.owner_device=="string"?m.owner_device:"",at:h},f=!0}const _=i===void 0?null:Jx(a.peerDeviceFacts,o,a.peerDeviceSnapshotAt,i),y=_?.facts??Yx(a.peerDeviceFacts,Object.fromEntries(Object.entries(o).filter(([,m])=>m.at>a.peerDeviceSnapshotAt))),v=l.filter(m=>m.locality==="remote");let b=a.sessions,p=!1;const A=[],k=new Map;for(let m=0;m<b.length;m+=1)k.set(b[m].session_id,m);for(const m of v){const w=k.get(m.session_id);if(w===void 0){A.push(m);continue}b[w]!==m&&(p||(b=b.slice(),p=!0),b[w]=Kn(b[w],m))}A.length>0&&(b=[...b,...A]);for(const m of l){if(m.locality==="remote"||!u.has(m.session_id))continue;const w=k.get(m.session_id);w===void 0||b[w]===m||(p||(b=b.slice(),p=!0),b[w]=Kn(b[w],m))}const M=new Set(l.map(m=>m.session_id)),P=new Set;for(const m of l)m.locality==="remote"&&typeof m.owner_device=="string"&&m.owner_device!==""&&m.reachable!==!1&&P.add(m.owner_device);const W=new Set;for(const m of b){if(m.locality!=="remote"||typeof m.owner_device!="string"||!_?.removed.includes(m.owner_device))continue;const w=a.placementFacts[m.session_id];w&&w.at>=(i??0)||(W.add(m.session_id),delete d[m.session_id])}for(const[m,w]of Object.entries(a.placementFacts))w.locality==="remote"&&(M.has(m)||w.at>=r||y[w.owner_device]?.reachable!==!1&&(w.owner_device===""||!P.has(w.owner_device)||(W.add(m),delete d[m])));W.size>0&&(b=b.filter(m=>!W.has(m.session_id)));const R=b.map(m=>Xx(m,y));return R.some((m,w)=>m!==b[w])&&(b=R,p=!0),!f&&A.length===0&&!p&&W.size===0&&Object.keys(o).length===0&&i===void 0?{}:{sessions:b,placementFacts:d,peerDeviceFacts:y,peerDeviceSnapshotAt:_?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:H1,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 VN(e,t){return t?e.filter(n=>n.archived!==!0):e}function ZN(e,t){let n=!1;const r=e.map(o=>{const i=t[o.session_id];return i===void 0||!i.answered||o.archived===i.archived?o:(n=!0,{...o,archived:i.archived})});return n?r:e}function YN(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function XN(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const JN="This backend cannot archive conversations. Update the backend and try again.",QN="This conversation is already archived. Use /unarchive to restore it.",qN="This conversation is not archived, so there is nothing to restore.",eL="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 tL(e,t,n){return n&&e&&t.trim().length>0}function nL(e,t){return t===e}const se=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,i=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(i),c(a)];return[116*d-16,500*(l-d),200*(d-u)]},fe=(e,t)=>{const[n,r,o]=se(e),[i,a,c]=se(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,_]=[(1+f)*r,(1+f)*a],[y,v]=[Math.hypot(h,o),Math.hypot(_,c)],b=(E,V)=>{if(E===0&&V===0)return 0;const G=Math.atan2(E,V)*d;return G<0?G+360:G},[p,A]=[b(o,h),b(c,_)],k=i-n,M=v-y;let P=0;y*v!==0&&(P=A-p,P>180?P-=360:P<-180&&(P+=360));const W=2*Math.sqrt(y*v)*Math.sin(P*l/2),R=(n+i)/2,m=(y+v)/2;let w;y*v===0?w=p+A:(w=Math.abs(p-A)>180?(p+A+360)/2:(p+A)/2,w>=360&&(w-=360));const S=1-.17*Math.cos((w-30)*l)+.24*Math.cos(2*w*l)+.32*Math.cos((3*w+6)*l)-.2*Math.cos((4*w-63)*l),T=1+.015*(R-50)**2/Math.sqrt(20+(R-50)**2),N=1+.045*m,Y=1+.015*m*S,X=-Math.sin(2*30*Math.exp(-(((w-275)/25)**2))*l)*2*Math.sqrt(m**7/(m**7+25**7));return Math.sqrt((k/T)**2+(M/N)**2+(W/Y)**2+X*(M/N)*(W/Y))},hs=([e,t,n])=>{const r=(e+16)/116,o=r+t/500,i=r-n/200,a=_=>_>6/29?_**3:3*(6/29)**2*(_-4/29),c=a(o)*.95047,l=a(r),d=a(i)*1.08883,f=[c*3.2404542+l*-1.5371385+d*-.4985314,c*-.969266+l*1.8760108+d*.041556,c*.0556434+l*-.2040259+d*1.0572252].map(_=>_<=.0031308?12.92*_:1.055*_**(1/2.4)-.055);if(f.some(_=>_<-.0015||_>1.0015))return null;const h=_=>Math.round(Math.min(1,Math.max(0,_))*255).toString(16).padStart(2,"0").toUpperCase();return`#${f.map(h).join("")}`},D=e=>Math.round(e*100)/100,Df=e=>{const t=e.replace("#","").trim(),n=t.length===3?t.split("").map(a=>a+a).join(""):t,[r,o,i]=[0,2,4].map(a=>{const c=Number.parseInt(n.slice(a,a+2),16)/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4});return .2126*r+.7152*o+.0722*i},oe=(e,t)=>{const[n,r]=[Df(e),Df(t)].sort((o,i)=>i-o);return(n+.05)/(r+.05)},W1=/^#[0-9a-fA-F]{3,8}$/,H=e=>typeof e=="string"&&W1.test(e),Pa=(e,t,n)=>{const r=f=>{const h=f.replace("#","").trim(),_=h.length===3?h.split("").map(y=>y+y).join(""):h;return[0,2,4].map(y=>Number.parseInt(_.slice(y,y+2),16))},[o,i,a]=r(e),[c,l,d]=r(t),u=(f,h)=>Math.round(f*n+h*(1-n));return`#${[u(o,c),u(i,l),u(a,d)].map(f=>f.toString(16).padStart(2,"0")).join("")}`},yn={"under-window":{dark:81,light:199},menu:{dark:102,light:171},popover:{dark:122,light:143}},Fl=["canvas","surface","elevated"],$s=["ink","inkMuted","inkDim"],ci=4.5,G1=3,z1=1.5,$g=["danger","success","warning","info"],Dg={hover:.05,selected:.08,field:.05,work:.08},Ng=4,K1=1.5,Ul=.96,V1=["sunken","surface"],Lg=3.5,Oc=e=>{const t=e.replace("#",""),n=t.length===3?t.split("").map(a=>a+a).join(""):t.slice(0,6),[r,o,i]=[0,2,4].map(a=>{const c=Number.parseInt(n.slice(a,a+2),16)/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4});return .2126*r+.7152*o+.0722*i},Zr=(e,t)=>{const[n,r]=[Oc(e),Oc(t)].sort((o,i)=>i-o);return(n+.05)/(r+.05)},Nf=(e,t)=>Number.parseInt(e.slice(1+t*2,3+t*2),16),Ln=e=>`#${e.toString(16).padStart(2,"0").repeat(3)}`,st=(e,t,n)=>`#${[0,1,2].map(r=>Math.round(Nf(e,r)*t+Nf(n,r)*(1-t)).toString(16).padStart(2,"0")).join("")}`,Mt=e=>Oc(e.canvas)<.18?"dark":"light",Fg=(e,t,n,r,o=ci)=>{for(let i=.2;i<=1.0001;i+=.01)if(Zr(e[n],st(e[t],i,r))>=o)return Math.round(i*100)/100;return 1},Bl=(e,t,n,r,o)=>{for(let i=.2;i<=1.0001;i+=.01){const a=st(e[t],i,r);if(Zr(e[n],st(e.ink,o,a))>=(n==="inkDim"?Lg:ci))return Math.round(i*100)/100}return 1},Z1=(e,t)=>st(e.ink,t,e.borderControl);function Y1(e,t){const n={};for(const r of["dark","light"]){let o=0;for(const i of Object.keys(yn))for(const{palette:a}of t){if(Mt(a)!==r)continue;const c=st(a.canvas,e[i][r].canvas,Ln(yn[i][r]));let l=.01;for(;l<1&&fe(st(a.ink,l,c),c)<Ng;)l=Math.round((l+.01)*100)/100;o=Math.max(o,l)}n[r]=Math.round(o*100)/100}return n}function X1(e,t=Dg){const n={};for(const[r,o]of Object.entries(yn)){n[r]={};for(const i of["dark","light"]){n[r][i]={};for(const a of Fl){let c=0;for(const{palette:l}of e)if(Mt(l)===i)for(const d of $s)c=Math.max(c,Fg(l,a,d,Ln(o[i])),...Object.values(t).map(u=>Bl(l,a,d,Ln(o[i]),u)));n[r][i][a]=Math.min(1,Math.round((c+.02)*100)/100)}}}return n}function J1(e){const t={};for(const n of["dark","light"]){let r=0;for(const{palette:o}of e){if(Mt(o)!==n)continue;const i=n==="dark"?"#ffffff":"#000000";for(const a of $s)r=Math.max(r,Fg(o,"elevated",a,i,a==="inkDim"?Lg:ci))}t[n]=Math.round(r*100)/100}return t}function Ug(e,t){let n=1;for(const r of Object.keys(e))n=Math.min(n,e[r][t]?.canvas??1);return n}function Bg(e,t,n,r){const o=r==="dark"?"#ffffff":"#000000";return st(e.elevated,t,st(e.canvas,Ug(n,r),o))}function Q1(e,t){const n={};for(const r of["dark","light"]){const o=Ug(t,r),i=r==="dark"?"#ffffff":"#000000";let a=0;for(const{palette:c}of e){if(Mt(c)!==r)continue;const l=st(c.canvas,o,i);for(const d of["inkMuted","ink"]){let u=.2;for(;u<=1.0001&&!(Zr(c[d],st(c.elevated,u,l))>=ci);u+=.01);a=Math.max(a,Math.round(Math.min(u,1)*100)/100)}}n[r]=Math.round(a*100)/100}return n}function q1(e,t,n){const r={};for(const o of["dark","light"]){let i=0;for(const{palette:a}of e){if(Mt(a)!==o)continue;const c=Bg(a,n[o],t,o);for(const l of $g){let d=0;for(;d<=1.0001&&!(Zr(st(a.ink,d,a[l]),c)>=ci);d+=.05);i=Math.max(i,Math.round(Math.min(d,1)*100)/100)}}r[o]=Math.round(i*100)/100}return r}function eT(e,t,n){const r={};for(const o of["dark","light"]){const i=n[o],a=Math.max(Ul,i),c=[Math.round((a-.8*(a-i))*100)/100,i];let l=0;for(const{palette:d}of e)if(Mt(d)===o)for(const u of c){const f=Bg(d,u,t,o);let h=0;for(;h<=1.0001&&!(Zr(st(d.ink,h,d.hairline),f)>=z1);h+=.05);l=Math.max(l,Math.round(Math.min(h,1)*100)/100)}r[o]=Math.round(l*100)/100}return r}function tT(e,t){const n={};for(const[r,o]of Object.entries(yn)){n[r]={};for(const i of["dark","light"]){let a=0;for(const{palette:c}of t)if(Mt(c)===i)for(const l of Fl){const d=st(c[l],e[r][i][l],Ln(o[i]));let u=0;for(;u<1&&Zr(Z1(c,u),d)<G1;)u=Math.round((u+.05)*100)/100;a=Math.max(a,u)}n[r][i]=Math.min(1,Math.round((a+.05)*100)/100)}}return n}const ao=new Map;function nT(e){const t=Mt(e),n=r=>Object.values(yn).every(o=>Fl.every(i=>$s.every(a=>Bl(e,i,a,Ln(o[t]),r)<=.95)));return Object.fromEntries(Object.entries(Dg).map(([r,o])=>{let i=o;for(;i>.01&&!n(i);)i=Math.round((i-.01)*100)/100;return[r,i]}))}function rT(e,t){const n=Mt(e);let r=Y1(t,[{palette:e}])[n];const o=()=>Object.entries(yn).every(([i,a])=>Array.from({length:101},(c,l)=>{const d=t[i][n].canvas,u=Math.max(Ul,d),f=Math.round((u-l/100*(u-d))*100)/100,h=st(e.canvas,f,Ln(a[n]));return fe(st(e.ink,r,h),h)>=Ng}).every(Boolean));for(;r<1&&!o();)r=Math.round((r+.01)*100)/100;return{dark:0,light:0,[n]:r}}function oT(e,t){const n=Mt(e);for(const r of V1)for(let o=5;o<=104;o++){const i=o/100;if(Object.entries(yn).every(([c,l])=>Array.from({length:101},(d,u)=>{const f=t[c][n].canvas,h=Math.max(Ul,f),_=Math.round((h-u/100*(h-f))*100)/100,y=Math.round(_*i*100)/100;if(y>1)return!1;const v=st(e.canvas,_,Ln(l[n]));return fe(st(e[r],y,v),v)>=K1}).every(Boolean)))return{dark:{role:r,scale:i},light:{role:r,scale:i}}}return null}function iT(e,t){const n=Mt(e);for(;;){const r=rT(e,t);let o=!1;for(const[i,a]of Object.entries(yn)){const c=Math.min(1,Math.round((Math.max(...$s.map(l=>Bl(e,"canvas",l,Ln(a[n]),r[n])))+.02)*100)/100);c>t[i][n].canvas&&(t[i][n].canvas=c,o=!0)}if(!o)return r}}const sT=["canvas","surface","elevated","sunken","ink","inkMuted","inkDim","borderControl","hairline",...$g];function aT(e){for(const t of sT){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 rL(e){aT(e);const t=JSON.stringify(e),n=ao.get(t);if(n)return n;const r=[{palette:e}],o=nT(e),i=X1(r,o);let a,c;for(let u=0;u<=99;u++){let f=!1;for(const h of Object.keys(yn)){const _=Mt(e),y=i[h][_].canvas,v=Math.max(y,u/100);f||=v!==y,i[h][_].canvas=v}if(!(u>0&&!f)&&(a=iT(e,i),c=oT(e,i),c))break}if(!c)throw new Error("palette roles cannot form a readable transparent lane");const l=Q1(r,i),d={alphaFloor:i,blockVeil:a,laneWash:c,controlMix:tT(i,r),bandFloor:J1(r),overlayFloor:l,overlayInkMix:q1(r,i,l),overlayEdgeMix:eT(r,i,l),stateAlpha:o};return ao.set(t,d),ao.size>8&&ao.delete(ao.keys().next().value),d}const Pc=new WeakMap,cT=(e,t)=>{t?Pc.set(e,t):Pc.delete(e)},oL=e=>Pc.get(e);/**
47
- * @remix-run/router v1.23.0
48
- *
49
- * Copyright (c) Remix Software Inc.
50
- *
51
- * This source code is licensed under the MIT license found in the
52
- * LICENSE.md file in the root directory of this source tree.
53
- *
54
- * @license MIT
55
- */function Jo(){return Jo=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},Jo.apply(this,arguments)}var Tn;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Tn||(Tn={}));const Lf="popstate";function iL(e){e===void 0&&(e={});function t(o,i){let{pathname:a="/",search:c="",hash:l=""}=lr(o.location.hash.substr(1));return!a.startsWith("/")&&!a.startsWith(".")&&(a="/"+a),Mc("",{pathname:a,search:c,hash:l},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function n(o,i){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 i=="string"?i:Hg(i))}function r(o,i){Hl(o.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(i)+")")}return dT(t,n,r,e)}function Ye(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Hl(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function lT(){return Math.random().toString(36).substr(2,8)}function Ff(e,t){return{usr:e.state,key:e.key,idx:t}}function Mc(e,t,n,r){return n===void 0&&(n=null),Jo({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?lr(t):t,{state:n,key:t&&t.key||r||lT()})}function Hg(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 dT(e,t,n,r){r===void 0&&(r={});let{window:o=document.defaultView,v5Compat:i=!1}=r,a=o.history,c=Tn.Pop,l=null,d=u();d==null&&(d=0,a.replaceState(Jo({},a.state,{idx:d}),""));function u(){return(a.state||{idx:null}).idx}function f(){c=Tn.Pop;let b=u(),p=b==null?null:b-d;d=b,l&&l({action:c,location:v.location,delta:p})}function h(b,p){c=Tn.Push;let A=Mc(v.location,b,p);n&&n(A,b),d=u()+1;let k=Ff(A,d),M=v.createHref(A);try{a.pushState(k,"",M)}catch(P){if(P instanceof DOMException&&P.name==="DataCloneError")throw P;o.location.assign(M)}i&&l&&l({action:c,location:v.location,delta:1})}function _(b,p){c=Tn.Replace;let A=Mc(v.location,b,p);n&&n(A,b),d=u();let k=Ff(A,d),M=v.createHref(A);a.replaceState(k,"",M),i&&l&&l({action:c,location:v.location,delta:0})}function y(b){let p=o.location.origin!=="null"?o.location.origin:o.location.href,A=typeof b=="string"?b:Hg(b);return A=A.replace(/ $/,"%20"),Ye(p,"No window.location.(origin|href) available to create URL for href: "+A),new URL(A,p)}let v={get action(){return c},get location(){return e(o,a)},listen(b){if(l)throw new Error("A history only accepts one active listener");return o.addEventListener(Lf,f),l=b,()=>{o.removeEventListener(Lf,f),l=null}},createHref(b){return t(o,b)},createURL:y,encodeLocation(b){let p=y(b);return{pathname:p.pathname,search:p.search,hash:p.hash}},push:h,replace:_,go(b){return a.go(b)}};return v}var Uf;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Uf||(Uf={}));function uT(e,t,n){return n===void 0&&(n="/"),fT(e,t,n)}function fT(e,t,n,r){let o=typeof t=="string"?lr(t):t,i=zg(o.pathname||"/",n);if(i==null)return null;let a=Wg(e);pT(a);let c=null;for(let l=0;c==null&&l<a.length;++l){let d=IT(i);c=kT(a[l],d)}return c}function Wg(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let o=(i,a,c)=>{let l={relativePath:c===void 0?i.path||"":c,caseSensitive:i.caseSensitive===!0,childrenIndex:a,route:i};l.relativePath.startsWith("/")&&(Ye(l.relativePath.startsWith(r),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(r.length));let d=On([r,l.relativePath]),u=n.concat(l);i.children&&i.children.length>0&&(Ye(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),Wg(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:yT(d,i.index),routesMeta:u})};return e.forEach((i,a)=>{var c;if(i.path===""||!((c=i.path)!=null&&c.includes("?")))o(i,a);else for(let l of Gg(i.path))o(i,a,l)}),t}function Gg(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,o=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return o?[i,""]:[i];let a=Gg(r.join("/")),c=[];return c.push(...a.map(l=>l===""?i:[i,l].join("/"))),o&&c.push(...a),c.map(l=>e.startsWith("/")&&l===""?"/":l)}function pT(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:wT(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const hT=/^:[\w-]+$/,mT=3,gT=2,_T=1,bT=10,vT=-2,Bf=e=>e==="*";function yT(e,t){let n=e.split("/"),r=n.length;return n.some(Bf)&&(r+=vT),t&&(r+=gT),n.filter(o=>!Bf(o)).reduce((o,i)=>o+(hT.test(i)?mT:i===""?_T:bT),r)}function wT(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 kT(e,t,n){let{routesMeta:r}=e,o={},i="/",a=[];for(let c=0;c<r.length;++c){let l=r[c],d=c===r.length-1,u=i==="/"?t:t.slice(i.length)||"/",f=ST({path:l.relativePath,caseSensitive:l.caseSensitive,end:d},u),h=l.route;if(!f)return null;Object.assign(o,f.params),a.push({params:o,pathname:On([i,f.pathname]),pathnameBase:TT(On([i,f.pathnameBase])),route:h}),f.pathnameBase!=="/"&&(i=On([i,f.pathnameBase]))}return a}function ST(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=ET(e.path,e.caseSensitive,e.end),o=t.match(n);if(!o)return null;let i=o[0],a=i.replace(/(.)\/+$/,"$1"),c=o.slice(1);return{params:r.reduce((d,u,f)=>{let{paramName:h,isOptional:_}=u;if(h==="*"){let v=c[f]||"";a=i.slice(0,i.length-v.length).replace(/(.)\/+$/,"$1")}const y=c[f];return _&&!y?d[h]=void 0:d[h]=(y||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:a,pattern:e}}function ET(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Hl(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let 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 IT(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Hl(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function zg(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function AT(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:RT(n,t):t,search:CT(r),hash:OT(o)}}function RT(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 Ma(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 xT(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Wl(e,t){let n=xT(e);return t?n.map((r,o)=>o===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Gl(e,t,n,r){r===void 0&&(r=!1);let o;typeof e=="string"?o=lr(e):(o=Jo({},e),Ye(!o.pathname||!o.pathname.includes("?"),Ma("?","pathname","search",o)),Ye(!o.pathname||!o.pathname.includes("#"),Ma("#","pathname","hash",o)),Ye(!o.search||!o.search.includes("#"),Ma("#","search","hash",o)));let i=e===""||o.pathname==="",a=i?"/":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=AT(o,c),d=a&&a!=="/"&&a.endsWith("/"),u=(i||a===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(d||u)&&(l.pathname+="/"),l}const On=e=>e.join("/").replace(/\/\/+/g,"/"),TT=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),CT=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,OT=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function PT(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Kg=["post","put","patch","delete"];new Set(Kg);const MT=["get",...Kg];new Set(MT);/**
56
- * React Router v6.30.0
57
- *
58
- * Copyright (c) Remix Software Inc.
59
- *
60
- * This source code is licensed under the MIT license found in the
61
- * LICENSE.md file in the root directory of this source tree.
62
- *
63
- * @license MIT
64
- */function Qo(){return Qo=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},Qo.apply(this,arguments)}const zl=x.createContext(null),jT=x.createContext(null),dr=x.createContext(null),Ds=x.createContext(null),wn=x.createContext({outlet:null,matches:[],isDataRoute:!1}),Vg=x.createContext(null);function sL(e,t){let{relative:n}=t===void 0?{}:t;Yr()||Ye(!1);let{basename:r,navigator:o}=x.useContext(dr),{hash:i,pathname:a,search:c}=NT(e,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:On([r,a])),o.createHref({pathname:l,search:c,hash:i})}function Yr(){return x.useContext(Ds)!=null}function Ns(){return Yr()||Ye(!1),x.useContext(Ds).location}function Zg(e){x.useContext(dr).static||x.useLayoutEffect(e)}function $T(){let{isDataRoute:e}=x.useContext(wn);return e?YT():DT()}function DT(){Yr()||Ye(!1);let e=x.useContext(zl),{basename:t,future:n,navigator:r}=x.useContext(dr),{matches:o}=x.useContext(wn),{pathname:i}=Ns(),a=JSON.stringify(Wl(o,n.v7_relativeSplatPath)),c=x.useRef(!1);return Zg(()=>{c.current=!0}),x.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=Gl(d,JSON.parse(a),i,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:On([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,a,i,e])}function aL(){let{matches:e}=x.useContext(wn),t=e[e.length-1];return t?t.params:{}}function NT(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=x.useContext(dr),{matches:o}=x.useContext(wn),{pathname:i}=Ns(),a=JSON.stringify(Wl(o,r.v7_relativeSplatPath));return x.useMemo(()=>Gl(e,JSON.parse(a),i,n==="path"),[e,a,i,n])}function LT(e,t){return FT(e,t)}function FT(e,t,n,r){Yr()||Ye(!1);let{navigator:o,static:i}=x.useContext(dr),{matches:a}=x.useContext(wn),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=Ns(),f;if(t){var h;let p=typeof t=="string"?lr(t):t;d==="/"||(h=p.pathname)!=null&&h.startsWith(d)||Ye(!1),f=p}else f=u;let _=f.pathname||"/",y=_;if(d!=="/"){let p=d.replace(/^\//,"").split("/");y="/"+_.replace(/^\//,"").split("/").slice(p.length).join("/")}let v=uT(e,{pathname:y}),b=GT(v&&v.map(p=>Object.assign({},p,{params:Object.assign({},l,p.params),pathname:On([d,o.encodeLocation?o.encodeLocation(p.pathname).pathname:p.pathname]),pathnameBase:p.pathnameBase==="/"?d:On([d,o.encodeLocation?o.encodeLocation(p.pathnameBase).pathname:p.pathnameBase])})),a,n,r);return t&&b?x.createElement(Ds.Provider,{value:{location:Qo({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:Tn.Pop}},b):b}function UT(){let e=ZT(),t=PT(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,o={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return x.createElement(x.Fragment,null,x.createElement("h2",null,"Unexpected Application Error!"),x.createElement("h3",{style:{fontStyle:"italic"}},t),n?x.createElement("pre",{style:o},n):null,null)}const BT=x.createElement(UT,null);class HT extends x.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?x.createElement(wn.Provider,{value:this.props.routeContext},x.createElement(Vg.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function WT(e){let{routeContext:t,match:n,children:r}=e,o=x.useContext(zl);return o&&o.static&&o.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(o.staticContext._deepestRenderedBoundaryId=n.route.id),x.createElement(wn.Provider,{value:t},r)}function GT(e,t,n,r){var o;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var i;if(!n)return null;if(n.errors)e=n.matches;else if((i=r)!=null&&i.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||Ye(!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:_}=n,y=f.route.loader&&h[f.route.id]===void 0&&(!_||_[f.route.id]===void 0);if(f.route.lazy||y){l=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}return a.reduceRight((u,f,h)=>{let _,y=!1,v=null,b=null;n&&(_=c&&f.route.id?c[f.route.id]:void 0,v=f.route.errorElement||BT,l&&(d<0&&h===0?(XT("route-fallback"),y=!0,b=null):d===h&&(y=!0,b=f.route.hydrateFallbackElement||null)));let p=t.concat(a.slice(0,h+1)),A=()=>{let k;return _?k=v:y?k=b:f.route.Component?k=x.createElement(f.route.Component,null):f.route.element?k=f.route.element:k=u,x.createElement(WT,{match:f,routeContext:{outlet:u,matches:p,isDataRoute:n!=null},children:k})};return n&&(f.route.ErrorBoundary||f.route.errorElement||h===0)?x.createElement(HT,{location:n.location,revalidation:n.revalidation,component:v,error:_,children:A(),routeContext:{outlet:null,matches:p,isDataRoute:!0}}):A()},null)}var Yg=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Yg||{}),Xg=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(Xg||{});function zT(e){let t=x.useContext(zl);return t||Ye(!1),t}function KT(e){let t=x.useContext(jT);return t||Ye(!1),t}function VT(e){let t=x.useContext(wn);return t||Ye(!1),t}function Jg(e){let t=VT(),n=t.matches[t.matches.length-1];return n.route.id||Ye(!1),n.route.id}function ZT(){var e;let t=x.useContext(Vg),n=KT(),r=Jg();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function YT(){let{router:e}=zT(Yg.UseNavigateStable),t=Jg(Xg.UseNavigateStable),n=x.useRef(!1);return Zg(()=>{n.current=!0}),x.useCallback(function(o,i){i===void 0&&(i={}),n.current&&(typeof o=="number"?e.navigate(o):e.navigate(o,Qo({fromRouteId:t},i)))},[e,t])}const Hf={};function XT(e,t,n){Hf[e]||(Hf[e]=!0)}function cL(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function lL(e){let{to:t,replace:n,state:r,relative:o}=e;Yr()||Ye(!1);let{future:i,static:a}=x.useContext(dr),{matches:c}=x.useContext(wn),{pathname:l}=Ns(),d=$T(),u=Gl(t,Wl(c,i.v7_relativeSplatPath),l,o==="path"),f=JSON.stringify(u);return x.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:o}),[d,f,o,n,r]),null}function JT(e){Ye(!1)}function dL(e){let{basename:t="/",children:n=null,location:r,navigationType:o=Tn.Pop,navigator:i,static:a=!1,future:c}=e;Yr()&&Ye(!1);let l=t.replace(/^\/*/,"/"),d=x.useMemo(()=>({basename:l,navigator:i,static:a,future:Qo({v7_relativeSplatPath:!1},c)}),[l,c,i,a]);typeof r=="string"&&(r=lr(r));let{pathname:u="/",search:f="",hash:h="",state:_=null,key:y="default"}=r,v=x.useMemo(()=>{let b=zg(u,l);return b==null?null:{location:{pathname:b,search:f,hash:h,state:_,key:y},navigationType:o}},[l,u,f,h,_,y,o]);return v==null?null:x.createElement(dr.Provider,{value:d},x.createElement(Ds.Provider,{children:n,value:v}))}function uL(e){let{children:t,location:n}=e;return LT(jc(t),n)}new Promise(()=>{});function jc(e,t){t===void 0&&(t=[]);let n=[];return x.Children.forEach(e,(r,o)=>{if(!x.isValidElement(r))return;let i=[...t,o];if(r.type===x.Fragment){n.push.apply(n,jc(r.props.children,i));return}r.type!==JT&&Ye(!1),!r.props.index||!r.props.children||Ye(!1);let a={id:r.props.id||i.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=jc(r.props.children,i)),n.push(a)}),n}const Ls=260,Kl=220,Vl=560,Qg=56,Zl=480,fL=8,Yl=44,Xl=400,qg=1200;function Jl(e){return Math.max(0,Math.min(qg,e-Zl))}function $c(e){return Jl(e)>=Xl?"docked":"overlay"}const QT=48,qT=16;function pL(e,t){if($c(e)==="docked")return{mode:"docked",width:Math.min(t,Jl(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,Xl),e-QT));return e-n>=qT?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function hL({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 eC(e,t=Ls,n=Yl){return $c(e-e_(t)-n)==="overlay"&&$c(e-Qg-n)==="docked"}function e_(e){return Number.isNaN(e)?Ls:Math.min(Vl,Math.max(Kl,e))}function tC(e,t=Yl){return Math.max(0,Math.min(Vl,e-Zl-t))}function mL(e,t,n=Ls,r=!1,o=Yl){const i=!t&&r&&eC(e,n,o),a=t||i,c=tC(e,o);return{mode:a?"strip":"docked",width:a?Qg:Math.min(e_(n),c),collapsed:a,resizable:!a&&c>=Kl}}function gL(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const _L=e=>e?"⌘B":"Ctrl+B",nC="data-canvas-shortcuts",rC=`[${nC}]`,oC=e=>t_(e,rC),iC='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',bL=e=>t_(e,iC);function t_(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const vL=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&oC(e.target)?"new-file":null},n_="small",sC=["small","medium","large"],r_="before:absolute before:-inset-0.5 before:content-['']",aC={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:r_},medium:{px:28,className:"size-7",glyphClassName:"size-3.5",hitClassName:""},large:{px:36,className:"size-9",glyphClassName:"size-4",hitClassName:""}},cC={small:{px:4,className:"mb-1"},medium:{px:6,className:"mb-1.5"},large:{px:8,className:"mb-2"}},yL={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:r_,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 wL(e){for(const t of sC)if(e===t)return t;return n_}function kL(e){return aC[e].px+cC[e].px}const o_="delegating",Oi=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,ja=e=>Math.max(1,Math.floor(e)),lC=e=>e===o_,i_=e=>e.locality==="remote"&&e.link_down===!0||e.peer_reach==="not-attempted"||e.peer_reach==="unknown";function Ql(e){return i_(e)?!1:typeof e.background_work=="boolean"?e.background_work:e.status?.code===o_}const dC=Intl.ListFormat;let $a=null;const uC=e=>{const t=sn();return $a?.tag!==t&&($a={tag:t,format:new dC(t,{type:"conjunction",style:"narrow"})}),$a.format.format(e)};function SL(e){if(i_(e))return"";const t=Ql(e);if(!t&&typeof e.background_work=="boolean")return"";const n=!lC(e.status?.code),r=[];n&&Oi(e.subagents_running)&&r.push(g("ui.chat.sidebar.row.bg.subagents",{count:ja(e.subagents_running)})),t&&Oi(e.jobs_running)&&r.push(g("ui.chat.sidebar.row.bg.jobs",{count:ja(e.jobs_running)}));const o=[];if(r.length>0&&o.push(g("ui.chat.sidebar.row.bg.running",{items:uC(r)})),n&&Oi(e.subagents_queued)){const i=ja(e.subagents_queued);o.push(r.length>0?g("ui.chat.sidebar.row.bg.queued",{count:i}):g("ui.chat.sidebar.row.bg.subagents_queued",{count:i}))}return t&&o.length===0&&e.status?.code!=="waiting"&&Oi(e.waiting_on)&&o.push(g("ui.chat.sidebar.row.bg.waiting")),o.join(" · ")}const fC=new Set(["idle","recent"]);function EL(e,t){return t!==""&&fC.has(e.status?.code??"recent")&&Ql(e)}const pC=["active","created"],IL={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"},hC=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function Fs(e){return hC.has(e.status?.code??"")||Ql(e)}const mC=new Set(["approval","answer"]);function s_(e){return mC.has(e.status?.code??"")}const gC=24*60*60*1e3,_C=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function ql(e,t){const n=t==="created"?e.created_at:e.updated_at;return typeof n!="number"||!Number.isFinite(n)||n<=0?null:n*1e3}const bC="last_user_at";function vC(e){const t=e[bC],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 yC(e,t,n){if(Fs(e))return"running";const r=ql(e,n);if(r===null)return"older";const o=_C(t);return r>=o?"today":r>=o-6*gC?"week":"older"}function AL(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const o of e)r[yC(o,t,n)].push(o);return r}function a_(e,t,n){const r=ql(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 i=Math.floor(o/60);if(i<24)return{unit:"hour",count:i};const a=Math.floor(i/24);return a<7?{unit:"day",count:a}:a<365?{unit:"week",count:Math.floor(a/7)}:{unit:"year",count:Math.floor(a/365)}}function RL(e,t,n){const r=a_(e,t,n);return r?g("ui.chat.sidebar_view.relative_short",r):""}function xL(e,t,n){const r=a_(e,t,n);return r?n==="created"?g("ui.chat.sidebar_view.relative_created",r):g("ui.chat.sidebar_view.relative_active",r):""}const Dc=["pinned","running","today","week","older","agents","teams"],TL={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 CL(e){return e==="agents"||e==="teams"}const qo=8;function wC(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function OL(e,t){return{...e,[t]:(e[t]??qo)+qo}}function PL(e,t,n,r,o){const i=!(e[n]??r);return{expanded:{...e,[n]:i},caps:!i&&!o?wC(t,n):t}}function c_(e){return`tag:${e}`}function l_(e,t){return e[c_(t)]===!1}function ML(e,t){const n=c_(t);if(l_(e,t)){const{[n]:r,...o}=e;return o}return{...e,[n]:!1}}function jL(e,t,n){return l_(t,n)?[]:e}function $L(e,t,n,r){return(e||t!=="")&&(r>qo||n.trim()!=="")}const DL="Collapse, then reopen, to restore the compact list";function NL(e){return(e??qo)>qo}const LL=e=>`section-grown-hint-${e}`,FL=e=>g("ui.chat.sidebar.catalogue.show_more",{hidden:e});function UL(e,t){return t==="agents"?g("ui.chat.sidebar.catalogue.show_more_agents",{count:e}):g("ui.chat.sidebar.catalogue.show_more_teams",{count:e})}function BL(e,t){return e.groupBy==="tag"&&!t?"section":e.groupBy}function HL(e){return e.tagsEnabled||e.groupBy==="tag"}const Er={hidden:[],order:[...Dc],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},kC=10,co=[25,50],SC=50,EC=500,IC=64,AC=2;function WL(e){return e.groupBy==="tag"?Math.max(e.loads,AC):e.loads}function Ur(e){const t=Math.max(0,Math.floor(e));return t===0?kC:t<=co.length?co[t-1]:co[co.length-1]+(t-co.length)*SC}function GL(e,t){const n=Ur(e+1)-Ur(e),r=Math.max(0,Math.min(n,t));return g("ui.chat.sidebar.catalogue.show_more_chats",{add:r})}function zL(e,t,n){const r=Ur(t+1)-Ur(t),o=Ur(t),i=Math.min(o+r,e.length);let a=0;for(let l=o;l<i;l+=1)Us(e[l])&&(a+=1);const c=Math.max(0,i-o-a);return c>0?c:Math.max(0,Math.min(r,n))}function KL(e,t){if(!t)return null;const n=e.filter(r=>Us(r));return n.length===0?null:{row:n.find(r=>s_(r))??n[0],count:n.length}}function Us(e){return Fs(e)}function RC(e){return s_(e)?0:Fs(e)?1:2}function xC(e,t){return Fs(e)?vC(e):ql(e,t)}function TC(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function VL(e,t,n){const r=e.map((o,i)=>({row:o,index:i,lane:t==="active-first"?RC(o):0,at:xC(o,n)}));return r.sort((o,i)=>o.lane-i.lane||TC(o.at,i.at)||o.index-i.index),r.map(o=>o.row)}function ZL(e,t){const{limit:n,currentId:r,searching:o=!1}=t;if(o)return{rows:[...e],lifted:!1,remaining:0};const i=[];let a=Math.max(0,n);for(const d of e){if(a>0){i.push(d),a-=1;continue}Us(d)&&i.push(d)}const c=Math.max(0,e.length-i.length);if(!r)return{rows:i,lifted:!1,remaining:c};const l=e.find(d=>d.session_id===r)??null;return l===null||i.includes(l)?{rows:i,lifted:!1,remaining:c}:{rows:[l,...i],lifted:!0,remaining:c}}function YL(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=Ur(t.loads),r=[];let o=n;for(const l of e){if(Us(l)){r.push(l);continue}o>0&&(r.push(l),o-=1)}const i=t.currentId,a=i==null?null:e.find(l=>l.session_id===i)??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 XL(e){if(e.add<=0)return null;const t=g("ui.chat.sidebar.catalogue.show_more_chats",{add:e.add});if(e.drawn>=e.total)return{label:t,aria:t};const n=`${e.drawn} of ${e.total}`;return{label:`${t} · ${n}`,aria:`${t} · ${n}`}}const CC="mt-4",OC="mt-2";function JL(e){return e?CC:OC}function QL(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function qL(e,t){if(t==="section"||t==="tag")return null;if(t==="flat")return[{key:"all",label:"",rows:[...e]}];const n=new Map;for(const i of e){const a=i.binding?.team||i.binding?.agent||"",c=a||"ungrouped",l=n.get(c)??{key:c,label:a||g("ui.chat.sidebar_view.ungrouped"),rows:[]};l.rows.push(i),n.set(c,l)}const r=[...n.values()],o=r.findIndex(i=>i.key==="ungrouped");return o>0&&r.push(...r.splice(o,1)),r}function PC(e,t){return!e.hidden.includes(t)}function d_(e){return e.order.filter(t=>PC(e,t))}function eF(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function tF(e,t,n){const r=d_(e),o=r.indexOf(t),i=r[o+n];if(o<0||i===void 0)return e;const a=e.order.indexOf(t),c=e.order.indexOf(i),l=[...e.order];return l[a]=i,l[c]=t,{...e,order:l}}const MC=["running","today","week","older"];function Wf(e){return MC.includes(e)}function nF(e,t,n,r){if(!Wf(t)||r&&!r(t))return!1;const o=d_(e),i=o.indexOf(t);if(i<0)return!1;const a=o[i+n];return a===void 0||!Wf(a)?!1:r?r(a):!0}const jC=["section","tag","agent","flat"],$C=["active-first","recent"];function rF(e){if(typeof e!="object"||e===null)return Er;const t=e,n=new Set(Dc),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 Dc)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 i=jC.includes(t.groupBy)?t.groupBy:Er.groupBy,a=pC.includes(t.basis)?t.basis:Er.basis,c=$C.includes(t.orderBy)?t.orderBy:Er.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(EC,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>=IC)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:i,tagsEnabled:typeof t.tagsEnabled=="boolean"?t.tagsEnabled:!1,autoTagForks:typeof t.autoTagForks=="boolean"?t.autoTagForks:Er.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const u_={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},DC=["recent","name","kind","modified","created","size"],NC=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function ed(e){const t=e&&typeof e=="object"?e:{};return{sort:DC.includes(t.sort??"")?t.sort:u_.sort,order:t.order==="desc"?"desc":"asc",group:typeof t.group=="boolean"?t.group:!0,workingOpen:t.workingOpen===!0,closedSections:Array.isArray(t.closedSections)?[...new Set(t.closedSections.filter(n=>[ei,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>NC.includes(n)))]:[]}}const ei="Attachments";function oF(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 i=n(r),a=n(o);if(i===null||a===null)return i===a?0:i===null?1:-1;const c=typeof i=="string"&&typeof a=="string"?i.localeCompare(a,void 0,{numeric:!0}):Number(i)-Number(a);return(t.order==="asc"?c:-c)||r.mentioned-o.mentioned})}const LC=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 iF(e,t,n,r,o=[]){const i=e.filter(l=>l.highlighted),a=e.filter(l=>!l.highlighted),c=[];if(o.length&&c.push({id:ei,label:g("ui.canvas.files.attachments"),items:o,open:n||!r.has(ei),highlights:!1}),i.length&&c.push({id:"Highlights",label:g("ui.canvas.finder_layout.highlights"),items:i,open:n||!r.has("Highlights"),highlights:!0}),i.length&&a.length&&(c.push({id:"Working files",label:g("ui.canvas.finder_layout.working_files"),items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return c;if(!t.group)a.length&&c.push({id:"Files",label:g("ui.canvas.finder_layout.files"),items:a,open:!0,highlights:!1});else for(const l of["Images","Videos","Sounds","Documents","Spreadsheets","Other"]){const d=a.filter(u=>LC(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const FC=32,sF=4,f_=32,p_=18;function aF(e){return e.height-f_-(e.kind==="tiles"&&e.section.id===ei?p_:0)}function cF(e,t,n){const r=[],o=new Map,i=Math.max(136,t-16),a=Math.max(1,Math.floor((i+4)/140));let c=0;const l=(d,u,f,h,_=1)=>{h.forEach((y,v)=>o.set(y.row.document.id,{band:r.length,column:v})),r.push({section:d,kind:u,height:f,top:c,items:h,cols:_}),c+=f};for(const d of e)if(l(d,"header",FC,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(d.id===ei){const u=d.items.filter(y=>y.row.media!=="image"),f=d.items.filter(y=>y.row.media==="image");for(const y of u)l(d,"compact",36,[y]);const h=(i-4*(a-1))/a,_=Math.round((h-8)*3/4)+f_+p_;for(let y=0;y<f.length;y+=a)l(d,"tiles",_,f.slice(y,y+a),a)}else if(n&&d.id==="Images"){const u=(i-4*(a-1))/a,f=Math.round((u-8)*3/4)+32;for(let h=0;h<d.items.length;h+=a)l(d,"tiles",f,d.items.slice(h,h+a),a)}else if(n&&d.id==="Videos")for(const u of d.items)l(d,"video",Math.min(Math.round((i-8)*9/16),280)+32,[u]);else if(n&&d.id==="Sounds")for(const u of d.items)l(d,"audio",80,[u]);else for(const u of d.items)l(d,"compact",36,[u]);return{bands:r,height:c,columns:a,positions:o}}function lF(e,t,n,r){const o=Math.max(600,n*.75);let i=0,a=e.bands.length;for(;i<a;){const d=i+a>>>1,u=e.bands[d];u.top+u.height<t-o?i=d+1:a=d}const c=new Set;for(let d=i;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 dF(e,t,n,r){const o=e.positions.get(t);if(!o)return null;const i=e.bands[o.band],a=e.bands.filter(u=>u.section.id===i.section.id&&u.items.length);if(n==="Home")return a[0]?.items[0]?.row.document.id??null;if(n==="End")return a.at(-1)?.items.at(-1)?.row.document.id??null;if(n==="ArrowLeft"||n==="ArrowRight")return i.items[o.column+(n==="ArrowLeft"?-1:1)]?.row.document.id??null;const c=n==="ArrowUp"||n==="PageUp"?-1:1,l=i.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 UC="both",h_="by-turn",BC=[{value:"by-turn"},{value:"by-response"}];function uF(e){for(const t of BC)if(e===t.value)return t.value;return h_}function fF(e){return e==="by-response"?g("ui.settings.appearance.transcript_display_mode_setting.by_response"):g("ui.settings.appearance.transcript_display_mode_setting.by_turn")}const pF="primary+alt+shift+space",HC=/^f([1-9]|1[0-9]|2[0-4])$/;function WC(e){return HC.test(e)}function GC(e,t){const n=zC(e,t);return t==="mac"?n.join(""):n.join("+")}function zC(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(i=>i.trim().toLowerCase()).filter(i=>i.length>0).map(i=>i in r?r[i]:i in o?o[i]:WC(i)||i.length===1?i.toUpperCase():i)}const Bs=[{id:"panel.console",get label(){return g("ui.settings.shortcuts.action.open_console")},get category(){return g("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return g("ui.settings.shortcuts.action.open_canvas")},get category(){return g("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return g("ui.settings.shortcuts.action.open_run_details")},get category(){return g("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return g("ui.settings.shortcuts.action.open_asks")},get category(){return g("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return g("ui.settings.shortcuts.action.open_browser")},get category(){return g("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return g("ui.settings.shortcuts.action.open_code_review")},get category(){return g("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.projects",get label(){return g("ui.settings.shortcuts.action.open_linked_projects")},get category(){return g("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],KC=new Map(Bs.map(e=>[e.id,e])),VC=e=>KC.get(e),ZC=new Set(["primary+0","primary+r","primary+shift+r","primary+t","primary+shift+t","primary+l",...[1,2,3,4,5,6,7,8,9].map(e=>`primary+${e}`),"primary+shift+n"]);class YC 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 td=new YC([["primary+p",()=>g("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>g("ui.settings.shortcuts.reserved.palette_commands")],["primary+k",()=>g("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>g("ui.settings.shortcuts.reserved.new_chat")],["primary+shift+n",()=>g("ui.settings.shortcuts.new_temporary_chat")],["primary+b",()=>g("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>g("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>g("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>g("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>g("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>g("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>g("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>g("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>g("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>g("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>g("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>g("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>g("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>g("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>g("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>g("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>g("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>g("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>g("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>g("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>g("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>g("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>g("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>g("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>g("ui.settings.shortcuts.reserved.browser_last_tab"):()=>g("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>g("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>g("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>g("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>g("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>g("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>g("ui.settings.shortcuts.reserved.close")],["primary+m",()=>g("ui.settings.shortcuts.reserved.minimise")]]),XC=["primary","alt","shift"],JC={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},QC=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),qC=e=>QC.has(e)||/^[a-z0-9]$/.test(e);function nd(e){if(typeof e!="string")return null;const t=e.toLowerCase().split("+").map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return null;const n=t[t.length-1];if(!qC(n))return null;const r=new Set;for(const i of t.slice(0,-1)){const a=JC[i];if(a===void 0)return null;r.add(a)}return[...XC.filter(i=>r.has(i)),n].join("+")}const m_=e=>e.split("+").includes("primary");function Hs(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!td.has(n)?n:VC(e)?.defaultChord??null}function hF(e){const t=new Map;for(const n of Bs){const r=Hs(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const eO=e=>e==="mac"?g("ui.settings.shortcuts.capture.needs_modifier_mac"):g("ui.settings.shortcuts.capture.needs_modifier");function tO(e,t,n,r="linux",o=new Map){const i=e===null?null:nd(e);if(i===null)return g("ui.settings.shortcuts.capture.unbindable");if(!m_(i))return eO(r);const a=td.get(i);if(a!==void 0)return a;const c=o.get(i);if(c!==void 0)return g("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of Bs)if(l.id!==t&&Hs(l.id,n)===i)return g("ui.settings.shortcuts.capture.already_assigned",{label:l.label});return null}function nO(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const o of Bs){const i=t[o.id];if(i===null){r[o.id]=null;continue}const a=typeof i=="string"?nd(i):null,c=a!==null&&ZC.has(a),l=a!==null&&m_(a)&&(c||!td.has(a)&&!n.has(a))?a:null;l!==null&&(r[o.id]=l);const d=Hs(o.id,r);d!==null&&n.add(d)}return r}function mF(e,t,n){const r=Hs(e,t);return r===null?null:g_(r,n)}function g_(e,t){return GC(e,t)}function gF(e,t){const n=e.split("+"),r=n[n.length-1],o=n.slice(0,-1).map(i=>i==="primary"?t==="mac"?"Meta":"Control":i==="shift"?"Shift":i==="alt"?"Alt":i);return{glyph:g_(e,t),aria:[...o,r.length===1?r.toUpperCase():r].join("+")}}const Gf=e=>{for(const t of[e.role,...e.variants])if(!G_.includes(t))throw new Error(`Unknown accent role: ${t}`);return Object.freeze({...e,variants:Object.freeze(e.variants)})},__=Object.freeze([Gf({id:"primary",role:"accent",storage:"seeds",labelKey:"ui.settings.appearance.editor.accent.primary",usageKey:"ui.settings.appearance.editor.accent.primary_usage",variants:["accentHover","accentActive","accentWash","onAccent"],preview:"interaction",ink:"accent",wash:"accentWash"}),Gf({id:"secondary",role:"accentAlt",storage:"overrides",labelKey:"ui.settings.appearance.editor.accent.secondary",usageKey:"ui.settings.appearance.editor.accent.secondary_usage",variants:["accentAltWash"],preview:"identity",ink:"accentAlt",wash:"accentAltWash"})]),_F=e=>__.some(t=>t.role===e||t.variants.includes(e)),je={strongText:7,text:4.5,nonText:3},zf=new Set(["inkDisabled"]),Ze=["canvas","surface","elevated","sunken"],b_=[["ink",je.strongText],["inkMuted",5.5],["inkDim",5]],hn=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Xt={dark:{canvasMin:9,canvasMax:15,elevatedMax:22},light:{canvasMax:94,sunkenMin:80}},An={canvasSurface:[2.5,5],surfaceElevated:[2,6],canvasSunken:[1.5,6]},rO=2,oO=1.03,rd=8,ms=2,Kf=.8,Vf=3,Zf=2,Yf=4,Nc=2.5,Xf=4,Jf=2.5,Qf=2,qf=2,iO=[{name:"hub source confirmation remedy",on:["warningWash"],fill:"accent",border:"accent",ink:"onAccent"},{name:"hub source confirmation diagnostic",on:["canvas"],fill:"warningWash",border:"warningBorder",ink:"inkMuted"},{name:"browser find row",on:["elevated"],fill:"elevated",border:"borderControl",ink:"inkMuted"},{name:"browser address suggestions",on:["elevated"],fill:"elevated",border:"borderControl",ink:"inkMuted"},{name:"browser approvals card",on:["elevated"],fill:"elevated",border:"borderControl",ink:"inkMuted"},{name:"primary button",on:Ze,fill:"accent",border:"accent",ink:"onAccent"},{name:"primary button (hover)",on:Ze,fill:"accentHover",border:"accentHover",ink:"onAccent"},{name:"primary button (pressed)",on:Ze,fill:"accentActive",border:"accentActive",ink:"onAccent"},{name:"tonal button",on:["elevated"],fill:"sunken",border:null,ink:"ink",edge:!1},{name:"tonal button (hover)",on:["elevated"],fill:"surface",border:null,ink:"ink",edge:!1},{name:"tonal button (pressed)",on:["elevated"],fill:"hairline",border:null,ink:"ink",edge:!1},{name:"outline control",on:Ze,fill:null,border:"borderControl",ink:"ink"},{name:"team avatar bubble",on:["canvas","surface","rowSelected","rowHover"],fill:"elevated",border:null,ink:"inkDim",edge:!1},{name:"team bridge person initial plate",on:["canvas","surface","elevated","rowHover"],fill:"mediaSurface",border:null,ink:"inkMuted",edge:!1},{name:"notification sound radio ring",on:["canvas"],fill:null,border:"borderControl",ink:"ink"},{name:"notification sound radio ring (hover)",on:["rowHover"],fill:null,border:"inkMuted",ink:"ink"},{name:"notification sound radio ring (checked)",on:["canvas","rowHover"],fill:null,border:"accent",ink:"ink"},{name:"team bridge reaction pill",on:["surface","canvas","rowHover"],fill:"elevated",border:null,ink:"inkMuted",edge:!1},{name:"team bridge reaction pill (hover)",on:["surface","canvas","rowHover"],fill:"sunken",border:null,ink:"ink",edge:!1},{name:"team bridge thread row (rest, count)",on:["canvas","surface","elevated","rowHover"],fill:null,border:null,ink:"accent",edge:!1},{name:"team bridge thread row (rest, last reply)",on:["canvas","surface","elevated","rowHover"],fill:null,border:null,ink:"inkMuted",edge:!1},{name:"team bridge thread row (hover, count)",on:["canvas","surface","elevated","rowHover"],fill:"sunken",border:null,ink:"accent",edge:!1},{name:"team bridge thread row (hover, last reply)",on:["canvas","surface","elevated","rowHover"],fill:"sunken",border:null,ink:"inkMuted",edge:!1},{name:"team bridge attachment chip name",on:["surface","canvas","rowHover"],fill:"mediaSurface",border:null,ink:"ink",edge:!1},{name:"team bridge attachment chip meta",on:["surface","canvas","rowHover"],fill:"mediaSurface",border:null,ink:"inkDim",edge:!1},{name:"team bridge attachment chip kind tile",on:["mediaSurface"],fill:"elevated",border:null,ink:"inkMuted",edge:!1},{name:"team bridge file card failure glyph",on:["mediaSurface"],fill:"elevated",border:null,ink:"danger",edge:!1},{name:"team bridge image action cluster",on:["mediaSurface"],fill:"elevated",border:null,ink:"inkMuted",edge:!1},{name:"team bridge image action cluster (hover)",on:["elevated"],fill:"rowHover",border:null,ink:"ink",edge:!1},{name:"team bridge own reaction pill",on:["canvas","surface","rowHover"],fill:"accentWash",border:null,ink:"accent",edge:!1},{name:"team bridge own reaction pill (hover)",on:["canvas","surface","rowHover"],fill:"accentWash",border:null,ink:"accentHover",edge:!1},{name:"team bridge person identity plate",on:["canvas","surface","elevated","rowHover"],fill:"accentAltWash",border:null,ink:"accentAlt",edge:!1},{name:"team bridge agent identity plate",on:["canvas","surface","elevated","rowHover"],fill:"accentAltWash",border:null,ink:"accent",edge:!1},{name:"team bridge unknown sender plate",on:["canvas","surface","elevated","rowHover"],fill:"accentAltWash",border:null,ink:"inkMuted",edge:!1},{name:"team bridge new messages divider pill",on:["canvas","surface"],fill:"accent",border:null,ink:"onAccent"},{name:"team bridge reaction add (hover)",on:["surface","canvas","rowHover"],fill:"elevated",border:null,ink:"ink",edge:!1},{name:"team bridge plate on a selected rail row",on:["rowSelected"],fill:"surface",border:null,ink:"inkMuted",edge:!1},{name:"image actions trigger",on:Ze,fill:"accentWash",border:null,ink:"inkMuted",edge:!1},{name:"input field",on:Ze,fill:"surface",border:"borderControl",ink:"ink"},{name:"composer (read-only)",on:["canvas"],fill:"elevated",border:null,edge:!1,ink:"inkDisabled"},{name:"window caption glyphs (active)",on:["canvas","sunken"],fill:null,border:null,edge:!1,ink:"inkMuted"},{name:"window caption glyphs (inactive)",on:["canvas","sunken"],fill:null,border:null,edge:!1,ink:"inkDim"},{name:"composer insert transcript (success outline)",on:["surface"],fill:"successWash",border:"successBorder",ink:"success"},{name:"composer cancel recording (danger glyph on outline)",on:["surface"],fill:"surface",border:"borderControl",ink:"danger"},{name:"composer cancel recording (hover / focus, danger wash)",on:["surface"],fill:"dangerWash",border:"borderControl",ink:"danger"},{name:"success callout",on:["canvas","surface"],fill:"successWash",border:"successBorder",ink:"success"},{name:"warning callout",on:["canvas","surface"],fill:"warningWash",border:"warningBorder",ink:"warning"},{name:"danger callout",on:["canvas","surface"],fill:"dangerWash",border:"dangerBorder",ink:"danger"},{name:"members dialog remove confirm (danger sm)",on:["elevated"],fill:"elevated",border:"dangerBorder",ink:"danger"},{name:"info callout",on:["canvas","surface"],fill:"infoWash",border:"infoBorder",ink:"info"},{name:"primary button on the danger wash",on:["dangerWash"],fill:"accent",border:"accent",ink:"onAccent"},{name:"primary remedy on the warning wash",on:["warningWash"],fill:"accent",border:"accent",ink:"onAccent"},{name:"status band (warning)",on:["canvas"],fill:"warningWash",border:"warningBorder",ink:"ink"},{name:"status band (danger)",on:["canvas"],fill:"dangerWash",border:"dangerBorder",ink:"ink"},{name:"status band detail line (warning)",on:["canvas"],fill:"warningWash",border:"warningBorder",ink:"inkMuted"},{name:"status band detail line (danger)",on:["canvas"],fill:"dangerWash",border:"dangerBorder",ink:"inkMuted"},{name:"picker row pointer mark",on:["elevated"],fill:null,border:"borderControl",ink:"ink"},{name:"combobox option active mark",on:["elevated"],fill:null,border:"borderControl",ink:"ink"},{name:"accent wash chip",on:["canvas","surface"],fill:"accentWash",border:"accent",ink:"accent"},{name:"accent alt wash chip",on:["canvas","surface"],fill:"accentAltWash",border:"accentAlt",ink:"accentAlt"},{name:"credential pill",on:["canvas","elevated"],fill:"infoWash",border:"infoBorder",ink:"ink"},{name:"credential pill (unbacked)",on:["canvas","elevated"],fill:"warningWash",border:"warningBorder",ink:"ink"},{name:"credential chip",on:["canvas","surface"],fill:"infoWash",border:"infoBorder",ink:"ink"},{name:"credential chip (unbacked)",on:["canvas","surface"],fill:"warningWash",border:"warningBorder",ink:"ink"},{name:"credential chip clear",on:["canvas","surface"],fill:"infoWash",border:"infoBorder",ink:"inkMuted"},{name:"credential chip clear (unbacked)",on:["canvas","surface"],fill:"warningWash",border:"warningBorder",ink:"inkMuted"},{name:"ask option button",on:["canvas","surface"],fill:"surface",border:"borderControl",ink:"ink"},{name:"question dock card",on:["canvas"],fill:"elevated",border:"accent",ink:"ink"},{name:"ask option button (hover)",on:["canvas","surface"],fill:"elevated",border:"borderControl",ink:"ink"},{name:"ask change answer button",on:["surface"],fill:"surface",border:"borderControl",ink:"ink"},{name:"mini sheet",on:["canvas"],fill:"elevated",border:"borderControl",ink:"ink"},{name:"browser agent marker chip",on:["sunken","elevated"],fill:"accentWash",border:"accent",ink:"ink"},{name:"browser shared marker pill",on:["sunken","elevated"],fill:null,border:"borderControl",ink:"inkMuted"},{name:"browser restored marker pill",on:["sunken","elevated"],fill:null,border:"borderControl",ink:"inkDim"},{name:"browser waiting marker chip",on:["sunken","elevated"],fill:"warningWash",border:"borderControl",ink:"ink"},{name:"browser failed marker chip",on:["sunken","elevated"],fill:"dangerWash",border:"borderControl",ink:"ink"},{name:"browser active tab",on:["sunken"],fill:"elevated",border:"borderControl",ink:"ink"},{name:"browser dragged tab",on:["sunken"],fill:"rowSelected",border:"borderControl",ink:"ink"},{name:"browser approvals badge",on:["canvas","surface","rowSelected","rowHover"],fill:"warningWash",border:"inkMuted",ink:"ink"},{name:"rail approval badge (quiet)",on:["canvas","surface","rowSelected","rowHover"],fill:"elevated",border:null,ink:"inkDim",edge:!1},{name:"rail attention badge (emphasis)",on:["canvas","surface","rowSelected","rowHover","elevated","accentWash"],fill:"accent",border:null,ink:"onAccent"},{name:"session row ask mark",on:["surface","rowSelected","rowHover"],fill:null,border:null,ink:"inkMuted",edge:!1},{name:"browser pane scope switch track",on:["sunken"],fill:"sunken",border:"borderControl",ink:"ink"},{name:"browser approvals tray row (selected)",on:["surface"],fill:"elevated",border:"borderControl",ink:"ink"},{name:"browser approvals dock",on:["canvas","elevated"],fill:"surface",border:"borderControl",ink:"ink"},{name:"browser consent band",on:Ze,fill:"surface",border:"borderControl",ink:"ink"},{name:"browser file-transfer row (refused)",on:Ze,fill:"dangerWash",border:"borderControl",ink:"ink"},{name:"context wheel, calm reading",on:["elevated"],fill:null,border:"info",ink:"inkMuted"},{name:"context wheel, worth noticing",on:["elevated"],fill:null,border:"warning",ink:"inkMuted"},{name:"context wheel, compaction due",on:["elevated"],fill:null,border:"danger",ink:"inkMuted"},{name:"reading button, hovered",on:["surface","canvas"],fill:"accentWash",border:"accent",ink:"ink"},{name:"console terminal selection",on:["sunken"],fill:"accent",border:"accent",ink:"onAccent"},{name:"console terminal well",on:["surface"],fill:"sunken",border:"borderControl",ink:"ink"},{name:"mesh device node",on:["sunken"],fill:"elevated",border:"borderControl",ink:"ink"},{name:"installer rail ring markers",on:["canvas"],fill:null,border:"borderControl",ink:"ink"},{name:"mesh scope boundary (solid)",on:["sunken"],fill:null,border:"borderControl",ink:"inkMuted"},{name:"code review state pill (open)",on:["elevated","surface"],fill:"infoWash",border:"infoBorder",ink:"info"},{name:"code review state pill (merged)",on:["elevated","surface"],fill:"successWash",border:"successBorder",ink:"success"},{name:"code review state pill (draft)",on:["elevated","surface"],fill:null,border:"borderControl",ink:"ink"},{name:"code review state pill (closed)",on:["elevated","surface"],fill:"sunken",border:"hairline",ink:"inkMuted",edge:!1},{name:"library card",on:Ze,fill:"surface",border:null,ink:"ink",edge:!1},{name:"library card secondary",on:["surface"],fill:"surface",border:null,ink:"inkDim",edge:!1},{name:"library thumbnail well",on:["surface","canvas"],fill:"sunken",border:null,ink:"inkMuted",edge:!1},{name:"library origin badge",on:["surface","sunken"],fill:"elevated",border:null,ink:"inkMuted",edge:!1},{name:"library composer field",on:["canvas","surface"],fill:"elevated",border:null,ink:"ink",edge:!1}],sO=[{name:"context wheel arc against its track",a:["info","warning","danger"],b:"sunken",floor:je.nonText}],aO=[{name:"team bridge selected rail glyph",on:["rowSelected"],fg:"accent"},{name:"team bridge agent plate glyph",on:["mediaSurface","accentAltWash"],fg:"accent"},{name:"team bridge agent mark (corner notch)",on:["mediaSurface","surface","accentAltWash"],fg:"accent",floor:4},{name:"turn bar complete mark",on:["canvas"],fg:"success"},{name:"session row running lane",on:["surface","rowSelected","rowHover"],fg:"accent"},{name:"spinner track against its ground",on:Ze,fg:"borderControl"},...["success","warning","danger"].map(e=>({name:`usage bar fill (${e})`,on:["sunken"],fg:e})),...["success","warning","danger"].map(e=>({name:`usage status dot (${e})`,on:["surface"],fg:e})),...["success","warning","danger","info","inkDim"].map(e=>({name:`integration status dot (${e})`,on:["surface","rowSelected"],fg:e})),{name:"provider row overflow trigger glyph (open)",on:["borderControl"],fg:"onAccent"},{name:"search setup mode mark dot (checked)",on:["accent"],fg:"onAccent"},...["danger","info"].map(e=>({name:`run panel trigger dot (${e})`,on:["canvas","accentWash","surface","rowSelected","rowHover"],fg:e})),{name:"panel rail lit glyph and bar",on:["rowSelected","rowHover","surface","elevated","canvas"],fg:"accent"},{name:"panel rail idle glyph",on:["surface","rowHover"],fg:"inkMuted"},{name:"panel rail console blip and files dot (inkMuted)",on:["surface","rowHover","rowSelected"],fg:"inkMuted"},{name:"panel rail console blip (accent)",on:["surface","rowHover","rowSelected"],fg:"accent"},{name:"usage unmeasured mark",on:["surface"],fg:"inkDim"},{name:"checkpoint rail tick",on:["canvas"],fg:"inkDim"},{name:"panel proportion fill (accent)",on:["sunken"],fg:"accent"},{name:"panel chart bar (accent)",on:["surface"],fg:"accent"},{name:"link toolbar action icon (hovered)",on:["accentWash"],fg:"accent"},{name:"search result active bar (accent)",on:["accentWash"],fg:"accent"},{name:"code review round mark (findings open)",on:["elevated","surface"],fg:"warning"},{name:"code review round mark (remediation posted)",on:["elevated","surface"],fg:"inkMuted"},{name:"code review round mark (clean)",on:["elevated","surface"],fg:"success"},{name:"code review round mark (verdict not stated)",on:["elevated","surface"],fg:"borderControl"}],cO=[{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}],lO=["borderControl","accent","successBorder","warningBorder","dangerBorder","infoBorder"],dO=["accent","success","warning","danger","info"],uO=[{fg:"surface",on:"accent",floor:je.text,name:"the console terminal's cursor ink on its own cursor (9.1)"}],fO=[],pO=[{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"}],Ir=15,Ar=8,hO=[{theme:"catppuccinMocha",a:"accentAlt",b:"info",floor:Ir,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:Ir,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:Ir,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:Ir,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:Ir,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:Ar,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:Ar,got:0,why:"`info` IS `accent` (`#00EFFF`), the palette's single cyan"},{theme:"obsidian",a:"info",b:"accent",floor:Ar,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:Ar,got:0,why:"`info` IS `accent` (`#91B7E9`), the palette's single steel blue"},{theme:"githubLight",a:"info",b:"accent",floor:Ar,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"}],mO=[],gO=[],_O=["mode",...Ze,"rowHover","rowSelected","messageSurface","mediaSurface","ink","inkMuted","inkDim","inkDisabled","hairline","borderControl","accent","accentHover","accentActive","accentWash","onAccent","accentAlt","accentAltWash","chartBarHover","tokenCommand","success","successWash","successBorder","warning","warningWash","warningBorder","danger","dangerWash","dangerBorder","info","infoWash","infoBorder","overlayShadow","scrim"],Pi=["success","warning","danger","info"],bO=["success","warning","danger","info","ink"],Or=8,lo="tokenCommand",Mi=Or,vO=["surface","elevated","messageSurface"],yO=[{theme:"obsidian",against:["ink","accent"],got:0,why:"monochrome: accent = ink = #FAFAFA. The run is separated by the semibold step, exactly as `functionName`/`className` are in code-mirror-theme.ts. Re-measure if ink or accent move."}],dn=15,ti=15,Ao=Or,ct=2,ep=4,wO=.75,tp=.12,np=.1,kO=[["surface","canvas"],["surface","elevated"],["elevated","canvas"]],SO=4,EO=2,IO=2,Da=1,gs=2,Na=2,rp=.5,AO=1.5,RO=1.5,v_=5,_s=2.5,y_=.5,bs=5,Lc=4,Fc=24,op=12,xO=.45,ip=.75,TO=.25,mn=2,w_=2,CO=[{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"}],OO=[{id:"catppuccinMacchiato",role:"rowSelected",bound:"rank",measured:.94,reason:"the INK FLOORS are what refuse the rank: this palette's whole legal step is 2.68 L*, so the selection cannot rise past it and the hover cannot fall without putting `inkDim` under its floor on the hover instead. The pair still separates by ΔE00 6.96 and ranks 4.9 C*, so this is the one palette in the fleet whose pair is ranked by cast rather than by lightness - which is the point of adding the C* rank at all"},{id:"rosePineDawn",role:"rowHover",bound:"band",measured:1.67,reason:"the fleet's minimum band, and it is the light family's compression at its worst: C* 2.7 puts the fill at the rule's own floor of 2.5, and at L* 94 the S_l term divides the 2.79 L* step down to 1.67. ITS CEILING IS 1.88, measured on this rule's own window: with the hover's cast held at the panel's own (C* 2.70, the rule's 2.5 floor), the largest hover the rule can author is bounded by its own clamp (`step_selected - 1.15` = 2.99 at the shipped selection step of 4.14, where `inkDim` is 5.02), and both that target and the looser rank bound above it (`step_selected - 1.0` = 3.14) resolve to the SAME 8-bit rung, `#F0EBE7` - a measured step of 3.14 and ΔE00 1.880 off `surface`. Raising the selection does not widen it either, because this palette's largest ink-legal step and the whole 4.10-4.30 band below it also resolve to one hex, `#F3E7DD`. Clearing the 2.0 field floor here needs the hover's cast OUTSIDE the window the rule names, and that is reachable at EITHER end, which is why this row's cause is not the ceiling alone: past it (C* 3.23 at step 2.99 measures ΔE00 2.03, 0.53 over the ceiling) or under its floor (C* 2.31 at step 2.94 is `#EFECE8`, ΔE00 2.01, 0.19 under the 2.5 floor) - both inside the slack the cap carries, which is the hex round trip's error and not a licence to sit outside the bound. So the class's floor on this palette is 1.9 and not 2.0, and if 2.0 is to hold here what changes is the floor's statement, not the value. The band's frame is committed and the disposition is a look judgement: at 1.67 it still reads as a mark"},{id:"gruvboxLight",role:"rowSelected",bound:"wash",measured:1.44,reason:"the wash proximity: this palette's `accentWash` is accent-derived and carries C* 20.6 at L* 93, which is inside the window the selection's own cast (the panel's 15.5 plus 4) may occupy. The palette has a cast in both the panel and the accent, so it is not in the neutral class, and the two fills are the same kind of thing at the same depth"},{id:"obsidian",role:"rowHover",bound:"wash",measured:1.38,reason:"the wash proximity on the palette the class was written for and no longer covers: `obsidian`'s panel carries C* 2.08, one hair INSIDE the colour rule where the class's threshold is 2.0, while its accent is #FAFAFA at C* 0 and its wash C* 1.36. There is no cast anywhere in this palette with which to separate two near-neutral fills, which is the class's own argument arriving at a palette the class's key no longer names - recorded here rather than widened there"}],Uc=10,ji="surface",sp=2,ap=1.15,PO=({composed:e=!1,capturePairs:t=!1}={})=>{const n={assertions:0,failures:0,composed:e},r=[],o=(R,m)=>e?m>=R-.01:Math.abs(R-m)<.01,i=(R,m,w)=>e?m>=R-w:Math.abs(R-m)<=w,a=new Set,c=(R,m,w,S)=>{const T=pO.find(N=>N.theme===R&&N.role===m&&N.ground===w&&o(N.got,S));return T&&a.add(T),T},l=new Set,d=(R,m,w,S)=>{const T=hO.find(N=>N.theme===R&&N.a===m&&N.b===w&&o(N.got,S));return T&&l.add(T),T},u=new Set,f=new Set,h=new Set,_=(R,m,w)=>`${R} on ${m} in ${w}`,y=[],v=R=>{n.failures++,y.push(`FAIL ${R}`)},b=new Set,p=(R,m,w,S)=>{const T=fO.find(N=>N.theme===R&&N.fg===m&&N.bg===w&&o(N.got,S));return T&&b.add(T),T};return Object.assign(n,{readings:r,pinMatches:o,ledgerHolds:i,log:y,fail:v,exceptionSeen:b,perceptibleSeen:a,pairPinSeen:l,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:h,controlEdgeKey:_,pinClaims:new Set,findException:p,findPerceptibleException:c,findPairPin:d,assertPair:(R,m,w,S,T,N)=>{const Y=m[w],X=m[S];if(!H(Y)||!H(X))return;n.assertions++;const E=oe(Y,X);if(t&&r.push({foreground:w,background:S,value:E,floor:T}),E>=T)return;const V=D(E);p(R,w,S,V)||v(`${R}: ${N} — ${w} ${Y} on ${S} ${X} = ${V}:1, need ${T}:1`)},assertIdentityPair:(R,m,w,S,T,N)=>{const Y=m[w],X=m[S];if(!H(Y)||!H(X))return;n.assertions++;const E=D(fe(Y,X));if(E>=T)return;const V=d(R,w,S,E);if(V){V.floor!==T&&v(`${R}: \`${w}\`/\`${S}\` is pinned at floor ${V.floor} but this assertion asks for ${T} — a pin records the bound it was granted under, so the pin and the floor have to be raised together`);return}v(`${R}: ${N} — \`${w}\` ${Y} and \`${S}\` ${X} are ΔE00 ${E} apart (need ${T}) — two roles a reader has to tell apart at this site cannot be one colour at two weights; move the palette value, or pin the palette in \`PAIR_PINS\` with the constraint that refuses it`)},floorUnreachablePin:(R,m)=>CO.find(S=>S.id===R&&S.role===m)??null,shortfallPin:(R,m,w)=>OO.find(T=>T.id===R&&T.role===m&&T.bound===w)??null}),n},MO=(e,t)=>{const{fail:n,assertPair:r,assertIdentityPair:o,findException:i,findPerceptibleException:a,floorUnreachablePin:c,shortfallPin:l,pinClaims:d,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:h,controlEdgeKey:_,pinMatches:y,ledgerHolds:v}=e;for(const{id:b,palette:p}of[t]){for(const m of _O)e.assertions++,m in p||n(`${b}: missing required role \`${m}\``);for(const[m,w]of b_)if(!zf.has(m))for(const S of hn)r(b,p,m,S,w,"body ink");for(let m=0;m<Ze.length;m++)for(let w=m+1;w<Ze.length;w++){const S=p[Ze[m]],T=p[Ze[w]];!H(S)||!H(T)||(e.assertions++,oe(S,T)<1.03&&n(`${b}: grounds \`${Ze[m]}\` ${S} and \`${Ze[w]}\` ${T} are indistinguishable (${D(oe(S,T))}:1) — elevation is a lightness step here, so they must differ`))}const A=[{role:"rowHover",castFloor:m=>Math.max(_s,y_*m),castCeiling:m=>Math.max(m,_s),stepFloor:AO,stepCeiling:null},{role:"rowSelected",castFloor:m=>Math.max(bs,m),castCeiling:m=>Math.min(Math.max(m+Lc,bs),Fc),stepFloor:RO,stepCeiling:v_}];for(const m of A){const w=m.role,S=p[w];if(!H(S))continue;const[T,N,Y]=se(S),[X,E,V]=se(p.surface),[,G,me]=se(p.accent),z=Math.hypot(G,me),ye=Math.hypot(E,V),be=Math.hypot(N,Y),Ce=m.castFloor(ye),$e=m.castCeiling(ye),_t=ye<mn;e.assertions++;const jt=ye>=mn?{name:"the panel's",hue:Math.atan2(V,E)}:z>=w_?{name:"`accent`'s",hue:Math.atan2(me,G)}:{name:"the panel's",hue:Math.atan2(V,E)},le=Math.atan2(Y,N),ke=Math.abs(((le-jt.hue)*180/Math.PI+540)%360-180);be>=mn&&ke>op&&n(`${b}: \`${w}\` ${S} sits ${D(ke)} degrees off ${jt.name} hue (the limit is ${op}) — a row state has to be the colour of the backdrop it is a state of, and the values this round replaced took the \`accent\`'s hue instead, which is more than 45 degrees off the panel on 25 of the 59 palettes and is the off-colour the operator reported. Take the hue from ${jt.name} and re-author the value at it`),e.assertions++,Ce>$e+1e-9?(d.add(`${b}:${w}:floor`),e.assertions++,c(b,w)||n(`${b}: \`${w}\` ${S} carries C* ${D(be)}, and its cast floor ${D(Ce)} is ABOVE its ceiling ${D($e)} — the panel's own cast is louder than this role is allowed to be, so the value has to sit at the ceiling and \`${b}\`'s \`${w}\` has to be in ROW_STATE_FLOOR_UNREACHABLE naming the constraint that refuses the floor (the flat cap, the rise, or the role's absolute term)`),e.assertions++,be<$e-ip&&n(`${b}: \`${w}\` ${S} carries C* ${D(be)} where its cast floor ${D(Ce)} is above its ceiling ${D($e)} — the floor cannot be held, but the CEILING is reachable and is what the ledger row promises this value sits at`)):be<Ce-xO&&n(`${b}: \`${w}\` ${S} carries C* ${D(be)}, under the cast floor ${D(Ce)} — a row state has to carry the cast of the panel it sits on, and a fill quieter than its own backdrop reads as a grey wash of that backdrop. This is the defect that was reachable because the two \`ROW_*_CHROMA_FLOOR\` constants were declared and asserted NOWHERE, and the measurement that found it was a hover at C* 4.79 on a panel of 13.44. Author the value at the panel's own hue, at the cast the rule names and the step the inks allow`),e.assertions++,be>$e+ip&&n(`${b}: \`${w}\` ${S} carries C* ${D(be)}, past the ${D($e)} this file allows — ${w==="rowHover"?"the hover may be lighter than its ground, it may not be a MORE coloured plane than it":`the selection may carry the panel's cast and the rule's rise of ${Lc} above it, and no more`}, and the flat cap is ${Fc}. Search the chroma back toward the panel and let the step and the pair's cast rank carry what the fill no longer can`),e.assertions++;const et=T-X,Ne=p.mode==="dark"?et:-et;if(Ne<m.stepFloor-1e-9&&n(`${b}: \`${w}\` ${S} sits ${D(Math.abs(et))} \`L*\` ${p.mode==="dark"?"above":"below"} \`surface\` ${p.surface}, so the step is ${p.mode==="dark"?"LIGHTER":"DARKER"}-by-${D(Ne)} where the floor is ${m.stepFloor} \`L*\` in the mode's raised direction — ΔE00 is a budget a chroma-only step can spend while moving the wrong way in lightness, and the three palettes that did exactly that were the same report answered twice`),m.stepCeiling!==null&&(e.assertions++,Ne>m.stepCeiling+TO+1e-9&&n(`${b}: \`${w}\` ${S} sits ${D(Ne)} \`L*\` from \`surface\`, past the ${m.stepCeiling} \`L*\` ceiling — every L* the row rises is ink headroom spent on the caps drawn inside it, so the step is taken as far as the inks allow and no further`)),w==="rowSelected"&&H(p.rowHover)){const[xe,pt,$t]=se(p.rowHover),bt=p.mode==="dark"?xe-X:X-xe,Xr=Math.hypot(pt,$t);if(e.assertions++,Ne<bt+Da-1e-9){const Fn=l(b,"rowSelected","rank");d.add(`${b}:rowSelected:rank`),e.assertions++,Fn?v(Fn.measured,Ne-bt,.05)||n(`${b}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Fn.measured} and the pair now ranks ${D(Ne-bt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${b}: \`rowSelected\` ${S} is ${D(Ne)} \`L*\` from \`surface\` where \`rowHover\` ${p.rowHover} is ${D(bt)} — the selection has to be at least ${Da} \`L*\` further out than the hover, or a reader scanning sees one mark at two strengths rather than two states. A palette that cannot reach it has its whole legal step consumed by the ink floors, and that is a ledger row rather than a relaxed floor`)}else!e.composed&&l(b,"rowSelected","rank")&&n(`${b}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — the pair ranks ${D(Ne-bt)} \`L*\`, clear of the ${Da} the row claims it misses. Remove the row`);e.assertions++,be<Xr+gs-1e-9&&n(`${b}: \`rowSelected\` ${S} carries C* ${D(be)} where \`rowHover\` ${p.rowHover} carries ${D(Xr)} — the selection has to carry at least ${gs} chroma more than the hover. This is the rank that costs nothing: a fill may be ranked on cast without spending a single L* of the ink budget, and the shipped fleet's chroma rank was INVERTED on 14 palettes because the hover desaturated while the selection did not`),e.assertions++,bt<rp*Ne-1e-9&&n(`${b}: \`rowHover\` ${p.rowHover} takes ${D(bt)} \`L*\` of the ${D(Ne)} the selection takes (${Math.round(bt/Ne*100)}%), under the ${Math.round(rp*100)}% this file requires — the operator asked for MORE of the brightening than the shipped 30%, and an absolute hover floor cannot state that on a fleet whose budgets differ by 2.5x`)}e.assertions++;const Et=fe(S,p.surface);if(Et<ct-1e-9){const xe=l(b,w,"band");d.add(`${b}:${w}:band`),e.assertions++,xe?v(xe.measured,Et,.05)||n(`${b}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${xe.measured} and the palette now measures ${D(Et)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${b}: \`${w}\` ${S} is ΔE00 ${D(Et)} from \`surface\` ${p.surface} (the field floor is ${ct}) — below this the mark is not findable while scanning, which is the operator's report restated. The band this role used to be held to was 4.0 and is WITHDRAWN because a backdrop-faithful fill cannot reach it on lightness; this floor is what is left, and a palette that misses even it needs a ledger row with the floor that refuses it`)}else!e.composed&&l(b,w,"band")&&n(`${b}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${D(Et)} from \`surface\`, clear of the ${ct} the row claims it misses. Remove the row`);e.assertions++;const ge=fe(S,p.accentWash);if(!_t&&ge<Na){const xe=l(b,w,"wash");d.add(`${b}:${w}:wash`),e.assertions++,xe?v(xe.measured,ge,.05)||n(`${b}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${xe.measured} and the palette now measures ${D(ge)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${b}: \`${w}\` ${S} is ΔE00 ${D(ge)} from \`accentWash\` ${p.accentWash} (need ${Na}) — a hovered row beside a hovered button would merge into one mark, and they are a row state and a control state, so they have to be two. A backdrop-relative fill and an accent-derived wash are the same kind of rung, so this can bite on a palette with a strong cast in both; that is a ledger row with the reading, not a widened floor`)}else!e.composed&&!_t&&l(b,w,"wash")&&n(`${b}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${D(ge)} from \`accentWash\`, clear of the ${Na} the row claims it misses. Remove the row`)}if(H(p.rowHover)&&H(p.rowSelected)){e.assertions++;const m=fe(p.rowSelected,p.rowHover),w=IO;m<w-1e-9&&n(`${b}: \`rowHover\` ${p.rowHover} and \`rowSelected\` ${p.rowSelected} are ΔE00 ${D(m)} apart (need ${w}) — the reader sees two marks and cannot rank them. This was the second half of the operator's report: on \`neon\` the shipped pair sat 1.80 ΔE apart while each was ~6.2 ΔE off the panel. The ranking is the fill's now, so a palette that misses this is missing because the two fills are the SAME MARK — give the selection more step or more cast than the hover`)}if(H(p.sunken)&&H(p.rowHover)&&H(p.rowSelected)&&H(p.borderControl))for(const m of["rowHover","rowSelected"]){e.assertions++;const w=fe(p.sunken,p[m]),S=oe(p.borderControl,p[m]);w<ct&&S<je.nonText&&n(`${b}: the agents sidebar's avatar plate has no perceivable edge against \`${m}\` — its \`sunken\` fill ${p.sunken} is ΔE00 ${D(w)} from it (need ${ct}) and the plate's \`borderControl\` edge ${p.borderControl} is ${D(S)}:1 against that same fill (need ${je.nonText}:1), so the row's own ${m==="rowHover"?"hover":"selection"} turns the avatar into a disc of the row's fill. Give the plate an edge the row's state cannot overrun, or a fill that state cannot land on`)}if(typeof p.scrim=="string"&&H(p.ink)){const m=p.scrim.match(/rgb\((\d+)\s+(\d+)\s+(\d+)\s*\/\s*([\d.]+)\)/);if(m){const[w,S,T,N]=m.slice(1).map(Number);for(const Y of hn){if(!H(p[Y]))continue;const X=[1,3,5].map(G=>Number.parseInt(p[Y].slice(G,G+2),16)),E=`#${[w,S,T].map((G,me)=>Math.round(G*N+X[me]*(1-N)).toString(16).padStart(2,"0")).join("")}`;e.assertions++;const V=oe(p.ink,E);V<je.nonText&&n(`${b}: the lightbox's current-tile ring has no perceivable edge over \`${Y}\` — \`ink\` is ${D(V)}:1 against the scrim composited over it (need ${je.nonText}:1). The scrim dims whatever is open under it, so the ring's role has to clear every ground the overlay can open over`)}}}for(const m of lO)for(const w of Ze)r(b,p,m,w,je.nonText,"structural edge");const k=[...Ze,"accentWash","messageSurface"];for(const m of dO)for(const w of k)r(b,p,m,w,je.text,"colour as text");r(b,p,"warning","elevated",je.text,"the picker's partial-listing note"),r(b,p,"danger","elevated",je.text,"danger as text on a dialog's ground"),r(b,p,"warning","rowSelected",je.text,"integration status text on a deep-linked row"),r(b,p,"accent","warningWash",je.text,"model-access band links on the warning wash"),r(b,p,"warning","rowHover",je.text,"the partial delivery word on the hovered row's ground"),r(b,p,"dangerBorder","elevated",je.nonText,"the danger control's only edge on a dialog's ground");for(const m of iO)for(const w of m.on){const S=p[w],T=m.fill?p[m.fill]:S,N=p[m.ink],Y=m.border?p[m.border]:null;if(!H(S)||!H(T)||!H(N))continue;e.assertions++;const X=oe(N,T);if(X<je.text&&!zf.has(m.ink)&&!i(b,m.ink,m.fill??w,X)&&n(`${b}: ${m.name} on ${w} — ink ${m.ink} ${N} on fill ${T} = ${X}:1, need ${je.text}:1`),m.edge!==!1){e.assertions++;const E=oe(T,S),V=H(Y)?oe(Y,S):0,G=Math.max(E,V);if(G<je.nonText){const me=gO.find(z=>z.control===m.name&&z.ground===w&&z.theme===b&&y(z.got,D(G)));me?h.add(_(me.control,me.ground,me.theme)):n(`${b}: ${m.name} on ${w} has no perceivable edge — fill ${E}:1, border ${V}:1, need one at ${je.nonText}:1`)}}}for(const m of uO)r(b,p,m.fg,m.on,m.floor,m.name);for(const m of aO)for(const w of m.on)r(b,p,m.fg,w,m.floor??je.nonText,m.name);for(const m of sO){const w=p[m.b];if(H(w))for(const S of m.a){const T=p[S];if(!H(T))continue;e.assertions++;const N=oe(T,w);N<m.floor&&!i(b,S,m.b,N)&&n(`${b}: ${m.name} — ${S} ${T} against ${m.b} ${w} = ${N}:1, need ${m.floor}:1`)}}for(const m of cO){const w=p[m.role];if(!H(w))continue;for(const E of m.on){if(!H(p[E]))continue;e.assertions++;const V=fe(w,p[E]);V<m.minDeltaE&&!a(b,m.role,E,D(V))&&n(`${b}: ${m.name} — ${m.role} ${w} on ${E} ${p[E]} is ΔE00 ${D(V)}, need ${m.minDeltaE} to be seen at all`)}if(!m.pairedWith||!m.against)continue;const S=p[m.pairedWith],T=p[m.against];if(!H(S)||!H(T))continue;e.assertions++;const N=oe(w,T),Y=oe(S,T),X=Math.max(N/Y,Y/N);X>m.maxWeightChange&&n(`${b}: ${m.name} — ${m.role} is ${D(X)}x the weight of ${m.pairedWith} against ${m.against}; one component must not change weight by more than ${m.maxWeightChange}x between states`)}for(let m=0;m<Pi.length;m++)for(let w=m+1;w<Pi.length;w++){const[S,T]=[Pi[m],Pi[w]];if(!H(p[S])||!H(p[T]))continue;e.assertions++;const N=fe(p[S],p[T]);N<dn&&n(`${b}: \`${S}\` ${p[S]} and \`${T}\` ${p[T]} are too close to tell apart (ΔE00 ${D(N)}, need ${dn}) — a semantic a reader cannot distinguish from another semantic is not a semantic`)}if(H(p.accentAlt)){if(H(p.accent)){e.assertions++;const T=fe(p.accentAlt,p.accent);T<dn&&n(`${b}: the second accent \`accentAlt\` ${p.accentAlt} is ΔE00 ${D(T)} from \`accent\` ${p.accent} (need ${dn}) — two accents have to be two accents at the sizes this one is drawn at, and a value that buys its separation by darkening is the same hue at another weight rather than a second hue`)}for(const T of["success","warning","danger"]){if(!H(p[T]))continue;e.assertions++;const N=fe(p.accentAlt,p[T]);N<dn&&n(`${b}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${D(N)} from \`${T}\` ${p[T]} (need ${dn}) — a decorative mark a reader can mistake for "${T==="danger"?"something broke":T}" costs them something real, so the palette moves the hue rather than the assertion`)}if(H(p.info)){e.assertions++;const T=fe(p.accentAlt,p.info);T<Or&&n(`${b}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${D(T)} from \`info\` ${p.info} (need ${Or}) — \`info\` is the family the port mapped the TUI's \`signal\` onto, so the floor here is the reduced one and not ${dn}; below it the two take the same name`)}const[,m,w]=se(p.accentAlt),S=Math.hypot(m,w);e.assertions++,S<ti&&n(`${b}: \`accentAlt\` ${p.accentAlt} is C* ${D(S)} (need ${ti}) — a second accent drained toward the ink passes every separation above and stops being a hue, which is the one way this role fails while the gate stays green`);for(const T of["canvas","surface","sunken"])r(b,p,"accentAlt",T,je.text,"second accent as text");r(b,p,"accentAlt","elevated",je.text,"second accent as text on a row's state ground")}if(o(b,p,"accentAlt","info",Ir,"the tool row's two category inks"),o(b,p,"info","accent",Ar,"the settled read ink against the liveness ink"),H(p.accentAltWash)&&H(p.accentWash)){e.assertions++;const m=fe(p.accentAltWash,p.accentWash);m<ct&&n(`${b}: \`accentAltWash\` ${p.accentAltWash} is ΔE00 ${D(m)} from \`accentWash\` ${p.accentWash} (need ${ct}) — the two washes sit adjacent in mermaid's categorical ramp, so a step the reader cannot see is not a step`)}for(const m of bO){if(!H(p[m])||!H(p.inkDim))continue;e.assertions++;const w=fe(p[m],p.inkDim);w<Or&&n(`${b}: syntax \`${m}\` ${p[m]} sits at ΔE00 ${D(w)} from comment \`${p.inkDim}\` (need ${Or}) — a token the eye cannot separate from the comment beside it is not highlighted`)}if(H(p[lo])&&H(p.ink)){const m=yO.find(w=>w.theme===b);for(const w of vO){if(!H(p[w]))continue;e.assertions++;const S=oe(p[lo],p[w]);S<4.5&&n(`${b}: the command token \`tokenCommand\` ${p[lo]} reads ${D(S)}:1 on \`${w}\` (need 4.5) - the token is text a user typed (the composer's leading /word, or the sent \`$skill\` mention), not decoration`)}for(const w of["ink","accent","success"]){if(!H(p[w]))continue;e.assertions++;const S=fe(p[lo],p[w]);if(!!m?.against.includes(w)){y(m.got,S)||n(`${b}: COMMAND_TOKEN_PINNED records ${m.got} for \`command\`/\`${w}\` but it now measures ${D(S)} - re-measure and update the pin (${m.why})`);continue}S<Mi&&n(`${b}: the command token \`tokenCommand\` ${p[lo]} sits at ΔE00 ${D(S)} from \`${w}\` ${p[w]} (need ${Mi}) - the composer paints this run in the same box as that ink, so a reader cannot tell which is which`)}if(H(p.success)){e.assertions++;const w=fe(p.success,p.ink);w<Mi&&n(`${b}: the roster NAME's ink \`success\` ${p.success} sits at ΔE00 ${D(w)} from prose \`ink\` ${p.ink} (need ${Mi}) - a resolved name that reads as prose is not a run`)}}if(H(p.inkMuted)&&H(p.inkDim)){e.assertions++,u.add(b);const m=fe(p.inkMuted,p.inkDim),w=mO.find(S=>S.theme===b);w&&f.add(w),m<Ao?w?y(w.got,m)||n(`${b}: INK_STEP_PINNED records ${w.got} but \`inkMuted\`/\`inkDim\` now measure ${D(m)} - re-measure and update the pin, so the recorded number stays the one in the palette`):n(`${b}: the control ink \`inkMuted\` ${p.inkMuted} sits at ΔE00 ${D(m)} from the readout ink \`inkDim\` ${p.inkDim} (need ${Ao}) - a chip that opens cannot be told from a reading that does not`):w&&!e.composed&&n(`${b}: the ink step is pinned at ${w.got} but now measures ${D(m)}, clearing the ${Ao} floor - delete the pin rather than leaving dead weight in the contract`)}for(const[m,w,S=ct]of[["canvas","surface"],["surface","elevated"],["elevated","sunken"],["accent","accentHover"],["accentHover","accentActive"],["accent","accentActive"],["surface","sunken"],["canvas","elevated",SO]]){if(!H(p[m])||!H(p[w]))continue;e.assertions++;const T=fe(p[m],p[w]);T<S&&n(`${b}: adjacent \`${m}\` and \`${w}\` are ΔE00 ${D(T)} apart (need ${S}) — a step the eye cannot see is not a step`)}{const m=se(p.canvas)[0],w=se(p.surface)[0],S=se(p.elevated)[0],T=se(p.sunken)[0],N=p.mode==="dark";e.composed||(e.assertions++,N&&(m<Xt.dark.canvasMin||m>Xt.dark.canvasMax)&&n(`${b}: dark \`canvas\` ${p.canvas} sits at L* ${D(m)} — the band is [${Xt.dark.canvasMin}, ${Xt.dark.canvasMax}] in L*. Below the floor the three ink weights and the three ladder steps stop fitting above each other without one of them breaking its own floor; above the ceiling the canvas is no longer the darker tone the operator asked for (2026-11-03), and a palette above it was not re-lit by the band's proportional map`),e.assertions++,N&&S>Xt.dark.elevatedMax&&n(`${b}: dark \`elevated\` ${p.elevated} sits at L* ${D(S)} — the ceiling is L* ${Xt.dark.elevatedMax}, because at L* 34 an \`inkDim\` at its floor needs L* 85 and the ink/hover distinction disappears into the top of the ramp`),e.assertions++,!N&&m>Xt.light.canvasMax&&n(`${b}: light \`canvas\` ${p.canvas} sits at L* ${D(m)} — the ceiling is L* ${Xt.light.canvasMax}. \`elevated\` at L* 100 is the end of sRGB's ramp and the minimum canvas-to-elevated spread is 2.5 + 2.5 L*, so a canvas above 95 has no room for both steps; 94 leaves 1 L* for 8-bit rounding`),e.assertions++,!N&&T<Xt.light.sunkenMin&&n(`${b}: light \`sunken\` ${p.sunken} sits at L* ${D(T)} — the floor is L* ${Xt.light.sunkenMin}. A light theme's recessed ground is the darkest plane in it, so it is the cap for every ink there and the keycap's ground on every selected row`));for(const[Y,X,E,[V,G],me]of[["canvas -> surface","canvas","surface",An.canvasSurface,w-m],["surface -> elevated","surface","elevated",An.surfaceElevated,S-w],["canvas -> sunken","canvas","sunken",An.canvasSunken,m-T]])if(e.assertions++,(me<V-1e-9||me>G+1e-9)&&n(`${b}: the ${Y} step is ${D(me)} L*, outside [${V}, ${G}] — the bounds are both ends of the same budget: below the floor the two grounds merge, and above the ceiling the step eats the room the ink ladder needs`),r(b,p,X,E,oO,`${Y} step`),X==="canvas"&&E==="sunken"||X==="surface"&&E==="elevated"){e.assertions++;const z=fe(p[X],p[E]),ye=X==="canvas"?rO:EO;z<ye&&n(X==="canvas"?`${b}: \`canvas\` and \`sunken\` are ΔE00 ${D(z)} apart (need ${ye}) — a well nobody can see is not a well, and both blocks that paint one are read inside a trace that sits on the canvas`:`${b}: \`surface\` ${p.surface} and \`elevated\` ${p.elevated} are ΔE00 ${D(z)} apart (need ${ye}) — the hover rung is the ground a hover, a menu and a dialog are all painted on, so it cannot sit closer to the panel than this and still report the pointer; it is also the ground the current row has to outrank, so a rung at this floor is what the row/hover ordering is measured against. Place it at the lowest \`L*\` that clears this and no lower - the row's own rank against the hover is asserted in the row-state loop below, so a rung placed here is a rung the two row fills have to fit above`)}}r(b,p,"ink","canvas",rd,"the transcript's body ink");for(const m of hn){if(!H(p.inkDisabled)||!H(p.inkDim)||!H(p[m]))continue;e.assertions++;const w=oe(p.inkDisabled,p[m]),S=oe(p.inkDim,p[m]);w>Kf*S+1e-9&&n(`${b}: \`inkDisabled\` on ${m} measures ${D(w)}:1 against \`inkDim\`'s ${D(S)}:1 — a factor of ${D(w/S)}, over the ${Kf} ceiling. A disabled control that meets the ink floors does not read as disabled`)}for(const[m,w]of[["inkDim","inkMuted"],["inkMuted","ink"]]){if(!H(p[m])||!H(p[w]))continue;e.assertions++;const S=fe(p[m],p[w]);S<ms&&n(`${b}: \`${w}\` and \`${m}\` are ΔE00 ${D(S)} apart (need ${ms}) — the three weights are a ladder, and a rung the eye cannot see is not a rung`)}{const m=fe(p.sunken,p.elevated);e.assertions++,m<Vf&&n(`${b}: the palette/picker active row (\`sunken\` ${p.sunken}) is ΔE00 ${D(m)} from the dialog ground it is painted on (\`elevated\` ${p.elevated}), need ${Vf} — a selection is a state the reader has to find while scanning, not a surface they read, and below this band it stops being findable`),e.assertions++;const w=Math.abs(se(p.sunken)[0]-se(p.elevated)[0]);w<Zf&&n(`${b}: the palette/picker active row sits ${D(w)} L* from \`elevated\`, under the ${Zf} L* floor — ΔE00 is a budget a chroma-only step can spend while the mark vanishes in a greyscale render, so the lightness half is asserted too`)}{if(p.messageSurface===void 0)continue;if(!H(p.messageSurface)){n(`${b}: the user message block's fill \`messageSurface\` ${JSON.stringify(p.messageSurface)} is present but not a flat hex colour, so the role's floor would be silently unmeasured - a malformed value must not switch a floor off`);continue}if(!H(p.canvas))continue;const m=fe(p.messageSurface,p.canvas);e.assertions++,m<Yf&&n(`${b}: the user message block's fill \`messageSurface\` ${p.messageSurface} is ΔE00 ${D(m)} from \`canvas\` ${p.canvas} (need ${Yf}) — the fill IS the block's boundary, and below this band it stops being findable`),e.assertions++;const w=Math.abs(se(p.messageSurface)[0]-se(p.canvas)[0]);w<Nc&&n(`${b}: the user message block's fill sits ${D(w)} L* from \`canvas\`, under the ${Nc} L* floor — ΔE00 is a budget a chroma-only step can spend while the mark vanishes in a greyscale render, so the lightness half is asserted too`)}{if(p.mediaSurface===void 0)continue;if(!H(p.mediaSurface)){n(`${b}: the media tile's fill \`mediaSurface\` ${JSON.stringify(p.mediaSurface)} is present but not a flat hex colour, so the role's floor would be silently unmeasured - a malformed value must not switch a floor off`);continue}if(!H(p.canvas))continue;const m=fe(p.mediaSurface,p.canvas);e.assertions++,m<Xf&&n(`${b}: the media tile's fill \`mediaSurface\` ${p.mediaSurface} is ΔE00 ${D(m)} from \`canvas\` ${p.canvas} (need ${Xf}) — the fill IS the borderless tile's extent, and below this band it stops being findable`),e.assertions++;const w=Math.abs(se(p.mediaSurface)[0]-se(p.canvas)[0]);w<Jf&&n(`${b}: the media tile's fill sits ${D(w)} L* from \`canvas\`, under the ${Jf} L* floor — ΔE00 is a budget a chroma-only step can spend while the fill vanishes in a greyscale render, so the lightness half is asserted too`)}for(const m of Ze){if(!H(p.accentWash)||!H(p[m]))continue;e.assertions++;const w=fe(p.accentWash,p[m]);w<Qf&&n(`${b}: the accent wash on ${m} is ΔE00 ${D(w)} (need ${Qf}) — a hover tint the reader cannot see is a hover state the pointer cannot report, and this pair reads 1.00-1.24:1, so no ratio assertion in this file can see it`)}for(const m of["canvas","surface","elevated","accentWash"]){if(!H(p.sunken)||!H(p[m]))continue;e.assertions++;const w=fe(p.sunken,p[m]);w<qf&&n(`${b}: the keycap's ground \`sunken\` ${p.sunken} is ΔE00 ${D(w)} from ${m} ${p[m]} (need ${qf}) — the cap annotates the row the reader has just selected, so its ground has to survive being painted on that row`)}if(H(p.chartBarHover)&&H(p.accent)&&H(p[ji])){e.assertions++;const m=fe(p.chartBarHover,p.accent);m<Uc&&n(`${b}: \`chartBarHover\` ${p.chartBarHover} is ΔE00 ${D(m)} from \`accent\` ${p.accent}, need ${Uc} — a mark the reader has to find among its SIBLINGS is compared with them, not with itself across two states`),e.assertions++;const w=oe(p.chartBarHover,p[ji]),S=oe(p.accent,p[ji]);w<S&&n(`${b}: \`chartBarHover\` is ${D(w)}:1 on ${ji} where \`accent\` is ${D(S)}:1 — the hovered mark must not recede toward the ground it is drawn on`)}for(const m of Ze){if(!H(p.hairline)||!H(p[m]))continue;e.assertions++;const w=fe(p.hairline,p[m]);w<ep&&n(`${b}: \`hairline\` on \`${m}\` is ΔE00 ${D(w)} (need ${ep}) — a 1px line has no area to integrate over, so a step that reads between two fields disappears in a rule`);const S=oe(p.hairline,p[m]);e.assertions++,S<ap&&n(`${b}: \`hairline\` on \`${m}\` is ${D(S)}:1 (need ${ap}) — its ΔE00 is carried in chroma, which a 1px line does not survive`),e.assertions++,S>sp&&n(`${b}: \`hairline\` on \`${m}\` is ${D(S)}:1 (max ${sp}) — past this it is drawing a border, and the system already has one of those`)}for(const[m,w]of kO){if(!H(p.hairline)||!H(p[m])||!H(p[w]))continue;const S=Pa(p.hairline,p[m],wO);e.assertions++;const T=fe(S,p[m]);T<ct&&n(`${b}: the panel seam over \`${m}\` is ΔE00 ${D(T)} from that ground (need ${ct}) — the seam is half the boundary, and half a boundary the reader cannot see is a panel edge that disappears`),e.assertions++;const N=fe(S,p[w]);N<ct&&n(`${b}: the panel seam over \`${m}\` is ΔE00 ${D(N)} from \`${w}\` (need ${ct}) — the seam has to read from the plane it faces as well as the one it sits on`)}const M=Pa(p.accent,p.surface,tp);for(const[m,w,S]of[["inkMuted",je.text,"washed row metadata ink"],["ink",je.text,"washed row body ink"]]){const T=p[m];if(!H(T))continue;e.assertions++;const N=D(oe(T,M));N>=w||n(`${b}: ${S} — ${m} ${T} on the arrival band ${M} (accent ${tp} over surface) = ${N}:1, need ${w}:1`)}for(const m of["canvas","surface","elevated","accentWash"]){const w=Pa(p.accent,p[m],np);for(const[S,T,N]of[["inkMuted",je.text,"loading pill label"]]){const Y=p[S];if(!H(Y))continue;e.assertions++;const X=D(oe(Y,w));X>=T||n(`${b}: ${N} — ${S} ${Y} on the loading pill ${w} (accent ${np} over ${m}) = ${X}:1, need ${T}:1`)}}const P=oe(M,p.surface),W=oe(p.rowHover,p.surface),R=oe(p.rowSelected,p.surface);e.assertions+=2,P<=W&&n(`${b}: the arrival band is ${D(P)}:1 over the pane and the row hover is ${D(W)}:1 — the mark the reader was TOLD about cannot be drawn more quietly than one their pointer rests on`),P<=R&&n(`${b}: the arrival band is ${D(P)}:1 over the pane and the selected row is ${D(R)}:1 — the arrival must outrank the row the reader is already on, or the landing reads as a selection`)}},jO=Object.freeze({soft:-100,gentle:-50,standard:0,strong:50,high:100}),$O=Object.freeze({dark:Object.freeze({high:5,soft:20}),light:Object.freeze({high:97,soft:89})}),DO=["canvas","surface","elevated","sunken","messageSurface","mediaSurface","rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash","hairline","hairlineStrong","inkDisabled"],NO=new Set(["rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash"]),Wi=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Ct=Wi.slice(0,4),uo=[...Ct,"accentWash","messageSurface"],La={ink:[Wi,7],inkMuted:[Wi,5.5],inkDim:[Wi,5],borderControl:[Ct,3],accent:[[...uo,"warningWash"],4.5],accentHover:[Ct,4.5],accentActive:[Ct,4.5],tokenCommand:[["surface","elevated","messageSurface"],4.5],accentAlt:[Ct,4.5],success:[uo,4.5],warning:[[...uo,"rowSelected","rowHover"],4.5],danger:[uo,4.5],info:[uo,4.5],successBorder:[Ct,3],warningBorder:[Ct,3],dangerBorder:[Ct,3],infoBorder:[Ct,3],chartBarHover:[["surface"],3]},Pt=.05,cp=.3,lp=4.1,LO=.06,FO=/^#[0-9A-Fa-f]{6}$/,it=e=>typeof e=="string"&&FO.test(e),Wt=e=>e.slice(0,7).toUpperCase(),dt=(e,t,n)=>{const r=Math.max(0,Math.min(100,e));for(let o=1;o>=0;o-=.02){const i=hs([r,t*o,n*o]);if(i)return i}return hs([r,0,0])},rr=(e,t,n)=>Math.min(...n.filter(r=>it(e[r])).map(r=>oe(t,e[r]))),Bc=(e,t,n,r,o=()=>!0)=>{const i=e[t];if(!it(i)||rr(e,i,n)>=r+Pt&&o(i))return i;const[a,c,l]=se(i),d=e.mode==="dark"?1:-1;for(let u=.25;u<=100;u+=.25){const f=dt(a+d*u,c,l);if(rr(e,f,n)>=r+Pt&&o(f))return f}return i},od=(e,t)=>{const n=t.filter(it).map(Wt),r=n.find(o=>oe(o,e)>=4.5);return r||[...n].sort((o,i)=>oe(i,e)-oe(o,e))[0]},$i=e=>1+.015*(e-50)**2/Math.sqrt(20+(e-50)**2),or=e=>{const[,t,n]=se(e);return Math.hypot(t,n)},dp=(e,t)=>{const[n,r,o]=se(e),i=Math.hypot(r,o);return i<1e-6?e:dt(n,r/i*t,o/i*t)},UO=e=>{if(!it(e.rowHover)||!it(e.rowSelected))return;WO(e);const t=or(e.surface),n=Math.max(_s,y_*t),r=Math.max(t,_s),o=Math.max(bs,t),i=Math.min(Math.max(t+Lc,bs),Fc),a=(f,h,_)=>Math.min(Math.max(f,h),_),c=or(e.rowHover),l=or(e.rowSelected);if(c>=n&&c<=r&&l>=o&&l<=i&&l>=c+gs)return;const d=a(c,n+.1,r-.1),u=a(Math.max(l,d+gs+.2),o+.1,i-.1);e.rowHover=dp(e.rowHover,d),e.rowSelected=dp(e.rowSelected,u)},BO=6,HO=e=>{const[,t,n]=se(e);return Math.atan2(n,t)},WO=e=>{const n=or(e.surface)>=mn?e.surface:or(e.accent)>=w_?e.accent:e.surface,r=HO(n);for(const o of["rowHover","rowSelected"]){const[i,a,c]=se(e[o]),l=Math.hypot(a,c);l<mn||Math.abs(((Math.atan2(c,a)-r)*180/Math.PI+540)%360-180)<=BO||(e[o]=dt(i,l*Math.cos(r),l*Math.sin(r)))}},GO=e=>{const t=e.mode==="dark"?1:-1,n=(r,o,i,a,c)=>{const l=e[r];if(!it(l))return;const d=_=>rr(e,_,o)>=i+Pt&&(!a||fe(_,e[a])>=c+Pt)&&(r!=="ink"||oe(_,e.canvas)>=rd+Pt);if(d(l))return;const[u,f,h]=se(l);for(let _=.25;_<=100;_+=.25){const y=dt(u+t*_,f,h);if(d(y)){e[r]=y;return}}};n("inkDim",hn,Gi("inkDim"),null,0),n("inkMuted",hn,Gi("inkMuted"),"inkDim",Ao),n("ink",hn,Gi("ink"),"inkMuted",ms)},Gi=e=>b_.find(([t])=>t===e)[1],zO=.15,k_=.12,KO=(e,t,n)=>{if(!it(e.ink)||!it(e.canvas))return;const r=Math.abs(n)/100,o=e.mode==="dark"?1:-1;if(n>0){const[l,d,u]=se(e.ink),f=t*(1+zO*r);if(oe(e.ink,e.canvas)>=f)return;for(let h=.25;h<=100;h+=.25){const _=l+o*h;if(_<0||_>100)break;const y=dt(_,d,u);if(e.ink=y,oe(y,e.canvas)>=f)return}return}const i=t*(1-k_*r),a=["ink","inkMuted","inkDim"].filter(l=>it(e[l])),c=l=>a.every(d=>rr(e,l[d],hn)>=Gi(d)+Pt)&&oe(l.ink,e.canvas)>=rd&&(!l.inkMuted||fe(l.ink,l.inkMuted)>=ms+Pt)&&(!l.inkMuted||!l.inkDim||fe(l.inkMuted,l.inkDim)>=Ao+Pt);for(const l of[a,a.slice(0,2),a.slice(0,1)]){const d=Object.fromEntries(l.map(u=>[u,se(e[u])]));for(let u=.25;u<=60;u+=.25){if(oe(e.ink,e.canvas)<=i)return;const f={...e};for(const h of l){const[_,y,v]=d[h];f[h]=dt(_-o*u,y,v)}if(!c(f))break;for(const h of l)e[h]=f[h]}}},Di=(e,t,n,r,o=()=>!0)=>{const i=e[t];if(!it(i)||!n.split(",").every(f=>it(e[f])))return;const a=f=>n.split(",").every(h=>fe(f,e[h])>=r+Pt)&&o(f);if(a(i))return;const[c,l,d]=se(i),u=e.mode==="dark"?1:-1;for(const f of[u,-u])for(let h=.25;h<=40;h+=.25){const _=dt(c+f*h,l,d);if(a(_)){e[t]=_;return}}},S_=(e,t,{spread:n=1,narrow:r=!1,ease:o=LO,travel:i=1}={})=>{if(t===0)return e;const a=t>0?"high":"soft",c=Math.abs(t)/100,l={...e},d=z=>se(Wt(e[z])),u=d("canvas")[0],f=$O[e.mode][a],h=DO.filter(z=>it(e[z])),_=a==="high"==(e.mode==="light")?1:-1;let y=Math.max(0,(f-u)*_)*_*c*i,v=u+y;const b=a==="soft"?1-.4*c:1,p=$i(v)/$i(u),A=(a==="soft"?p:Math.max(1,p))*n,k=Object.fromEntries(h.map(z=>[z,v+(d(z)[0]-u)*A])),M=e.mode==="dark"?1:-1,P=(z,[,ye],be)=>{const Ce=(d(z)[0]-u)*be,$e=(k[z]-v)*be,_t=Math.max(Ce,ye-.15);$e>_t&&(k[z]=v+be*_t)};P("surface",An.canvasSurface,M),P("sunken",An.canvasSunken,-M);{const z=(d("elevated")[0]-d("surface")[0])*M,ye=(k.elevated-k.surface)*M,be=Math.max(z,An.surfaceElevated[1]-.15);ye>be&&(k.elevated=k.surface+M*be)}const W=d("surface")[0],R=e.mode==="dark"?1:-1,m=(d("rowSelected")[0]-W)*R,w=(d("rowHover")[0]-W)*R,S=m>0?Math.min(A,v_/m):A,T=a==="soft"?S:Math.max(1,S);if(k.rowSelected=k.surface+R*m*T,k.rowHover=k.surface+R*w*T,e.mode==="light"&&a==="high"){const z=u+y,ye=Object.keys(k).filter(Ce=>d(Ce)[0]>u),be=Math.max(0,...ye.map(Ce=>d(Ce)[0]-u));if(be>0){const Ce=ge=>{const xe=Math.min(1,(100-cp-ge)/be),pt={canvas:dt(ge,...d("canvas").slice(1))};for(const $t of ye)pt[$t]=dt(ge+(d($t)[0]-u)*xe,...d($t).slice(1));return pt},$e=[["canvas","surface",ct],["surface","elevated",ct],["canvas","elevated",lp],["canvas","messageSurface",lp]].filter(([ge,xe])=>(ge==="canvas"||ye.includes(ge))&&ye.includes(xe)),_t=[["canvas","surface",An.canvasSurface[0]],["surface","elevated",An.surfaceElevated[0]],["canvas","messageSurface",Nc]].filter(([ge,xe])=>(ge==="canvas"||ye.includes(ge))&&ye.includes(xe)),jt=(ge,xe,pt)=>pt+.02,le=ge=>$e.every(([xe,pt,$t])=>fe(ge[xe],ge[pt])>=jt(xe,pt,$t))&&_t.every(([xe,pt,$t])=>se(ge[pt])[0]-se(ge[xe])[0]>=$t+.15);let ke=z;for(;ke>u&&!le(Ce(ke));)ke=Math.max(u,ke-.25);const et=ke<=u?1:Math.min(1,(100-cp-ke)/be),Ne=Math.max(1,$i(ke)/$i(u))*n,Et={rowHover:k.rowHover-k.surface,rowSelected:k.rowSelected-k.surface};for(const ge of Object.keys(k))k[ge]=ye.includes(ge)?ke+(d(ge)[0]-u)*et:ke+(k[ge]-z)*(Ne/A);for(const ge of["rowHover","rowSelected"])ge in k&&Number.isFinite(Et[ge])&&(k[ge]=k.surface+Et[ge]);v=ke,y=ke-u}}if(a==="soft"&&r){const z=le=>e.mode==="dark"?le>v:le<v,ye=le=>le>8?((le+16)/116)**3:Math.max(0,le)/903.3,be=(le,ke)=>{const[et,Ne]=[ye(le),ye(ke)];return(Math.max(et,Ne)+.05)/(Math.min(et,Ne)+.05)},Ce=hn.filter(le=>le in k&&z(k[le])),_t=Math.max(1,...hn.filter(le=>le in k&&(e.mode==="dark"?d(le)[0]>u:d(le)[0]<u)).map(le=>be(u,d(le)[0])))*(1-o*c),jt=le=>Math.max(1,...Ce.map(ke=>be(v,v+(k[ke]-v)*le)));if(Ce.length>0&&jt(1)>_t){let le=1;for(;le>.3&&jt(le)>_t;)le-=.01;for(const ke of Object.keys(k))z(k[ke])&&(k[ke]=v+(k[ke]-v)*le)}}const N=Math.min(...Object.values(k)),Y=Math.max(...Object.values(k)),X=N<.5?.5-N:Y>100?100-Y:0,E=or(Wt(e.surface)),V=E>=mn?Math.max(b,Math.min(1,(mn+.4)/E)):b;for(const z of h){const[,ye,be]=d(z),Ce=NO.has(z)?1:z==="surface"?V:b;l[z]=dt(k[z]+X,ye*Ce,be*Ce)}UO(l),y=v+X-u;for(const z of Object.keys(La))it(e[z])&&(l[z]=Wt(e[z]));GO(l),KO(l,oe(Wt(e.ink),Wt(e.canvas)),t);const G=se(l.accent)[0];l.accent=Bc(l,"accent",...La.accent);const me=se(l.accent)[0]-G;for(const z of["accentHover","accentActive"]){if(!it(l[z])||me===0)continue;const[ye,be,Ce]=se(l[z]);l[z]=dt(ye+me,be,Ce)}for(const[z,[ye,be]]of Object.entries(La))z.startsWith("ink")||z==="accent"||(l[z]=Bc(l,z,ye,be));return Di(l,"accentHover","accent",ct,z=>rr(l,z,Ct)>=4.5+Pt),Di(l,"accentActive","accent,accentHover",ct,z=>rr(l,z,Ct)>=4.5+Pt),Di(l,"accentAlt","accent",dn,z=>rr(l,z,Ct)>=4.5+Pt&&or(z)>=ti),Di(l,"chartBarHover","accent",Uc,z=>oe(z,l.surface)>=oe(l.accent,l.surface)),l.onAccent=od(l.accent,[e.onAccent,l.ink,l.canvas,"#FFFFFF","#000000"]),l},vs=(e,t="custom")=>{const n=PO({composed:!0});return MO(n,{id:t,palette:e}),n.log},zi=(e,t)=>{const n=od(e.accent,[t.onAccent,e.ink,e.canvas,"#FFFFFF","#000000"]);return n===e.onAccent?e:{...e,onAccent:n}},up=new Set(["mode","overlayShadow","scrim","onAccent"]),VO=["rowHover","rowSelected","accentWash","surface"],ZO=/\b[a-z][A-Za-z]+\b/g,YO=(e,t)=>{const n=new Map;for(const[o,i]of Object.entries(e))!up.has(o)&&it(i)&&n.set(i.toUpperCase(),o);const r=new Set;for(const o of t){if(o.includes("ROW_STATE_MEASURED_SHORTFALL"))for(const i of VO)r.add(i);for(const[i]of o.matchAll(ZO))i in e&&!up.has(i)&&it(e[i])&&r.add(i);for(const[i]of o.matchAll(XO)){const a=n.get(i.toUpperCase());a&&r.add(a)}}return[...r]},XO=/#[0-9A-Fa-f]{6}\b/g,JO=/(?:= |ΔE00 )(\d+(?:\.\d+)?)(?::1)?[\s\S]*?need (\d+(?:\.\d+)?)/,QO=e=>{let t=0;for(const n of e){const r=n.match(JO);if(!r){t+=1;continue}const o=Number(r[1]),i=Number(r[2]);t+=i>0?Math.min(1,Math.max(0,(i-o)/i)):1}return t},fp=e=>e.length*1e3+QO(e),qO=[.5,-.5,1,-1,2,-2,4,-4,7,-7,11,-11],eP=[.7,.85,1.15,1.35],tP=60,E_=(e,t,n=e,{pinned:r=[],maxEvaluations:o=Number.POSITIVE_INFINITY,lightnessOnly:i=!1}={})=>{const a=new Set(r),c=h=>a.has("onAccent")?h:zi(h,n);let l=0,d=c(e),u=vs(d,t),f=fp(u);for(let h=0;h<tP&&u.length>0;h++){let _=null;for(const y of YO(d,u)){if(a.has(y))continue;const[v,b,p]=se(d[y]),A=[...qO.map(k=>dt(v+k,b,p)),...i?[]:eP.map(k=>dt(v,b*k,p*k))];for(const k of A){if(k===d[y])continue;if(++l>o)return{palette:d,findings:u};const M=c({...d,[y]:k}),P=vs(M,t),W=fp(P);W<(_?_.score:f)-1e-9&&(_={next:M,findings:P,score:W})}}if(!_)break;d=_.next,u=_.findings,f=_.score}return{palette:d,findings:u}},nP=5,rP=[1,1.15],oP=[{spread:1,narrow:!0},{spread:1,narrow:!0,ease:0},...rP.map(e=>({spread:e})),{spread:1,travel:.5,soft:!0},{spread:1,travel:0,soft:!0}],pp=.015,iP=(e,t,n)=>{const r=oe(Wt(e.ink),Wt(e.canvas)),o=oe(t.ink,t.canvas),i=se(Wt(e.canvas))[0],a=se(t.canvas)[0],c=n>0==(e.mode==="light")?1:-1;return n>0?o>=r-pp&&(a-i)*c>=-.05:o<=r+pp},sP=(e,t,n,r)=>{const i=oe(Wt(t.ink),Wt(t.canvas))*(1-k_*(Math.abs(n)/100)),a=e.mode==="dark"?-1:1,c=["ink","inkMuted","inkDim"].filter(d=>it(e[d]));let l=e;for(const d of[c,c.slice(0,2),c.slice(0,1)]){const u=Object.fromEntries(d.map(f=>[f,se(l[f])]));for(let f=.25;f<=20;f+=.25){if(oe(l.ink,l.canvas)<=i)return l;const h={...l};for(const _ of d){const[y,v,b]=u[_];h[_]=dt(y+a*f,v,b)}if(vs(zi(h,t),r).length>0)break;l=zi(h,t)}}for(let d=0;d<6&&oe(l.ink,l.canvas)>i;d++){let u=null;for(const f of[0,1,2])for(const h of[1,-1]){const y=Number.parseInt(l.ink.slice(1+2*f,3+2*f),16)+h;if(y<0||y>255)continue;const v=`#${l.ink.slice(1,1+2*f)}${y.toString(16).padStart(2,"0").toUpperCase()}${l.ink.slice(3+2*f)}`,b=oe(v,l.canvas);if(b>=oe(l.ink,l.canvas))continue;const p=zi({...l,ink:v},t);vs(p,r).length>0||(!u||b>u.r)&&(u={r:b,next:p})}if(!u)break;l=u.next}return l},aP=(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(nP,Math.abs(o)))for(const i of oP){if((i.narrow||i.soft)&&o>0)continue;const a=S_(e,o,i),c=E_(a,n,e);if(o<0&&c.findings.length===0&&(c.palette=sP(c.palette,e,o,n)),c.findings.length===0&&iP(e,c.palette,o))return{palette:c.palette,effectiveContrast:o}}return{palette:e,effectiveContrast:0}},Vn=/^#[0-9A-Fa-f]{6}$/,cP=/^#[0-9A-Fa-f]{3}$/,gt=e=>{if(typeof e!="string")return null;let t=e.trim();return t.startsWith("#")||(t=`#${t}`),cP.test(t)&&(t=`#${[...t.slice(1)].map(n=>n+n).join("")}`),Vn.test(t)?t.toUpperCase():null},lP=["accentHover","accentActive","accentWash","chartBarHover"],Bt=e=>{const[t,n,r]=se(e);return[t,Math.hypot(n,r),Math.atan2(r,n)]},dP=e=>Bt(e)[1],ys=(e,t,n)=>dt(e,Math.max(0,t)*Math.cos(n),Math.max(0,t)*Math.sin(n)),uP=4,fP=(e,t,n)=>{const[r,o,i]=Bt(e),[a,c,l]=Bt(t),[d,u,f]=Bt(n);return o<uP?ys(d+(a-r),c,f):ys(d+(a-r),u*(c/o),f+(l-i))},pP=(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},hP=(e,t,{authored:n=e,id:r="custom",paletteAccent:o,preserveSecondary:i=!1}={})=>{const a=pP(t,n,o);if(!a)return{palette:e,applied:!1,adjusted:0,requested:a};const c={...e,accent:a};for(const h of lP)!Vn.test(n[h]??"")||!Vn.test(n.accent??"")||(c[h]=fP(n.accent,n[h],a));if(Vn.test(e.accentWash??"")&&Vn.test(n.accentWash??"")){const h=Bt(e.accentWash)[0],[,_,y]=Bt(c.accentWash);c.accentWash=ys(h,Math.max(_,Bt(n.accentWash)[1]),y)}if(dP(c.surface)<mn){const h=Bt(c.accent)[2];for(const _ of["rowHover","rowSelected"]){if(!Vn.test(c[_]??""))continue;const[y,v]=Bt(c[_]);v>=mn&&(c[_]=ys(y,v,h))}}!i&&t.kind==="theme-alt"?Bt(n.accent)[1]>=ti&&(c.accentAlt=gt(n.accent)):!i&&fe(c.accent,c.accentAlt)<dn&&Bt(n.accent)[1]>=ti&&(c.accentAlt=gt(n.accent));const l=se(c.accent)[0];c.accent=Bc(c,"accent",mP,4.5,h=>fe(h,c.ink)>=3);const d=se(c.accent)[0]-l;if(d!==0)for(const h of["accentHover","accentActive","chartBarHover"]){if(!Vn.test(c[h]??""))continue;const[_,y,v]=se(c[h]);c[h]=dt(_+d,y,v)}c.onAccent=od(c.accent,[n.onAccent,c.ink,c.canvas,"#FFFFFF","#000000"]);const u=E_(c,r,n);return i&&__.filter(h=>h.storage==="overrides").flatMap(h=>[h.role,...h.variants]).some(h=>u.palette[h]!==e[h])||u.findings.length>0||fe(u.palette.accent,u.palette.ink)<3?{palette:e,applied:!1,adjusted:0,requested:a}:{palette:u.palette,applied:!0,adjusted:fe(a,u.palette.accent),requested:a}},mP=["canvas","surface","elevated","sunken","accentWash","messageSurface","warningWash"],hp=["dark","light"],gP=12,bF=50,vF="custom-themes-storage",_P=60,I_=Object.freeze({dark:0,light:0}),Rn=Object.freeze({kind:"theme"}),A_=Object.freeze({dark:Rn,light:Rn}),Hc=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(-100,Math.min(100,Math.round(e))),R_=e=>!e||typeof e!="object"?I_:{dark:Hc(e.dark),light:Hc(e.light)},Wc=(e,t=()=>!0)=>{if(!e||typeof e!="object")return Rn;switch(e.kind){case"theme":return Rn;case"theme-alt":return{kind:"theme-alt"};case"palette":return typeof e.id=="string"&&t(e.id)?{kind:"palette",id:e.id}:Rn;case"custom":{const n=gt(e.hex);return n?{kind:"custom",hex:n}:Rn}default:return Rn}},x_=(e,t)=>!e||typeof e!="object"?A_:{dark:Wc(e.dark,t),light:Wc(e.light,t)},Kr=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===gP)break}return t},bP=(e,t)=>{const n=gt(t);return Kr(n?[n,...Array.isArray(e)?e:[]]:e)},vP=/^custom-[a-z0-9]{1,30}$/,id=e=>typeof e=="string"&&vP.test(e)?e:null,yF=(e,{isThemeName:t,isRole:n})=>{if(!e||typeof e!="object"||e.format!=="local-operator-theme"||e.version!==1)return null;const r=id(e.id);if(!r||!Yc(r)||typeof e.base!="string"||!t(e.base))return null;const o=typeof e.name=="string"&&e.name.trim()?e.name.trim().slice(0,_P):null;if(!o)return null;const i=a=>{const c={};if(!a||typeof a!="object")return c;for(const[l,d]of Object.entries(a)){if(!n(l))continue;const u=gt(d);u&&Xc(u)&&(c[l]=u)}return c};return{format:"local-operator-theme",version:1,id:r,name:o,base:e.base,seeds:i(e.seeds),overrides:i(e.overrides),updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:0}},en=Object.freeze(Object.entries(jO).sort(([,e],[,t])=>e-t).map(([e,t])=>Object.freeze({name:e,value:t}))),mp=5,yP=8,wP=e=>Math.max(-100,Math.min(100,e)),wF=(e,{snap:t=!0}={})=>{if(!Number.isFinite(e))return 0;const n=wP(Math.round(e/mp)*mp);if(!t)return n;for(const{value:r}of en)if(Math.abs(e-r)<=yP)return r;return n},kP=e=>en.find(t=>t.value===e)?.name??null,kF=e=>{let t=en[2];for(const n of en){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},SF=e=>{if(kP(e))return null;for(let t=1;t<en.length;t++)if(e<en[t].value)return[en[t-1].name,en[t].name];return null},EF=(e,t)=>{const r=(t>0?en:[...en].reverse()).find(o=>t>0?o.value>e:o.value<e);return r?r.value:e},SP=[[15,"pink"],[50,"red"],[70,"orange"],[85,"amber"],[105,"yellow"],[133,"lime"],[165,"green"],[200,"teal"],[245,"cyan"],[294,"blue"],[300,"indigo"],[335,"violet"],[360,"pink"]],sd=8,ad=e=>{const[t,n,r]=se(e),o=Math.atan2(r,n)*180/Math.PI;return{L:t,C:Math.hypot(n,r),h:o<0?o+360:o}},IF=e=>{const{C:t,h:n}=ad(e);if(t<sd)return"neutral";for(const[r,o]of SP)if(n<r)return o;return"pink"},AF=(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()),i=new Map;let a=null;for(const l of o){const{C:d,h:u}=ad(l.palette.accent);if(d<sd){(!a||d<a.C)&&(a={...l,C:d});continue}const f=Math.floor(u/36),h=Math.abs(u-(f*36+18)),_=i.get(f);(!_||h<_.off||h===_.off&&l.id<_.id)&&i.set(f,{...l,off:h})}const c=[...i.entries()].sort(([l],[d])=>l-d).map(([,l])=>({id:l.id,hex:l.palette.accent.toUpperCase()}));return a&&c.push({id:a.id,hex:a.palette.accent.toUpperCase()}),c},RF=(e,t)=>{const n=new Set,r=[];for(const i of e){if(i.palette.mode!==t)continue;const a=String(i.palette.accent).toUpperCase();n.has(a)||(n.add(a),r.push({id:i.id,hex:a}))}const o=i=>{const{C:a,h:c}=ad(i);return a<sd?1e3:c};return r.sort((i,a)=>o(i.hex)-o(a.hex))},EP=40,Ki=(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 i=[...o].map(a=>{const c=a.codePointAt(0)??0;return c<32||c===127?" ":a}).join("").replace(/\s+/g," ").trim().slice(0,EP);i&&(n[r]=i)}return n},xF=Object.freeze({strip:"lo-preview",chip:e=>`lo-preview-${e}`}),TF=(e,t,n=null)=>{const r=[];for(const{id:o,contrast:i}of t){if(!Yc(o))continue;const a=i===0?e:S_(e,i),c=n?{...a,...n}:a;Object.entries(c).every(([d,u])=>d==="mode"||Xc(u))&&r.push(Ip(o,c))}return r.join(`
65
- `)},CF=e=>{const[t,n,r]=se(e),o=Math.atan2(r,n)*180/Math.PI;return{l:t,c:Math.hypot(n,r),h:o<0?o+360:o}},OF=({l:e,c:t,h:n})=>{const r=Math.max(0,Math.min(100,e)),o=n*Math.PI/180;for(let i=Math.max(0,t);i>=0;i-=1){const a=hs([r,i*Math.cos(o),i*Math.sin(o)]);if(a)return a}return hs([r,0,0])??"#000000"},PF=e=>{const t=oe("#FFFFFF",e),n=oe("#000000",e);return t>=n?{ink:"#FFFFFF",ratio:t}:{ink:"#000000",ratio:n}},MF=Object.freeze(["accent","accentHover","accentActive","accentWash","onAccent","chartBarHover","accentAlt","accentAltWash"]),gp=64,Gc=["canvas","run","browser","console","code"],IP={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function T_(e){return typeof e=="string"&&Gc.includes(e)}function cd(e){return e.startsWith("draft:")}function li(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function ld(e){return e.length>gp?e.slice(e.length-gp):e}function C_(e,t,n){return ld([...e.filter(([r])=>r!==t),[t,n]])}function AP(e,t,n){return li(e,t)!==n?e:e.filter(([r])=>r!==t)}function RP(e,t){return li(e,t)===void 0?e:e.filter(([n])=>n!==t)}function xP(e,t,n){const r=li(e,t);return r===void 0?e:ld([...e.filter(([o])=>o!==t&&o!==n),[n,r]])}const _p=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function bp(e,t,n){if(n||typeof t!="string")return _p;const r=li(e,t);return r===void 0?_p:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function TP(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===""||cd(r)||T_(o)&&(t.delete(r),t.set(r,o))}return ld([...t.entries()])}function jF(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 vp(e){return IP[e]}let CP=0;const OP=()=>`console-command:${++CP}`,PP={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},di=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,Ws=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,MP=e=>{const t=di(e);return t===null||t==="ask"?null:PP[t]},En=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Wn=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:C_(e.rightSlotMemory,n,t)}},fo=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=AP(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},jP=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=RP(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},$P=Object.freeze({mounted:!1,session:!1}),O_=Object.freeze([]);function $F(e,t){const n=di(t);if(n===null||!Ws(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=po(Xl,t.rightSlotWidth);break;case"run":r=po(wp,t.rightSlotWidth);break;case"browser":r=po(UP,t.rightSlotWidth);break;case"console":r=po(BP,t.rightSlotWidth);break;case"code":r=po(wp,t.rightSlotWidth);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,Jl(e)):Math.min(r,Math.max(0,e-Zl))}function po(e,t){return Math.min(qg,Math.max(e,t||DP))}function DF(e){const t=di(e);return t!==null&&Ws(t,e)}function NF(e){const t=di(e);return t!==null&&Ws(t,e)?t:null}function LF(e){const t=di(e);return(t==="canvas"||t==="ask")&&Ws(t,e)}const DP=640,yp=Ls,NP=20,LP=4,FP=20,wp=320,UP=480,BP=480,HP=5e3,FF=(e,t)=>e.some(n=>n.surface===t),UF=(e,t=Date.now())=>e.some(n=>t-n.at<HP),WP=[],GP=5,zP=["chatMeasureWidth"],BF=oi()(Is((e,t)=>({finderFiles:u_,setFinderFiles:n=>e({finderFiles:ed({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:h_,agentAvatarSize:n_,themeName:B_,contrast:I_,accent:A_,customAccents:[],customAccentNames:{},customThemeId:null,setContrast:(n,r)=>e(o=>({contrast:{...o.contrast,[n]:Hc(r)}})),setAccent:(n,r)=>e(o=>({accent:{...o.accent,[n]:Wc(r,Vc)}})),addCustomAccent:(n,r)=>e(o=>{const i=bP(o.customAccents,n),a=gt(n),c=Ki(o.customAccentNames,i);return!r||!a?{customAccents:i,customAccentNames:c}:{customAccents:i,customAccentNames:c,accent:{...o.accent,[r]:{kind:"custom",hex:a}}}}),removeCustomAccent:n=>e(r=>{const o=gt(n),i={...r.accent};for(const c of hp){const l=i[c];l.kind==="custom"&&l.hex===o&&(i[c]=Rn)}const a={...r.customAccentNames};return o&&delete a[o],{customAccents:r.customAccents.filter(c=>c!==o),customAccentNames:a,accent:i}}),renameCustomAccent:(n,r)=>e(o=>{const i=gt(n);return!i||!o.customAccents.includes(i)?{}:{customAccentNames:Ki({...o.customAccentNames,[i]:r},o.customAccents)}}),replaceCustomAccent:(n,r)=>e(o=>{const i=gt(n),a=gt(r);if(!i||!a||i===a)return{};if(o.customAccents.indexOf(i)<0)return{};const l=o.customAccents.filter(h=>h!==a);l.splice(l.indexOf(i),1,a);const d=Kr(l),u={...o.customAccentNames};u[i]!==void 0&&u[a]===void 0&&(u[a]=u[i]),delete u[i];const f={...o.accent};for(const h of hp){const _=f[h];_.kind==="custom"&&_.hex===i&&(f[h]={kind:"custom",hex:a})}return{customAccents:d,customAccentNames:Ki(u,d),accent:f}}),rightSlotWidth:0,chatSidebarWidth:yp,chatSidebarRegions:UC,chatSidebarView:Er,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:O_,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:$P,consoleOpenIntent:null,consoleCommandIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:WP,isCreateAgentDialogOpen:!1,mentionRecents:null,profileRecents:{agent:[],team:[]},conversationRecents:[],shortcutBindings:{},openCreateAgentDialog:()=>{e({isCreateAgentDialogOpen:!0})},closeCreateAgentDialog:()=>{e({isCreateAgentDialogOpen:!1})},openCommandPalette:()=>{e({isCommandPaletteOpen:!0})},closeCommandPalette:()=>{e({isCommandPaletteOpen:!1,commandPaletteQuery:""})},toggleCommandPalette:(n="")=>{e(r=>({isCommandPaletteOpen:!r.isCommandPaletteOpen,commandPaletteQuery:r.isCommandPaletteOpen?r.commandPaletteQuery:n}))},setCommandPaletteQuery:n=>{e({commandPaletteQuery:n})},toggleSidebar:()=>{e(n=>({isSidebarCollapsed:!n.isSidebarCollapsed}))},setSidebarOverflowExpanded:n=>{e({sidebarOverflowExpanded:n})},setSidebarCollapsed:n=>{e({isSidebarCollapsed:n})},setShowAgentReasoning:n=>{e({showAgentReasoning:n})},setTranscriptDisplayMode:n=>{e({transcriptDisplayMode:n})},setAgentAvatarSize:n=>{e({agentAvatarSize:n})},setTheme:n=>{e({themeName:n,customThemeId:null})},setCanvasOpen:n=>{e(r=>n?{...En("isCanvasOpen"),...Wn(r,"canvas")}:{isCanvasOpen:!1,...fo(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...En("isRunPanelOpen"),...Wn(r,"run")}:{isRunPanelOpen:!1,...fo(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...En("isBrowserPaneOpen"),...Wn(r,"browser")}:{isBrowserPaneOpen:!1,...fo(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...En("isConsolePaneOpen"),...Wn(r,"console")}:{isConsolePaneOpen:!1,...fo(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...En("isCodeReviewPaneOpen"),...Wn(r,"code")}:{isCodeReviewPaneOpen:!1,...fo(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...En("isCodeReviewPaneOpen"),...Wn(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,o)=>{e(i=>{const a=typeof i.rightSlotKey=="string";if(n)return{...En("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:a?null:MP(i),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?o?.dismissSlot?{...c,...jP(i)}:{...c,...bp(i.rightSlotMemory,i.rightSlotKey,!1)}:i.rightSlotKey===null?o?.dismissSlot?{...c,rightSlotLegacySeed:null}:c:o?.dismissSlot?{...c,rightSlotLegacySeed:null}:{...c,...i.askDrawerEvictedPane===null?null:{[i.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})},requestConsoleCommand:n=>{const r={sessionId:n.sessionId,command:n.command,submit:n.submit===!0,nonce:OP(),filedAt:Date.now(),...n.askId===void 0?{}:{askId:n.askId},...n.questionId===void 0?{}:{questionId:n.questionId}};return e({consoleCommandIntent:r}),r},clearConsoleCommandIntent:n=>{e(r=>r.consoleCommandIntent?.nonce===n?{consoleCommandIntent:null}:{})},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 i=o.consoleLiveSurface;return i?.sessionId===n&&i.count===r?{}:{consoleLiveSurface:{sessionId:n,count:r}}})},markConsoleUnseen:(n,r)=>{e(o=>o.consoleUnseen.some(i=>i.surface===r)?{}:{consoleUnseen:[...o.consoleUnseen,{sessionId:n,surface:r,at:Date.now()}]})},clearConsoleUnseen:n=>{const r=Array.isArray(n)?n:[n];e(o=>{const i=o.consoleUnseen.filter(a=>!r.includes(a.surface));return i.length===o.consoleUnseen.length?{}:{consoleUnseen:i}})},setRightSlotWidth:n=>{e({rightSlotWidth:n})},restoreDefaultRightSlotWidth:()=>{e({rightSlotWidth:0})},bindRightSlotKey:(n,r)=>{e(o=>{let i=o.rightSlotMemory,a=o.rightSlotLegacySeed;const c=r?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(i=xP(i,c,n)),n===null||(cd(n)?a=null:a!==null&&li(i,n)===void 0&&(i=C_(i,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:i,rightSlotLegacySeed:a,...bp(i,n,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 i=nd(r);i!==null&&tO(i,n,t().shortcutBindings,"linux",o)===null&&e(a=>({shortcutBindings:{...a.shortcutBindings,[n]:i}}))},clearShortcutBinding:n=>{e(r=>({shortcutBindings:{...r.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(r=>({...En("isRunPanelOpen"),...Wn(r,"run"),runPanelReveal:{section:n,nonce:(r.runPanelReveal?.nonce??0)+1}}))},clearRunPanelReveal:n=>{e(r=>r.runPanelReveal?.nonce===n?{runPanelReveal:null}:{})},setChatSidebarWidth:n=>{e({chatSidebarWidth:Math.min(Vl,Math.max(Kl,n))})},setChatSidebarRegions:n=>{e({chatSidebarRegions:n})},setChatSidebarListHeight:n=>{e({chatSidebarListHeight:n})},restoreDefaultChatSidebarListHeight:()=>{e({chatSidebarListHeight:null})},setChatSidebarOrder:n=>{e({chatSidebarOrder:n})},setChatSidebarView:n=>{e({chatSidebarView:n})},dismissBuiltinOffer:n=>{e({dismissedBuiltinOfferSignature:n})},restoreDefaultChatSidebarWidth:()=>{e({chatSidebarWidth:yp})},rememberMention:(n,r)=>{e(o=>{const i=o.mentionRecents,a=i?.cwd===n?i.paths:[],c=[r,...a.filter(l=>l!==r)].slice(0,NP);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(o=>({profileRecents:{...o.profileRecents,[n]:KP(o.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const o=YP(r.conversationRecents),i=VP(o,n);return i.length===o.length&&i.every((a,c)=>a===o[c])?r:{conversationRecents:i}})}}),{name:"ui-preferences-storage",version:GP,migrate:qP,partialize:XP,merge:QP}));function KP(e,t){return[t,...e.filter(n=>n!==t)].slice(0,LP)}function VP(e,t){return[t,...e.filter(n=>n!==t)].slice(0,FP)}const ZP=[];function YP(e){return Array.isArray(e)?e:ZP}function XP(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:r,consoleCommandIntent:o,consoleLiveSurface:i,askOpenIntent:a,isAskDrawerOpen:c,askDrawerScope:l,askDrawerEvictedPane:d,rightSlotRoute:u,isCanvasOpen:f,isRunPanelOpen:h,isBrowserPaneOpen:_,isConsolePaneOpen:y,isCodeReviewPaneOpen:v,rightSlotKey:b,...p}=e;return{...p,rightSlotMemory:JP(e.rightSlotMemory)}}function JP(e){return(e??O_).filter(([t])=>!cd(t))}function QP(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:o,isBrowserPaneOpen:i,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:ed(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:TP(n.rightSlotMemory),rightSlotLegacySeed:T_(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:nO(n.shortcutBindings),contrast:R_(n.contrast),accent:x_(n.accent,Vc),customAccents:Kr(n.customAccents),customAccentNames:Ki(n.customAccentNames,Kr(n.customAccents)),customThemeId:id(n.customThemeId)}}function qP(e,t){const n={...e??{}};if(t<1&&eM(n),t<2)for(const r of zP)delete n[r];if(t<3){let r=null;for(const o of Gc)if(n[vp(o)]===!0){r=o;break}r!==null&&(n.rightSlotLegacySeed=r);for(const o of Gc)delete n[vp(o)]}return t<4&&(n.finderFiles=ed(n.finderFiles)),t<5&&(n.contrast=R_(n.contrast),n.accent=x_(n.accent,Vc),n.customAccents=Kr(n.customAccents),n.customThemeId=id(n.customThemeId)),n}function eM(e){const t=[["canvasWidth",800],["runPanelWidth",420],["browserPanelWidth",640],["consolePanelWidth",796]];let n=0;for(const[r,o]of t){const i=e[r];if(typeof i=="number"&&i>0&&i!==o){n=i;break}}for(const[r]of t)delete e[r];e.rightSlotWidth=n}const zc=e=>e.replace(/\\/g,"/"),P_=()=>window.location.hash?zc(window.location.hash.substring(1)):zc(window.location.pathname),HF=(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,"/")},WF=(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]==="",i=o?n.slice(0,2):n.slice(0,1),a=n.slice(i.length),c=y=>{const v=t-y.length-(y?3:2);let b=[];for(let p=a.length-1;p>=0;p-=1){const A=[a[p],...b];if(A.join("/").length>v)break;b=A}return b},l=(y,v)=>y?`${y}/…/${v.join("/")}`:`…/${v.join("/")}`,d=i.join("/"),u=c(d);if(u.length>0)return u.length===a.length?e:l(d,u);const f=o?n[0]:"",h=c(f);if(h.length>0)return l(f,h);const _=t-(f?`${f}/…/`.length:2);return _>0?l(f,[r.slice(-_)]):"…"},GF=(e,t)=>zc(e).includes(t);function tM(e,t){const n=Je.getState();if(n.activeSessionId===e&&!n.activeDraftKey)return null;const r=Fr.begin(e,t);return cR(Fr,r,()=>Je.getState(),Je.subscribe),r}let kp=!1;function nM(){if(kp||typeof window>"u"||typeof window.addEventListener!="function")return;kp=!0;const e=()=>{const t=m0();t&&(P_().split("/").includes(t)||g0(t))};window.addEventListener("hashchange",e),window.addEventListener("popstate",e)}function zF(e,t,n="open"){const r=tM(t,n);if(r!==null){Fr.note(t,"request",r,{fallback:!0});const c=Je.getState();try{_0(t,{remoteOwned:Tg(c.sessions,c.placementFacts,t)}),nM()}catch{}}const i=Je.getState().openSession(t),a=`/chat/${t}`;return e(a),i.then(c=>{if(c||P_()!==a)return;const l=Je.getState();if(l.activeDraftKey){e("/chat",{replace:!0});return}const d=l.activeSessionId;e(d?`/chat/${d}`:"/chat",{replace:!0})}),i}const Kc=e=>{const t=JSON.stringify(Object.keys(e).sort().map(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)},rM=(e,{contrast:t=0,accent:n={kind:"theme"},id:r,paletteAccent:o,preserveSecondary:i=!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=aP(e,t,{id:r});let l=c.palette,d=!0,u=0;if(!a){const f=hP(l,n,{authored:e,id:r,paletteAccent:o,preserveSecondary:i});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-${Kc(l)}`,effectiveContrast:c.effectiveContrast,requestedContrast:t,accentApplied:d,accentAdjusted:u}},Sp="lo-composed-theme",oM=4,Gn=new Map,iM=(e,t)=>{const n=Gn.get(e);if(n)return Gn.delete(e),Gn.set(e,n),n;const r=H_(t);if(Gn.set(e,r),Gn.size>oM){const o=Gn.keys().next().value;o!==void 0&&Gn.delete(o)}return r},sM=e=>Zc(e)?.palette.accent,aM=16,yr=new Map,cM=(e,t,n)=>{const r=Ep(e.themeName),o=Zc(r.id);if(!o)throw new Error(`no palette for theme ${r.id}`);const i=t??o.palette,a=i.mode,c=n??r.id,l=e.contrast[a]??0,d=e.accent[a],u=JSON.stringify([r.id,n??null,t?Kc(t):null,l,d??null]);let f=yr.get(u);if(f?yr.delete(u):f=rM(i,{contrast:l,accent:d,id:c,preserveSecondary:t!==void 0,paletteAccent:sM}),yr.set(u,f),yr.size>aM){const _=yr.keys().next().value;_!==void 0&&yr.delete(_)}if(f.identity&&!n)return{...f,id:r.id,muiTheme:r.theme};const h=`lo-${Kc(f.palette)}`;return{...f,id:h,identity:!1,muiTheme:iM(h,f.palette)}},lM=(e,t)=>Yc(e)&&Object.entries(t).every(([n,r])=>n==="mode"||Xc(r))&&(t.mode==="dark"||t.mode==="light"),KF=(e,t=document,n,r,o=i=>cM(i,n,r))=>{let i=o(e);if(!i.identity&&!lM(i.id,i.palette)){console.error(`[theme] refused to publish composed theme ${JSON.stringify(i.id).slice(0,60)}: an id or value is outside the CSS grammar; showing the built-in theme`);const l=Ep(e.themeName),d=Zc(l.id);if(!d)throw new Error(`no palette for theme ${l.id}`);i={identity:!0,palette:d.palette,id:l.id,effectiveContrast:0,requestedContrast:i.requestedContrast,accentApplied:!1,accentAdjusted:0,muiTheme:l.theme}}const a=t.documentElement,c=t.getElementById(Sp);if(i.identity)c?.remove();else{const l=c??t.createElement("style");l.id=Sp,l.textContent=Ip(i.id,i.palette),c||t.head.appendChild(l)}return cT(t,i.identity?null:i.palette),a.dataset.theme=i.id,a.classList.toggle("dark",i.palette.mode==="dark"),i},VF=e=>({themeName:e.themeName,customThemeId:e.customThemeId??null,contrast:e.contrast,accent:e.accent}),ZF=e=>JSON.stringify([e.themeName,e.contrast?.dark??0,e.contrast?.light??0,e.accent?.dark??null,e.accent?.light??null,e.customThemeId??null]);export{mg as $,Je as A,UN as B,zN as C,pF as D,p1 as E,u1 as F,KF as G,VF as H,BF as I,lt as J,zC as K,ZF as L,cM as M,s as N,mh as O,du as P,Ae as Q,j$ as R,mt as S,$$ as T,wg as U,zx as V,Kx as W,SN as X,hg as Y,bN as Z,yN as _,hj as a,gP as a$,vN as a0,mN as a1,kN as a2,_N as a3,wN as a4,lL as a5,Qm as a6,Rg as a7,VN as a8,ZN as a9,zc as aA,Sk as aB,RM as aC,Uj as aD,OM as aE,qv as aF,CM as aG,PM as aH,gM as aI,Cp as aJ,Zs as aK,rl as aL,hM as aM,Zv as aN,Vv as aO,pR as aP,Mx as aQ,wD as aR,SD as aS,ED as aT,ng as aU,wL as aV,sC as aW,yL as aX,aC as aY,cC as aZ,gt as a_,Ns as aa,bL as ab,YP as ac,gD as ad,yn as ae,st as af,Zr as ag,Bc as ah,pM as ai,k0 as aj,zy as ak,Ky as al,gu as am,$M as an,aN as ao,YD as ap,NM as aq,K_ as ar,We as as,ec as at,Is as au,$y as av,wo as aw,fj as ax,ij as ay,ch as az,cj as b,NF as b$,IF as b0,PF as b1,EP as b2,rL as b3,kP as b4,kF as b5,en as b6,xF as b7,mp as b8,wF as b9,Nd as bA,Cb as bB,Ld as bC,Tb as bD,Rb as bE,nL as bF,C1 as bG,KN as bH,$N as bI,P_ as bJ,GF as bK,AM as bL,IM as bM,EM as bN,SM as bO,TM as bP,Yp as bQ,Ut as bR,Eo as bS,l$ as bT,d$ as bU,ky as bV,I0 as bW,uj as bX,qM as bY,dj as bZ,lj as b_,SF as ba,EF as bb,AF as bc,RF as bd,TF as be,MF as bf,OS as bg,S1 as bh,pj as bi,__ as bj,rM as bk,CF as bl,_F as bm,BC as bn,uF as bo,mD as bp,VD as bq,ni as br,ot as bs,Rp as bt,gb as bu,yb as bv,Sb as bw,xb as bx,Ib as by,Ab as bz,mj as c,QL as c$,mF as c0,_n as c1,Vd as c2,il as c3,nw as c4,Ss as c5,th as c6,gN as c7,ae as c8,hN as c9,HF as cA,BL as cB,HL as cC,PC as cD,Wf as cE,CL as cF,eF as cG,tF as cH,nF as cI,TL as cJ,lD as cK,cf as cL,uD as cM,dD as cN,fD as cO,xg as cP,tL as cQ,rF as cR,WL as cS,VL as cT,ZL as cU,GL as cV,zL as cW,Er as cX,AL as cY,d_ as cZ,$L as c_,Sr as ca,Ic as cb,Ac as cc,fN as cd,pN as ce,cN as cf,lN as cg,dN as ch,gF as ci,UF as cj,HP as ck,FF as cl,lh as cm,ej as cn,KM as co,uh as cp,d0 as cq,uy as cr,tb as cs,fy as ct,ql as cu,YM as cv,Cf as cw,tj as cx,k1 as cy,TN as cz,la as d,qg as d$,qo as d0,JL as d1,hD as d2,qL as d3,Ur as d4,Mf as d5,NL as d6,DL as d7,LL as d8,UL as d9,Ni as dA,ei as dB,aF as dC,dF as dD,DM as dE,MM as dF,vL as dG,WF as dH,fF as dI,zA as dJ,pD as dK,kM as dL,yR as dM,bj as dN,DF as dO,$c as dP,$P as dQ,po as dR,$F as dS,pL as dT,hL as dU,fL as dV,Xl as dW,Jl as dX,QM as dY,JM as dZ,UP as d_,FL as da,OL as db,YL as dc,XL as dd,SL as de,EL as df,EN as dg,AN as dh,RL as di,IN as dj,Fs as dk,xL as dl,YN as dm,l_ as dn,KL as dp,ML as dq,jL as dr,PL as ds,IL as dt,oF as du,iF as dv,cF as dw,lF as dx,FC as dy,sF as dz,aL as e,gj as e$,BP as e0,wp as e1,_D as e2,Zl as e3,bD as e4,vD as e5,JN as e6,XN as e7,QN as e8,eL as e9,DN as eA,oC as eB,BN as eC,uN as eD,BM as eE,WM as eF,HM as eG,oj as eH,Bs as eI,Hs as eJ,g_ as eK,tO as eL,td as eM,QD as eN,um as eO,xr as eP,D$ as eQ,Nn as eR,nr as eS,ly as eT,hF as eU,Xa as eV,_L as eW,tM as eX,uL as eY,JT as eZ,e_,qN as ea,z0 as eb,ai as ec,aj as ed,HN as ee,Np as ef,js as eg,mx as eh,RD as ei,rN as ej,oN as ek,Ig as el,g1 as em,Fr as en,Ms as eo,WN as ep,GN as eq,Ck as er,ZD as es,CD as et,jN as eu,kx as ev,l1 as ew,Eg as ex,a1 as ey,Af as ez,$T as f,hR as f$,_j as f0,lb as f1,GC as f2,yM as f3,cd as f4,jF as f5,jd as f6,vM as f7,bM as f8,Ua as f9,mL as fA,Qg as fB,tC as fC,Kl as fD,GM as fE,Jd as fF,Lw as fG,zM as fH,gy as fI,XD as fJ,LD as fK,FD as fL,FM as fM,UM as fN,ND as fO,rg as fP,gR as fQ,Rm as fR,h_ as fS,Qh as fT,Hw as fU,VM as fV,yD as fW,kD as fX,TD as fY,xD as fZ,ID as f_,Ro as fa,pb as fb,Eb as fc,Ob as fd,_M as fe,WE as ff,oL as fg,dr as fh,zg as fi,sL as fj,NT as fk,Hg as fl,iL as fm,cL as fn,dL as fo,rj as fp,sj as fq,Es as fr,kt as fs,mb as ft,fh as fu,y1 as fv,Yr as fw,LF as fx,gL as fy,Yl as fz,O0 as g,$k as g$,MD as g0,PD as g1,Tr as g2,XM as g3,nj as g4,ZM as g5,Rj as g6,ml as g7,ul as g8,Dn as g9,O$ as gA,P$ as gB,C$ as gC,T$ as gD,h$ as gE,bE as gF,_E as gG,Ho as gH,g$ as gI,p$ as gJ,u$ as gK,o$ as gL,Bu as gM,c$ as gN,_$ as gO,a$ as gP,s$ as gQ,i$ as gR,t$ as gS,Zj as gT,e$ as gU,Hj as gV,Wj as gW,zj as gX,Gj as gY,qh as gZ,Qj as g_,nn as ga,vs as gb,bF as gc,yF as gd,OF as ge,od as gf,PO as gg,MO as gh,E_ as gi,vF as gj,id as gk,vE as gl,m$ as gm,f$ as gn,I$ as go,A$ as gp,M$ as gq,x$ as gr,y$ as gs,w$ as gt,k$ as gu,v$ as gv,S$ as gw,E$ as gx,b$ as gy,R$ as gz,Pb as h,kL as h$,aD as h0,Qk as h1,Wx as h2,qj as h3,yI as h4,eD as h5,wm as h6,nD as h7,J$ as h8,Q$ as h9,N$ as hA,Oj as hB,Xj as hC,qS as hD,Jh as hE,Lh as hF,$j as hG,qd as hH,nd as hI,WC as hJ,_k as hK,Vj as hL,XS as hM,Jj as hN,n$ as hO,r$ as hP,Yj as hQ,Xk as hR,Mj as hS,Hk as hT,Dj as hU,Nj as hV,Fj as hW,Lj as hX,Bj as hY,Kj as hZ,cD as h_,tD as ha,_I as hb,ma as hc,q$ as hd,wI as he,Z$ as hf,F$ as hg,K$ as hh,oD as hi,L$ as hj,V$ as hk,X$ as hl,sD as hm,iD as hn,Y$ as ho,U$ as hp,B$ as hq,H$ as hr,W$ as hs,G$ as ht,z$ as hu,rD as hv,py as hw,hy as hx,my as hy,Mu as hz,V_ as i,LN as i$,WD as i0,BD as i1,OR as i2,zD as i3,HD as i4,UD as i5,GD as i6,KD as i7,Pj as i8,jj as i9,Tj as iA,lk as iB,Th as iC,fl as iD,Ih as iE,Y0 as iF,X0 as iG,Aj as iH,ay as iI,Ij as iJ,wj as iK,Sj as iL,xu as iM,yj as iN,vj as iO,Ej as iP,Tu as iQ,kj as iR,ih as iS,Cj as iT,xj as iU,FN as iV,OD as iW,DD as iX,jD as iY,$D as iZ,NN as i_,vc as ia,Qn as ib,ON as ic,PN as id,RN as ie,xN as ig,MN as ih,Ql as ii,fC as ij,LM as ik,bc as il,AD as im,qD as io,eN as ip,nN as iq,fR as ir,tN as is,iN as it,Px as iu,sN as iv,j0 as iw,CN as ix,xh as iy,Wo as iz,Ge as j,Yv as j0,Qd as j1,JD as j2,ns as k,mM as l,Dp as m,S0 as n,zF as o,jM as p,Oy as q,A0 as r,Py as s,My as t,vb as u,jy as v,oi as w,xM as x,wM as y,Tg as z};