local-operator-ui 0.50.0 → 0.50.2

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 (102) hide show
  1. package/out/main/index.js +128 -16
  2. package/out/renderer/assets/{_basePickBy-lGrnJBuR.js → _basePickBy-B0CGodz5.js} +1 -1
  3. package/out/renderer/assets/{_baseUniq-pte-KX1w.js → _baseUniq-8ysZQvmz.js} +1 -1
  4. package/out/renderer/assets/{agent-details-page-Z9dxDwRo.js → agent-details-page-CdnNoAG1.js} +1 -1
  5. package/out/renderer/assets/{agent-hub-page-Cz8gFsZM.js → agent-hub-page-DzJe_j6z.js} +1 -1
  6. package/out/renderer/assets/{agents-page-COqm0S08.js → agents-page-B8ehgi1r.js} +3 -3
  7. package/out/renderer/assets/appearance-DxToWtVc.js +65 -0
  8. package/out/renderer/assets/{approvalsOverlay-CicMWNcZ.js → approvalsOverlay-C-vFFJMh.js} +1 -1
  9. package/out/renderer/assets/{arc-hAc2en7O.js → arc-C6vMPnZo.js} +1 -1
  10. package/out/renderer/assets/{architectureDiagram-IEHRJDOE-D_y6xNyM.js → architectureDiagram-IEHRJDOE-BaKmVFd8.js} +1 -1
  11. package/out/renderer/assets/{avatar-cropper-C7py7Qx_.js → avatar-cropper-CCvczwaj.js} +1 -1
  12. package/out/renderer/assets/{blockDiagram-JOT3LUYC-Nxeg066s.js → blockDiagram-JOT3LUYC-DNJTzz0-.js} +1 -1
  13. package/out/renderer/assets/{book-open-CcuWpl8w.js → book-open-AjJXGzb6.js} +1 -1
  14. package/out/renderer/assets/browser-page-B1LNZlf_.js +1 -0
  15. package/out/renderer/assets/{browser-webauthn-prompt-BB_bJj8e.js → browser-webauthn-prompt-D7ldFLmy.js} +1 -1
  16. package/out/renderer/assets/{building-2-DUTiKSZR.js → building-2-DrbuKv4e.js} +1 -1
  17. package/out/renderer/assets/{c4Diagram-VJAJSXHY-7blpEUA4.js → c4Diagram-VJAJSXHY-CFvnENAF.js} +1 -1
  18. package/out/renderer/assets/channel-C0mudVZF.js +1 -0
  19. package/out/renderer/assets/{chunk-4BMEZGHF-BnppHVjz.js → chunk-4BMEZGHF-DSSF88xF.js} +1 -1
  20. package/out/renderer/assets/{chunk-A2AXSNBT-lcrRt06T.js → chunk-A2AXSNBT-DW2Smd4N.js} +1 -1
  21. package/out/renderer/assets/{chunk-AEK57VVT-CWuCvRUX.js → chunk-AEK57VVT-vmOkmkFl.js} +1 -1
  22. package/out/renderer/assets/{chunk-D6G4REZN-NylPQJHQ.js → chunk-D6G4REZN-C-1gQ6dD.js} +1 -1
  23. package/out/renderer/assets/{chunk-RZ5BOZE2-BAbSYrOw.js → chunk-RZ5BOZE2-CvkHOneP.js} +1 -1
  24. package/out/renderer/assets/{chunk-XZIHB7SX-Czwc89Qp.js → chunk-XZIHB7SX-DtVS8cQp.js} +1 -1
  25. package/out/renderer/assets/classDiagram-GIVACNV2-DfsohnxP.js +1 -0
  26. package/out/renderer/assets/classDiagram-v2-COTLJTTW-DfsohnxP.js +1 -0
  27. package/out/renderer/assets/clone-DogRJTvD.js +1 -0
  28. package/out/renderer/assets/{console-mirror-D3KgKkJ4.js → console-mirror-CUiw0R0Z.js} +1 -1
  29. package/out/renderer/assets/{consoleCapture-hEDcGqMm.js → consoleCapture-CEIY9xSK.js} +1 -1
  30. package/out/renderer/assets/{conversation-input-sync-Dxp2po1V.js → conversation-input-sync-BGfWeOqy.js} +258 -258
  31. package/out/renderer/assets/{dagre-OKDRZEBW-cJiulspo.js → dagre-OKDRZEBW-CWzXBwaH.js} +1 -1
  32. package/out/renderer/assets/{diagram-SSKATNLV-DuU2Ob4k.js → diagram-SSKATNLV-t868hyXW.js} +1 -1
  33. package/out/renderer/assets/{diagram-VNBRO52H-ByaPlu8m.js → diagram-VNBRO52H-DUoOE-bt.js} +1 -1
  34. package/out/renderer/assets/{erDiagram-Q7BY3M3F-xg39R-Hw.js → erDiagram-Q7BY3M3F-DYWVOUdq.js} +1 -1
  35. package/out/renderer/assets/{error-boundary-CGxvzGme.js → error-boundary-CtkXM619.js} +1 -1
  36. package/out/renderer/assets/{flowDiagram-4HSFHLVR-DhHpCd7_.js → flowDiagram-4HSFHLVR-BswlGsLM.js} +1 -1
  37. package/out/renderer/assets/{ganttDiagram-APWFNJXF-DsA_iVfT.js → ganttDiagram-APWFNJXF-CCEe3Tdm.js} +1 -1
  38. package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-BeD4wz46.js → gitGraphDiagram-7IBYFJ6S-Bl10LWvi.js} +1 -1
  39. package/out/renderer/assets/{graph-BAW_Wl-7.js → graph-DKQjDGox.js} +1 -1
  40. package/out/renderer/assets/{heart-B-Sb1Tu4.js → heart-mTaKHtD-.js} +1 -1
  41. package/out/renderer/assets/{index-iOn7FNrw.js → index-BcwoLiEJ.js} +1 -1
  42. package/out/renderer/assets/{index-DdP_V3o3.js → index-Bh3nSSKU.js} +208 -203
  43. package/out/renderer/assets/{index-M2Q3Vvud.js → index-CWP3MhTA.js} +1 -1
  44. package/out/renderer/assets/{index-kQ72C_pJ.css → index-CaftKcJ-.css} +1 -1
  45. package/out/renderer/assets/{index-LyMDqjwu.js → index-CfE0tEz7.js} +1 -1
  46. package/out/renderer/assets/infoDiagram-PH2N3AL5-BOATky3y.js +2 -0
  47. package/out/renderer/assets/{installer-DHJd0qet.js → installer-D-_8CWoh.js} +1 -1
  48. package/out/renderer/assets/{journeyDiagram-U35MCT3I-D2CcuKmx.js → journeyDiagram-U35MCT3I-B5JRH6pA.js} +1 -1
  49. package/out/renderer/assets/{kanban-definition-NDS4AKOZ-Dmn-Ixie.js → kanban-definition-NDS4AKOZ-BMQ51i2A.js} +1 -1
  50. package/out/renderer/assets/{layout-CMyXRMah.js → layout-BlYEyiLa.js} +1 -1
  51. package/out/renderer/assets/{legacy-agents-page-9XFymm4j.js → legacy-agents-page-Ca9aGS2m.js} +1 -1
  52. package/out/renderer/assets/{library-page-Ca8qV_y6.js → library-page-1Q4ToZpC.js} +29 -29
  53. package/out/renderer/assets/{log-in-D82RadKB.js → log-in-Cz3YBOsh.js} +1 -1
  54. package/out/renderer/assets/{mermaid.core-9drGuzsu.js → mermaid.core-D7HsriVr.js} +5 -5
  55. package/out/renderer/assets/{mesh-page-ZoAeUlTN.js → mesh-page-B2xAXfjA.js} +1 -1
  56. package/out/renderer/assets/{messages-BFeJYEKx.js → messages-CvRfSjnp.js} +8 -8
  57. package/out/renderer/assets/{mindmap-definition-ALO5MXBD-CFPSzITF.js → mindmap-definition-ALO5MXBD-CMk15Uui.js} +1 -1
  58. package/out/renderer/assets/{mini-Db9iHOlL.js → mini-lkT5V9WE.js} +1 -1
  59. package/out/renderer/assets/{notebook-pen-Dk1ZVNZY.js → notebook-pen-DadCKhKK.js} +1 -1
  60. package/out/renderer/assets/{notifications-page-DozJ9vPE.js → notifications-page-DLvG89Rx.js} +1 -1
  61. package/out/renderer/assets/{org-access-ZqOP2qWb.js → org-access-mvMfl6RO.js} +1 -1
  62. package/out/renderer/assets/{org-surface-gate-2rpCIwjt.js → org-surface-gate-DG0gOjUM.js} +1 -1
  63. package/out/renderer/assets/{page-header-cvl2kE3M.js → page-header-CyxvZBjK.js} +1 -1
  64. package/out/renderer/assets/{pieDiagram-IB7DONF6-DsP1Eugm.js → pieDiagram-IB7DONF6-B5VgM5cu.js} +1 -1
  65. package/out/renderer/assets/{project-markdown-BR8Zqhbr.js → project-markdown-C7j9JEv7.js} +1 -1
  66. package/out/renderer/assets/{projects-page-Bv0lsufR.js → projects-page-Cy7ci4iQ.js} +1 -1
  67. package/out/renderer/assets/{publication-validation-rrxabkBj.js → publication-validation-LHyYGXxk.js} +1 -1
  68. package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-BqcOGQfG.js → quadrantDiagram-7GDLP6J5-CabDBOXn.js} +1 -1
  69. package/out/renderer/assets/{radar-MK3ICKWK-GCl99S35.js → radar-MK3ICKWK-Bs5DDyVg.js} +1 -1
  70. package/out/renderer/assets/{radient-auth-buttons-en5FAXg4.js → radient-auth-buttons-CjpUv3nP.js} +1 -1
  71. package/out/renderer/assets/{requirementDiagram-KVF5MWMF-DprWueCE.js → requirementDiagram-KVF5MWMF-s_UB9693.js} +1 -1
  72. package/out/renderer/assets/{roles-KXyR--wS.js → roles-D1pcbxAx.js} +1 -1
  73. package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-Dopn4P2k.js → sankeyDiagram-QLVOVGJD-FBDT6-L8.js} +1 -1
  74. package/out/renderer/assets/{schedules-page-DhI6ek4D.js → schedules-page-DWG-H1tc.js} +1 -1
  75. package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-B4bTz0nC.js → sequenceDiagram-X6HHIX6F-Dk2LRARF.js} +1 -1
  76. package/out/renderer/assets/settings-page-Cc3TAlMl.js +296 -0
  77. package/out/renderer/assets/smartart-CZP-KJQm.js +1 -0
  78. package/out/renderer/assets/{stateDiagram-DGXRK772-ChaHDZEF.js → stateDiagram-DGXRK772-nAeHi0Q3.js} +1 -1
  79. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-CdCpeeGq.js +1 -0
  80. package/out/renderer/assets/{team-bridge-page-CXPAGqCx.js → team-bridge-page-DyGy6Kbj.js} +20 -20
  81. package/out/renderer/assets/{team-bridge-scope-preference-DiTLGS2H.js → team-bridge-scope-preference-DMVpYrdA.js} +1 -1
  82. package/out/renderer/assets/{timeline-definition-BDJGKUSR-Cs2qa5IM.js → timeline-definition-BDJGKUSR-pJTYZrUl.js} +1 -1
  83. package/out/renderer/assets/{use-download-agent-mutation-Dgouj0xJ.js → use-download-agent-mutation-BimCWRpf.js} +1 -1
  84. package/out/renderer/assets/{use-session-snapshot-BlA6ikDu.js → use-session-snapshot-D90Nwywl.js} +1 -1
  85. package/out/renderer/assets/{xychartDiagram-VJFVF3MP-BchqXXt4.js → xychartDiagram-VJFVF3MP-CNYZmTD0.js} +1 -1
  86. package/out/renderer/browser-approvals-overlay.html +3 -3
  87. package/out/renderer/console-capture.html +7 -7
  88. package/out/renderer/index.html +9 -9
  89. package/out/renderer/installer.html +5 -5
  90. package/out/renderer/mini.html +9 -9
  91. package/package.json +1 -1
  92. package/out/renderer/assets/appearance-BP7od2ad.js +0 -65
  93. package/out/renderer/assets/browser-page-Dzqm0H3q.js +0 -1
  94. package/out/renderer/assets/channel-Be5WncX5.js +0 -1
  95. package/out/renderer/assets/classDiagram-GIVACNV2-CsBMVjCt.js +0 -1
  96. package/out/renderer/assets/classDiagram-v2-COTLJTTW-CsBMVjCt.js +0 -1
  97. package/out/renderer/assets/clone-Cjm_Ye8h.js +0 -1
  98. package/out/renderer/assets/hash-CYvFNwsC.js +0 -6
  99. package/out/renderer/assets/infoDiagram-PH2N3AL5-D0IVoTiR.js +0 -2
  100. package/out/renderer/assets/settings-page-KL9Tf3Db.js +0 -296
  101. package/out/renderer/assets/smartart-DRxFRqM8.js +0 -1
  102. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-DsNbsRL4.js +0 -1
@@ -0,0 +1,65 @@
1
+ import{r as I,j as gm,b as ol,D as _m,i as Ba,e as Bu,f as Ha,h as bm}from"./index-BcwoLiEJ.js";import{t as v,a as vm}from"./messages-CvRfSjnp.js";import{P as ym,i as Wa,a as Ga,p as Hu}from"./roles-D1pcbxAx.js";var Es=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(){}},Vn=typeof window>"u"||"Deno"in globalThis;function Rt(){}function wm(e,t){return typeof e=="function"?e(t):e}function Fi(e){return typeof e=="number"&&e>=0&&e!==1/0}function Wu(e,t){return Math.max(e+(t||0)-Date.now(),0)}function mr(e,t){return typeof e=="function"?e(t):e}function Nt(e,t){return typeof e=="function"?e(t):e}function il(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:o,queryKey:i,stale:c}=e;if(i){if(r){if(t.queryHash!==za(i,t.options))return!1}else if(!ts(t.queryKey,i))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||s&&s!==t.state.fetchStatus||o&&!o(t))}function al(e,t){const{exact:n,status:r,predicate:s,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(es(t.options.mutationKey)!==es(o))return!1}else if(!ts(t.options.mutationKey,o))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function za(e,t){return(t?.queryKeyHashFn||es)(e)}function es(e){return JSON.stringify(e,(t,n)=>Hi(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function ts(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>ts(e[n],t[n])):!1}function Gu(e,t){if(e===t)return e;const n=cl(e)&&cl(t);if(n||Hi(e)&&Hi(t)){const r=n?e:Object.keys(e),s=r.length,o=n?t:Object.keys(t),i=o.length,c=n?[]:{};let l=0;for(let d=0;d<i;d++){const u=n?d:o[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=Gu(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return s===i&&l===s?e:c}return t}function Bi(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 cl(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Hi(e){if(!ll(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!ll(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ll(e){return Object.prototype.toString.call(e)==="[object Object]"}function km(e){return new Promise(t=>{setTimeout(t,e)})}function Wi(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Gu(e,t):t}function Sm(e){return e}function Em(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Am(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ka=Symbol();function zu(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ka?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Rm=class extends Es{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!Vn&&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"}},Va=new Rm,Im=class extends Es{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!Vn&&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}},lo=new Im;function Gi(){let e,t;const n=new Promise((s,o)=>{e=s,t=o});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}function Tm(e){return Math.min(1e3*2**e,3e4)}function Ku(e){return(e??"online")==="online"?lo.isOnline():!0}var Vu=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function ti(e){return e instanceof Vu}function Zu(e){let t=!1,n=0,r=!1,s;const o=Gi(),i=b=>{r||(h(new Vu(b)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>Va.isFocused()&&(e.networkMode==="always"||lo.isOnline())&&e.canRun(),u=()=>Ku(e.networkMode)&&e.canRun(),f=b=>{r||(r=!0,e.onSuccess?.(b),s?.(),o.resolve(b))},h=b=>{r||(r=!0,e.onError?.(b),s?.(),o.reject(b))},g=()=>new Promise(b=>{s=_=>{(r||d())&&b(_)},e.onPause?.()}).then(()=>{s=void 0,r||e.onContinue?.()}),y=()=>{if(r)return;let b;const _=n===0?e.initialPromise:void 0;try{b=_??e.fn()}catch(p){b=Promise.reject(p)}Promise.resolve(b).then(f).catch(p=>{if(r)return;const R=e.retry??(Vn?0:3),k=e.retryDelay??Tm,O=typeof k=="function"?k(n,p):k,L=R===!0||typeof R=="number"&&n<R||typeof R=="function"&&R(n,p);if(t||!L){h(p);return}n++,e.onFail?.(n,p),km(O).then(()=>d()?void 0:g()).then(()=>{t?h(p):y()})})};return{promise:o,cancel:i,continue:()=>(s?.(),o),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?y():g().then(y),o)}}var xm=e=>setTimeout(e,0);function Cm(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=xm;const o=c=>{t?e.push(c):s(()=>{n(c)})},i=()=>{const c=e;e=[],c.length&&s(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||i()}return l},batchCalls:c=>(...l)=>{o(()=>{c(...l)})},schedule:o,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var nt=Cm(),Yu=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Fi(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Vn?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},Om=class extends Yu{#t;#e;#n;#r;#s;#a;#i;constructor(e){super(),this.#i=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Pm(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#s?.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=Wi(this.state.data,e,this.options);return this.#o({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#o({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#s?.promise;return this.#s?.cancel(e),t?t.then(Rt).catch(Rt):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>Nt(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ka||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||!Wu(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#s?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#s?.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.#s&&(this.#i?this.#s.cancel({revert:!0}):this.#s.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#o({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.#s)return this.#s.continueRetry(),this.#s.promise}if(e&&this.setOptions(e),!this.options.queryFn){const c=this.observers.find(l=>l.options.queryFn);c&&this.setOptions(c.options)}const n=new AbortController,r=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},s=()=>{const c=zu(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(l),this.#i=!1,this.options.persister?this.options.persister(c,l,this):c(l)},o={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:s};r(o),this.options.behavior?.onFetch(o,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#o({type:"fetch",meta:o.fetchOptions?.meta});const i=c=>{ti(c)&&c.silent||this.#o({type:"error",error:c}),ti(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#s=Zu({initialPromise:t?.initialPromise,fn:o.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){i(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){i(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:i,onFail:(c,l)=>{this.#o({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#o({type:"pause"})},onContinue:()=>{this.#o({type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}),this.#s.start()}#o(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,...Qu(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 ti(r)&&r.revert&&this.#e?{...this.#e,fetchStatus:"idle"}:{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),nt.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function Qu(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ku(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Pm(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 Mm=class extends Es{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,s=t.queryHash??za(r,t);let o=this.get(s);return o||(o=new Om({client:e,queryKey:r,queryHash:s,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(o)),o}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){nt.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#t.get(e)}getAll(){return[...this.#t.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>il(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>il(e,n)):t}notify(e){nt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){nt.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){nt.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},jm=class extends Yu{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||$m(),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=Zu({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(r,s)=>{this.#r({type:"failed",failureCount:r,error:s})},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 s=await this.options.onMutate?.(e);s!==this.state.context&&this.#r({type:"pending",context:s,variables:e,isPaused:n})}const r=await this.#n.start();return await this.#e.config.onSuccess?.(r,e,this.state.context,this),await this.options.onSuccess?.(r,e,this.state.context),await this.#e.config.onSettled?.(r,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(r,null,e,this.state.context),this.#r({type:"success",data:r}),r}catch(r){try{throw await this.#e.config.onError?.(r,e,this.state.context,this),await this.options.onError?.(r,e,this.state.context),await this.#e.config.onSettled?.(void 0,r,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,r,e,this.state.context),r}finally{this.#r({type:"error",error:r})}}finally{this.#e.runNext(this)}}#r(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),nt.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#e.notify({mutation:this,type:"updated",action:e})})}};function $m(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Dm=class extends Es{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 jm({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=$s(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=$s(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=$s(e);if(typeof t=="string"){const r=this.#e.get(t)?.find(s=>s.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=$s(e);return typeof t=="string"?this.#e.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){nt.batch(()=>{this.#t.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#t.clear(),this.#e.clear()})}getAll(){return Array.from(this.#t)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>al(t,n))}findAll(e={}){return this.getAll().filter(t=>al(e,t))}notify(e){nt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return nt.batch(()=>Promise.all(e.map(t=>t.continue().catch(Rt))))}};function $s(e){return e.options.scope?.id}function dl(e){return{onFetch:(t,n)=>{const r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,o=t.state.data?.pages||[],i=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=zu(t.options,t.fetchOptions),g=async(y,b,_)=>{if(u)return Promise.reject();if(b==null&&y.pages.length)return Promise.resolve(y);const p={client:t.client,queryKey:t.queryKey,pageParam:b,direction:_?"backward":"forward",meta:t.options.meta};f(p);const R=await h(p),{maxPages:k}=t.options,O=_?Am:Em;return{pages:O(y.pages,R,k),pageParams:O(y.pageParams,b,k)}};if(s&&o.length){const y=s==="backward",b=y?Xu:zi,_={pages:o,pageParams:i},p=b(r,_);c=await g(_,p,y)}else{const y=e??o.length;do{const b=l===0?i[0]??r.initialPageParam:zi(r,c);if(l>0&&b==null)break;c=await g(c,b),l++}while(l<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function zi(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 Xu(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function kx(e,t){return t?zi(e,t)!=null:!1}function Sx(e,t){return!t||!e.getPreviousPageParam?!1:Xu(e,t)!=null}var Nm=class{#t;#e;#n;#r;#s;#a;#i;#o;constructor(e={}){this.#t=e.queryCache||new Mm,this.#e=e.mutationCache||new Dm,this.#n=e.defaultOptions||{},this.#r=new Map,this.#s=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#i=Va.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#o=lo.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#i?.(),this.#i=void 0,this.#o?.(),this.#o=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(mr(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}),o=this.#t.get(r.queryHash)?.state.data,i=wm(t,o);if(i!==void 0)return this.#t.build(this,r).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return nt.batch(()=>this.#t.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;nt.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return nt.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=nt.batch(()=>this.#t.findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Rt).catch(Rt)}invalidateQueries(e,t={}){return nt.batch(()=>(this.#t.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=nt.batch(()=>this.#t.findAll(e).filter(s=>!s.isDisabled()).map(s=>{let o=s.fetch(void 0,n);return n.throwOnError||(o=o.catch(Rt)),s.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then(Rt)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(mr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Rt).catch(Rt)}fetchInfiniteQuery(e){return e.behavior=dl(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Rt).catch(Rt)}ensureInfiniteQueryData(e){return e.behavior=dl(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return lo.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(es(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{ts(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#s.set(es(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{ts(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=za(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===Ka&&(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()}},Lm=class extends Es{constructor(e,t){super(),this.options=t,this.#t=e,this.#o=null,this.#i=Gi(),this.options.experimental_prefetchInRender||this.#i.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#r=void 0;#s;#a;#i;#o;#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),ul(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ki(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ki(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 Nt(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&&!Bi(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&fl(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||Nt(this.options.enabled,this.#e)!==Nt(t.enabled,this.#e)||mr(this.options.staleTime,this.#e)!==mr(t.staleTime,this.#e))&&this.#g();const s=this.#_();r&&(this.#e!==n||Nt(this.options.enabled,this.#e)!==Nt(t.enabled,this.#e)||s!==this.#c)&&this.#b(s)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return Fm(this,n)&&(this.#r=n,this.#a=this.options,this.#s=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(Rt)),t}#g(){this.#y();const e=mr(this.options.staleTime,this.#e);if(Vn||this.#r.isStale||!Fi(e))return;const n=Wu(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,!(Vn||Nt(this.options.enabled,this.#e)===!1||!Fi(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||Va.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,s=this.#r,o=this.#s,i=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&&ul(e,t),S=m&&fl(e,n,t,r);(w||S)&&(u={...u,...Qu(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:g,errorUpdatedAt:y,status:b}=u;h=u.data;let _=!1;if(t.placeholderData!==void 0&&h===void 0&&b==="pending"){let m;s?.isPlaceholderData&&t.placeholderData===i?.placeholderData?(m=s.data,_=!0):m=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,m!==void 0&&(b="success",h=Wi(s?.data,m,t),f=!0)}if(t.select&&h!==void 0&&!_)if(s&&h===o?.data&&t.select===this.#m)h=this.#f;else try{this.#m=t.select,h=t.select(h),h=Wi(s?.data,h,t),this.#f=h,this.#o=null}catch(m){this.#o=m}this.#o&&(g=this.#o,h=this.#f,y=Date.now(),b="error");const p=u.fetchStatus==="fetching",R=b==="pending",k=b==="error",O=R&&p,L=h!==void 0,T={status:b,fetchStatus:u.fetchStatus,isPending:R,isSuccess:b==="success",isError:k,isInitialLoading:O,isLoading:O,data:h,dataUpdatedAt:u.dataUpdatedAt,error:g,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&&!R,isLoadingError:k&&!L,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:k&&L,isStale:Za(e,t),refetch:this.refetch,promise:this.#i};if(this.options.experimental_prefetchInRender){const m=x=>{T.status==="error"?x.reject(T.error):T.data!==void 0&&x.resolve(T.data)},w=()=>{const x=this.#i=T.promise=Gi();m(x)},S=this.#i;switch(S.status){case"pending":e.queryHash===n.queryHash&&m(S);break;case"fulfilled":(T.status==="error"||T.data!==S.value)&&w();break;case"rejected":(T.status!=="error"||T.error!==S.reason)&&w();break}}return T}updateResult(){const e=this.#r,t=this.createResult(this.#e,this.options);if(this.#s=this.#e.state,this.#a=this.options,this.#s.data!==void 0&&(this.#p=this.#e),Bi(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,s=typeof r=="function"?r():r;if(s==="all"||!s&&!this.#h.size)return!0;const o=new Set(s??this.#h);return this.options.throwOnError&&o.add("error"),Object.keys(this.#r).some(i=>{const c=i;return this.#r[c]!==e[c]&&o.has(c)})};this.#S({listeners:n()})}#k(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#S(e){nt.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function Um(e,t){return Nt(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function ul(e,t){return Um(e,t)||e.state.data!==void 0&&Ki(e,t,t.refetchOnMount)}function Ki(e,t,n){if(Nt(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Za(e,t)}return!1}function fl(e,t,n,r){return(e!==t||Nt(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Za(e,n)}function Za(e,t){return Nt(t.enabled,e)!==!1&&e.isStaleByTime(mr(t.staleTime,e))}function Fm(e,t){return!Bi(e.getCurrentResult(),t)}var Ya=I.createContext(void 0),Bm=e=>{const t=I.useContext(Ya);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Ex=({client:e,children:t})=>(I.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),gm.jsx(Ya.Provider,{value:e,children:t})),Ju=I.createContext(!1),Hm=()=>I.useContext(Ju);Ju.Provider;function Wm(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Gm=I.createContext(Wm()),zm=()=>I.useContext(Gm);function Km(e,t){return typeof e=="function"?e(...t):!!e}function pl(){}var Vm=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},Zm=e=>{I.useEffect(()=>{e.clearReset()},[e])},Ym=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Km(n,[e.error,r])),Qm=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)))},Xm=(e,t)=>e.isLoading&&e.isFetching&&!t,Jm=(e,t)=>e?.suspense&&t.isPending,hl=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function qm(e,t,n){const r=Bm(n),s=Hm(),o=zm(),i=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(i),i._optimisticResults=s?"isRestoring":"optimistic",Qm(i),Vm(i,o),Zm(o);const c=!r.getQueryCache().get(i.queryHash),[l]=I.useState(()=>new t(r,i)),d=l.getOptimisticResult(i),u=!s&&e.subscribed!==!1;if(I.useSyncExternalStore(I.useCallback(f=>{const h=u?l.subscribe(nt.batchCalls(f)):pl;return l.updateResult(),h},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),I.useEffect(()=>{l.setOptions(i)},[i,l]),Jm(i,d))throw hl(i,l,o);if(Ym({result:d,errorResetBoundary:o,throwOnError:i.throwOnError,query:r.getQueryCache().get(i.queryHash),suspense:i.suspense}))throw d.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(i,d),i.experimental_prefetchInRender&&!Vn&&Xm(d,s)&&(c?hl(i,l,o):r.getQueryCache().get(i.queryHash)?.promise)?.catch(pl).finally(()=>{l.updateResult()}),i.notifyOnChangeProps?d:l.trackResult(d)}function qu(e,t){return qm(e,Lm,t)}const eg=()=>{const e=I.useContext(Ya)??null,t=I.useMemo(()=>new Nm({defaultOptions:{queries:{enabled:!1,retry:!1,gcTime:0}}}),[]);return I.useEffect(()=>{if(!e)return()=>t.clear()},[e,t]),I.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function Ax(e){return e!=="detached"&&e!=="wedged"}function ef(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function Rx(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=ef(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 ge;(function(e){e.assertEqual=s=>s;function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{const o={};for(const i of s)o[i]=i;return o},e.getValidEnumValues=s=>{const o=e.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),i={};for(const c of o)i[c]=s[c];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(const i of s)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ge||(ge={}));var Vi;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Vi||(Vi={}));const B=ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),rn=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}},M=ge.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"]),tg=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(o){return o.message},r={_errors:[]},s=o=>{for(const i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let c=r,l=0;for(;l<i.path.length;){const d=i.path[l];l===i.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(i))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return s(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,ge.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}kt.create=e=>new kt(e);const yr=(e,t)=>{let n;switch(e.code){case M.invalid_type:e.received===B.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case M.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ge.jsonStringifyReplacer)}`;break;case M.unrecognized_keys:n=`Unrecognized key(s) in object: ${ge.joinValues(e.keys,", ")}`;break;case M.invalid_union:n="Invalid input";break;case M.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ge.joinValues(e.options)}`;break;case M.invalid_enum_value:n=`Invalid enum value. Expected ${ge.joinValues(e.options)}, received '${e.received}'`;break;case M.invalid_arguments:n="Invalid function arguments";break;case M.invalid_return_type:n="Invalid function return type";break;case M.invalid_date:n="Invalid date";break;case M.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}"`:ge.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case M.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 M.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 M.custom:n="Invalid input";break;case M.invalid_intersection_types:n="Intersection results could not be merged";break;case M.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case M.not_finite:n="Number must be finite";break;default:n=t.defaultError,ge.assertNever(e)}return{message:n}};let tf=yr;function ng(e){tf=e}function uo(){return tf}const fo=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let c="";const l=r.filter(d=>!!d).slice().reverse();for(const d of l)c=d(i,{data:t,defaultError:c}).message;return{...s,path:o,message:c}},rg=[];function U(e,t){const n=uo(),r=fo({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===yr?void 0:yr].filter(s=>!!s)});e.common.issues.push(r)}class ct{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 s of n){if(s.status==="aborted")return q;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const s of n){const o=await s.key,i=await s.value;r.push({key:o,value:i})}return ct.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return q;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}}const q=Object.freeze({status:"aborted"}),ur=e=>({status:"dirty",value:e}),lt=e=>({status:"valid",value:e}),Zi=e=>e.status==="aborted",Yi=e=>e.status==="dirty",Zn=e=>e.status==="valid",ns=e=>typeof Promise<"u"&&e instanceof Promise;function po(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 nf(e,t,n,r,s){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var V;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(V||(V={}));var Wr,Gr;class Qt{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}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 ml=(e,t)=>{if(Zn(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:s}=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:s}:{errorMap:(i,c)=>{var l,d;const{message:u}=e;return i.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??r)!==null&&l!==void 0?l:c.defaultError}:i.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??n)!==null&&d!==void 0?d:c.defaultError}},description:s}}class le{get description(){return this._def.description}_getType(t){return rn(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:rn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ct,ctx:{common:t.parent.common,data:t.data,parsedType:rn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(ns(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 s={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:rn(t)},o=this._parseSync({data:t,path:s.path,parent:s});return ml(s,o)}"~validate"(t){var n,r;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:rn(t)};if(!this["~standard"].async)try{const o=this._parseSync({data:t,path:[],parent:s});return Zn(o)?{value:o.value}:{issues:s.common.issues}}catch(o){!((r=(n=o?.message)===null||n===void 0?void 0:n.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(o=>Zn(o)?{value:o.value}:{issues:s.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:rn(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(ns(s)?s:Promise.resolve(s));return ml(r,o)}refine(t,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{const i=t(s),c=()=>o.addIssue({code:M.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(c(),!1)):i?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new Bt({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 Zt.create(this,this._def)}nullable(){return Rn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ft.create(this)}promise(){return kr.create(this,this._def)}or(t){return is.create([this,t],this._def)}and(t){return as.create(this,t,this._def)}transform(t){return new Bt({...ce(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new fs({...ce(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new Qa({typeName:Q.ZodBranded,type:this,...ce(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new ps({...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 As.create(this,t)}readonly(){return hs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const sg=/^c[^\s-]{8,}$/i,og=/^[0-9a-z]+$/,ig=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ag=/^[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,cg=/^[a-z0-9_-]{21}$/i,lg=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,dg=/^[-+]?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)?)??$/,ug=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,fg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ni;const pg=/^(?:(?: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])$/,hg=/^(?:(?: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])$/,mg=/^(([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]))$/,gg=/^(([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])$/,_g=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,bg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rf="((\\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])))",vg=new RegExp(`^${rf}$`);function sf(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 yg(e){return new RegExp(`^${sf(e)}$`)}function of(e){let t=`${rf}T${sf(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 wg(e,t){return!!((t==="v4"||!t)&&pg.test(e)||(t==="v6"||!t)&&mg.test(e))}function kg(e,t){if(!lg.test(e))return!1;try{const[n]=e.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||!s.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function Sg(e,t){return!!((t==="v4"||!t)&&hg.test(e)||(t==="v6"||!t)&&gg.test(e))}class Ut extends le{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==B.string){const o=this._getOrReturnCtx(t);return U(o,{code:M.invalid_type,expected:B.string,received:o.parsedType}),q}const r=new ct;let s;for(const o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),U(s,{code:M.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(s=this._getOrReturnCtx(t,s),U(s,{code:M.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){const i=t.data.length>o.value,c=t.data.length<o.value;(i||c)&&(s=this._getOrReturnCtx(t,s),i?U(s,{code:M.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&U(s,{code:M.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")ug.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"email",code:M.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")ni||(ni=new RegExp(fg,"u")),ni.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"emoji",code:M.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")ag.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"uuid",code:M.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")cg.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"nanoid",code:M.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")sg.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"cuid",code:M.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")og.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"cuid2",code:M.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")ig.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"ulid",code:M.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),U(s,{validation:"url",code:M.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"regex",code:M.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(t,s),U(s,{code:M.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(s=this._getOrReturnCtx(t,s),U(s,{code:M.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(s=this._getOrReturnCtx(t,s),U(s,{code:M.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?of(o).test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{code:M.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?vg.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{code:M.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?yg(o).test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{code:M.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?dg.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"duration",code:M.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?wg(t.data,o.version)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"ip",code:M.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?kg(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"jwt",code:M.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?Sg(t.data,o.version)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"cidr",code:M.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?_g.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"base64",code:M.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?bg.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"base64url",code:M.invalid_string,message:o.message}),r.dirty()):ge.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:M.invalid_string,...V.errToObj(r)})}_addCheck(t){return new Ut({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...V.errToObj(t)})}url(t){return this._addCheck({kind:"url",...V.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...V.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...V.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...V.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...V.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...V.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...V.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...V.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...V.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...V.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...V.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...V.errToObj(t)})}datetime(t){var n,r;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(n=t?.offset)!==null&&n!==void 0?n:!1,local:(r=t?.local)!==null&&r!==void 0?r:!1,...V.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...V.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...V.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...V.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...V.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...V.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...V.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...V.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...V.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...V.errToObj(n)})}nonempty(t){return this.min(1,V.errToObj(t))}trim(){return new Ut({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ut({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ut({...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}}Ut.create=e=>{var t;return new Ut({checks:[],typeName:Q.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};function Eg(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=parseInt(e.toFixed(s).replace(".","")),i=parseInt(t.toFixed(s).replace(".",""));return o%i/Math.pow(10,s)}class Sn extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==B.number){const o=this._getOrReturnCtx(t);return U(o,{code:M.invalid_type,expected:B.number,received:o.parsedType}),q}let r;const s=new ct;for(const o of this._def.checks)o.kind==="int"?ge.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:M.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:M.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:M.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?Eg(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),U(r,{code:M.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:M.not_finite,message:o.message}),s.dirty()):ge.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,V.toString(n))}gt(t,n){return this.setLimit("min",t,!1,V.toString(n))}lte(t,n){return this.setLimit("max",t,!0,V.toString(n))}lt(t,n){return this.setLimit("max",t,!1,V.toString(n))}setLimit(t,n,r,s){return new Sn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:V.toString(s)}]})}_addCheck(t){return new Sn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:V.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:V.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:V.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:V.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:V.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:V.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:V.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:V.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:V.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&ge.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)}}Sn.create=e=>new Sn({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...ce(e)});class En extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==B.bigint)return this._getInvalidInput(t);let r;const s=new ct;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:M.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:M.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),U(r,{code:M.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):ge.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return U(n,{code:M.invalid_type,expected:B.bigint,received:n.parsedType}),q}gte(t,n){return this.setLimit("min",t,!0,V.toString(n))}gt(t,n){return this.setLimit("min",t,!1,V.toString(n))}lte(t,n){return this.setLimit("max",t,!0,V.toString(n))}lt(t,n){return this.setLimit("max",t,!1,V.toString(n))}setLimit(t,n,r,s){return new En({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:V.toString(s)}]})}_addCheck(t){return new En({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:V.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:V.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:V.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:V.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:V.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}En.create=e=>{var t;return new En({checks:[],typeName:Q.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};class rs extends le{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==B.boolean){const r=this._getOrReturnCtx(t);return U(r,{code:M.invalid_type,expected:B.boolean,received:r.parsedType}),q}return lt(t.data)}}rs.create=e=>new rs({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});class Yn extends le{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==B.date){const o=this._getOrReturnCtx(t);return U(o,{code:M.invalid_type,expected:B.date,received:o.parsedType}),q}if(isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return U(o,{code:M.invalid_date}),q}const r=new ct;let s;for(const o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),U(s,{code:M.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(s=this._getOrReturnCtx(t,s),U(s,{code:M.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):ge.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Yn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:V.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:V.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}}Yn.create=e=>new Yn({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...ce(e)});class ho extends le{_parse(t){if(this._getType(t)!==B.symbol){const r=this._getOrReturnCtx(t);return U(r,{code:M.invalid_type,expected:B.symbol,received:r.parsedType}),q}return lt(t.data)}}ho.create=e=>new ho({typeName:Q.ZodSymbol,...ce(e)});class ss extends le{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:M.invalid_type,expected:B.undefined,received:r.parsedType}),q}return lt(t.data)}}ss.create=e=>new ss({typeName:Q.ZodUndefined,...ce(e)});class os extends le{_parse(t){if(this._getType(t)!==B.null){const r=this._getOrReturnCtx(t);return U(r,{code:M.invalid_type,expected:B.null,received:r.parsedType}),q}return lt(t.data)}}os.create=e=>new os({typeName:Q.ZodNull,...ce(e)});class wr extends le{constructor(){super(...arguments),this._any=!0}_parse(t){return lt(t.data)}}wr.create=e=>new wr({typeName:Q.ZodAny,...ce(e)});class Bn extends le{constructor(){super(...arguments),this._unknown=!0}_parse(t){return lt(t.data)}}Bn.create=e=>new Bn({typeName:Q.ZodUnknown,...ce(e)});class cn extends le{_parse(t){const n=this._getOrReturnCtx(t);return U(n,{code:M.invalid_type,expected:B.never,received:n.parsedType}),q}}cn.create=e=>new cn({typeName:Q.ZodNever,...ce(e)});class mo extends le{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:M.invalid_type,expected:B.void,received:r.parsedType}),q}return lt(t.data)}}mo.create=e=>new mo({typeName:Q.ZodVoid,...ce(e)});class Ft extends le{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==B.array)return U(n,{code:M.invalid_type,expected:B.array,received:n.parsedType}),q;if(s.exactLength!==null){const i=n.data.length>s.exactLength.value,c=n.data.length<s.exactLength.value;(i||c)&&(U(n,{code:i?M.too_big:M.too_small,minimum:c?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(U(n,{code:M.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(U(n,{code:M.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,c)=>s.type._parseAsync(new Qt(n,i,n.path,c)))).then(i=>ct.mergeArray(r,i));const o=[...n.data].map((i,c)=>s.type._parseSync(new Qt(n,i,n.path,c)));return ct.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new Ft({...this._def,minLength:{value:t,message:V.toString(n)}})}max(t,n){return new Ft({...this._def,maxLength:{value:t,message:V.toString(n)}})}length(t,n){return new Ft({...this._def,exactLength:{value:t,message:V.toString(n)}})}nonempty(t){return this.min(1,t)}}Ft.create=(e,t)=>new Ft({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...ce(t)});function ir(e){if(e instanceof Ue){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Zt.create(ir(r))}return new Ue({...e._def,shape:()=>t})}else return e instanceof Ft?new Ft({...e._def,type:ir(e.element)}):e instanceof Zt?Zt.create(ir(e.unwrap())):e instanceof Rn?Rn.create(ir(e.unwrap())):e instanceof Xt?Xt.create(e.items.map(t=>ir(t))):e}class Ue extends le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=ge.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==B.object){const d=this._getOrReturnCtx(t);return U(d,{code:M.invalid_type,expected:B.object,received:d.parsedType}),q}const{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof cn&&this._def.unknownKeys==="strip"))for(const d in s.data)i.includes(d)||c.push(d);const l=[];for(const d of i){const u=o[d],f=s.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new Qt(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof cn){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(d==="strict")c.length>0&&(U(s,{code:M.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=s.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new Qt(s,f,s.path,u)),alwaysSet:u in s.data})}}return s.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=>ct.mergeObjectSync(r,d)):ct.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return V.errToObj,new Ue({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,o,i,c;const l=(i=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,n,r).message)!==null&&i!==void 0?i:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=V.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new Ue({...this._def,unknownKeys:"strip"})}passthrough(){return new Ue({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ue({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ue({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Q.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Ue({...this._def,catchall:t})}pick(t){const n={};return ge.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}omit(t){const n={};return ge.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}deepPartial(){return ir(this)}partial(t){const n={};return ge.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new Ue({...this._def,shape:()=>n})}required(t){const n={};return ge.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Zt;)o=o._def.innerType;n[r]=o}}),new Ue({...this._def,shape:()=>n})}keyof(){return af(ge.objectKeys(this.shape))}}Ue.create=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strip",catchall:cn.create(),typeName:Q.ZodObject,...ce(t)});Ue.strictCreate=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strict",catchall:cn.create(),typeName:Q.ZodObject,...ce(t)});Ue.lazycreate=(e,t)=>new Ue({shape:e,unknownKeys:"strip",catchall:cn.create(),typeName:Q.ZodObject,...ce(t)});class is extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(const c of o)if(c.result.status==="valid")return c.result;for(const c of o)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const i=o.map(c=>new kt(c.ctx.common.issues));return U(n,{code:M.invalid_union,unionErrors:i}),q}if(n.common.async)return Promise.all(r.map(async o=>{const i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o;const i=[];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"&&!o&&(o={result:u,ctx:d}),d.common.issues.length&&i.push(d.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;const c=i.map(l=>new kt(l));return U(n,{code:M.invalid_union,unionErrors:c}),q}}get options(){return this._def.options}}is.create=(e,t)=>new is({options:e,typeName:Q.ZodUnion,...ce(t)});const en=e=>e instanceof ls?en(e.schema):e instanceof Bt?en(e.innerType()):e instanceof ds?[e.value]:e instanceof An?e.options:e instanceof us?ge.objectValues(e.enum):e instanceof fs?en(e._def.innerType):e instanceof ss?[void 0]:e instanceof os?[null]:e instanceof Zt?[void 0,...en(e.unwrap())]:e instanceof Rn?[null,...en(e.unwrap())]:e instanceof Qa||e instanceof hs?en(e.unwrap()):e instanceof ps?en(e._def.innerType):[];class $o extends le{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.object)return U(n,{code:M.invalid_type,expected:B.object,received:n.parsedType}),q;const r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(U(n,{code:M.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const s=new Map;for(const o of n){const i=en(o.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of i){if(s.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);s.set(c,o)}}return new $o({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...ce(r)})}}function Qi(e,t){const n=rn(e),r=rn(t);if(e===t)return{valid:!0,data:e};if(n===B.object&&r===B.object){const s=ge.objectKeys(t),o=ge.objectKeys(e).filter(c=>s.indexOf(c)!==-1),i={...e,...t};for(const c of o){const l=Qi(e[c],t[c]);if(!l.valid)return{valid:!1};i[c]=l.data}return{valid:!0,data:i}}else if(n===B.array&&r===B.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let o=0;o<e.length;o++){const i=e[o],c=t[o],l=Qi(i,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===B.date&&r===B.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class as extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(Zi(o)||Zi(i))return q;const c=Qi(o.value,i.value);return c.valid?((Yi(o)||Yi(i))&&n.dirty(),{status:n.value,value:c.data}):(U(r,{code:M.invalid_intersection_types}),q)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}as.create=(e,t,n)=>new as({left:e,right:t,typeName:Q.ZodIntersection,...ce(n)});class Xt extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.array)return U(r,{code:M.invalid_type,expected:B.array,received:r.parsedType}),q;if(r.data.length<this._def.items.length)return U(r,{code:M.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),q;!this._def.rest&&r.data.length>this._def.items.length&&(U(r,{code:M.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const o=[...r.data].map((i,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new Qt(r,i,r.path,c)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>ct.mergeArray(n,i)):ct.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new Xt({...this._def,rest:t})}}Xt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Xt({items:e,typeName:Q.ZodTuple,rest:null,...ce(t)})};class cs extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.object)return U(r,{code:M.invalid_type,expected:B.object,received:r.parsedType}),q;const s=[],o=this._def.keyType,i=this._def.valueType;for(const c in r.data)s.push({key:o._parse(new Qt(r,c,r.path,c)),value:i._parse(new Qt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?ct.mergeObjectAsync(n,s):ct.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof le?new cs({keyType:t,valueType:n,typeName:Q.ZodRecord,...ce(r)}):new cs({keyType:Ut.create(),valueType:t,typeName:Q.ZodRecord,...ce(n)})}}class go extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.map)return U(r,{code:M.invalid_type,expected:B.map,received:r.parsedType}),q;const s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([c,l],d)=>({key:s._parse(new Qt(r,c,r.path,[d,"key"])),value:o._parse(new Qt(r,l,r.path,[d,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of i){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return q;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const l of i){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return q;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}go.create=(e,t,n)=>new go({valueType:t,keyType:e,typeName:Q.ZodMap,...ce(n)});class Qn extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.set)return U(r,{code:M.invalid_type,expected:B.set,received:r.parsedType}),q;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(U(r,{code:M.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(U(r,{code:M.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const o=this._def.valueType;function i(l){const d=new Set;for(const u of l){if(u.status==="aborted")return q;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>o._parse(new Qt(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>i(l)):i(c)}min(t,n){return new Qn({...this._def,minSize:{value:t,message:V.toString(n)}})}max(t,n){return new Qn({...this._def,maxSize:{value:t,message:V.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}Qn.create=(e,t)=>new Qn({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...ce(t)});class gr extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.function)return U(n,{code:M.invalid_type,expected:B.function,received:n.parsedType}),q;function r(c,l){return fo({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,uo(),yr].filter(d=>!!d),issueData:{code:M.invalid_arguments,argumentsError:l}})}function s(c,l){return fo({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,uo(),yr].filter(d=>!!d),issueData:{code:M.invalid_return_type,returnTypeError:l}})}const o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof kr){const c=this;return lt(async function(...l){const d=new kt([]),u=await c._def.args.parseAsync(l,o).catch(g=>{throw d.addIssue(r(l,g)),d}),f=await Reflect.apply(i,this,u);return await c._def.returns._def.type.parseAsync(f,o).catch(g=>{throw d.addIssue(s(f,g)),d})})}else{const c=this;return lt(function(...l){const d=c._def.args.safeParse(l,o);if(!d.success)throw new kt([r(l,d.error)]);const u=Reflect.apply(i,this,d.data),f=c._def.returns.safeParse(u,o);if(!f.success)throw new kt([s(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new gr({...this._def,args:Xt.create(t).rest(Bn.create())})}returns(t){return new gr({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new gr({args:t||Xt.create([]).rest(Bn.create()),returns:n||Bn.create(),typeName:Q.ZodFunction,...ce(r)})}}class ls extends le{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}ls.create=(e,t)=>new ls({getter:e,typeName:Q.ZodLazy,...ce(t)});class ds extends le{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return U(n,{received:n.data,code:M.invalid_literal,expected:this._def.value}),q}return{status:"valid",value:t.data}}get value(){return this._def.value}}ds.create=(e,t)=>new ds({value:e,typeName:Q.ZodLiteral,...ce(t)});function af(e,t){return new An({values:e,typeName:Q.ZodEnum,...ce(t)})}class An extends le{constructor(){super(...arguments),Wr.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{expected:ge.joinValues(r),received:n.parsedType,code:M.invalid_type}),q}if(po(this,Wr)||nf(this,Wr,new Set(this._def.values)),!po(this,Wr).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{received:n.data,code:M.invalid_enum_value,options:r}),q}return lt(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 An.create(t,{...this._def,...n})}exclude(t,n=this._def){return An.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Wr=new WeakMap;An.create=af;class us extends le{constructor(){super(...arguments),Gr.set(this,void 0)}_parse(t){const n=ge.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==B.string&&r.parsedType!==B.number){const s=ge.objectValues(n);return U(r,{expected:ge.joinValues(s),received:r.parsedType,code:M.invalid_type}),q}if(po(this,Gr)||nf(this,Gr,new Set(ge.getValidEnumValues(this._def.values))),!po(this,Gr).has(t.data)){const s=ge.objectValues(n);return U(r,{received:r.data,code:M.invalid_enum_value,options:s}),q}return lt(t.data)}get enum(){return this._def.values}}Gr=new WeakMap;us.create=(e,t)=>new us({values:e,typeName:Q.ZodNativeEnum,...ce(t)});class kr extends le{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.promise&&n.common.async===!1)return U(n,{code:M.invalid_type,expected:B.promise,received:n.parsedType}),q;const r=n.parsedType===B.promise?n.data:Promise.resolve(n.data);return lt(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}kr.create=(e,t)=>new kr({type:e,typeName:Q.ZodPromise,...ce(t)});class Bt extends le{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),s=this._def.effect||null,o={addIssue:i=>{U(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async c=>{if(n.value==="aborted")return q;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?q:l.status==="dirty"||n.value==="dirty"?ur(l.value):l});{if(n.value==="aborted")return q;const c=this._def.schema._parseSync({data:i,path:r.path,parent:r});return c.status==="aborted"?q:c.status==="dirty"||n.value==="dirty"?ur(c.value):c}}if(s.type==="refinement"){const i=c=>{const l=s.refinement(c,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?q:(c.status==="dirty"&&n.dirty(),i(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?q:(c.status==="dirty"&&n.dirty(),i(c.value).then(()=>({status:n.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Zn(i))return i;const c=s.transform(i.value,o);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(i=>Zn(i)?Promise.resolve(s.transform(i.value,o)).then(c=>({status:n.value,value:c})):i);ge.assertNever(s)}}Bt.create=(e,t,n)=>new Bt({schema:e,typeName:Q.ZodEffects,effect:t,...ce(n)});Bt.createWithPreprocess=(e,t,n)=>new Bt({schema:t,effect:{type:"preprocess",transform:e},typeName:Q.ZodEffects,...ce(n)});class Zt extends le{_parse(t){return this._getType(t)===B.undefined?lt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Zt.create=(e,t)=>new Zt({innerType:e,typeName:Q.ZodOptional,...ce(t)});class Rn extends le{_parse(t){return this._getType(t)===B.null?lt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Rn.create=(e,t)=>new Rn({innerType:e,typeName:Q.ZodNullable,...ce(t)});class fs extends le{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===B.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}fs.create=(e,t)=>new fs({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});class ps extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ns(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new kt(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new kt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ps.create=(e,t)=>new ps({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});class _o extends le{_parse(t){if(this._getType(t)!==B.nan){const r=this._getOrReturnCtx(t);return U(r,{code:M.invalid_type,expected:B.nan,received:r.parsedType}),q}return{status:"valid",value:t.data}}}_o.create=e=>new _o({typeName:Q.ZodNaN,...ce(e)});const Ag=Symbol("zod_brand");class Qa extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class As extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?q:o.status==="dirty"?(n.dirty(),ur(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?q:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new As({in:t,out:n,typeName:Q.ZodPipeline})}}class hs extends le{_parse(t){const n=this._def.innerType._parse(t),r=s=>(Zn(s)&&(s.value=Object.freeze(s.value)),s);return ns(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}hs.create=(e,t)=>new hs({innerType:e,typeName:Q.ZodReadonly,...ce(t)});function gl(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function cf(e,t={},n){return e?wr.create().superRefine((r,s)=>{var o,i;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=gl(t,r),h=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;s.addIssue({code:"custom",...f,fatal:h})}});if(!c){const l=gl(t,r),d=(i=(o=l.fatal)!==null&&o!==void 0?o:n)!==null&&i!==void 0?i:!0;s.addIssue({code:"custom",...l,fatal:d})}}):wr.create()}const Rg={object:Ue.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 Ig=(e,t={message:`Input not instance of ${e.name}`})=>cf(n=>n instanceof e,t),lf=Ut.create,df=Sn.create,Tg=_o.create,xg=En.create,uf=rs.create,Cg=Yn.create,Og=ho.create,Pg=ss.create,Mg=os.create,jg=wr.create,$g=Bn.create,Dg=cn.create,Ng=mo.create,Lg=Ft.create,Ug=Ue.create,Fg=Ue.strictCreate,Bg=is.create,Hg=$o.create,Wg=as.create,Gg=Xt.create,zg=cs.create,Kg=go.create,Vg=Qn.create,Zg=gr.create,Yg=ls.create,Qg=ds.create,Xg=An.create,Jg=us.create,qg=kr.create,_l=Bt.create,e_=Zt.create,t_=Rn.create,n_=Bt.createWithPreprocess,r_=As.create,s_=()=>lf().optional(),o_=()=>df().optional(),i_=()=>uf().optional(),a_={string:e=>Ut.create({...e,coerce:!0}),number:e=>Sn.create({...e,coerce:!0}),boolean:e=>rs.create({...e,coerce:!0}),bigint:e=>En.create({...e,coerce:!0}),date:e=>Yn.create({...e,coerce:!0})},c_=q;var a=Object.freeze({__proto__:null,defaultErrorMap:yr,setErrorMap:ng,getErrorMap:uo,makeIssue:fo,EMPTY_PATH:rg,addIssueToContext:U,ParseStatus:ct,INVALID:q,DIRTY:ur,OK:lt,isAborted:Zi,isDirty:Yi,isValid:Zn,isAsync:ns,get util(){return ge},get objectUtil(){return Vi},ZodParsedType:B,getParsedType:rn,ZodType:le,datetimeRegex:of,ZodString:Ut,ZodNumber:Sn,ZodBigInt:En,ZodBoolean:rs,ZodDate:Yn,ZodSymbol:ho,ZodUndefined:ss,ZodNull:os,ZodAny:wr,ZodUnknown:Bn,ZodNever:cn,ZodVoid:mo,ZodArray:Ft,ZodObject:Ue,ZodUnion:is,ZodDiscriminatedUnion:$o,ZodIntersection:as,ZodTuple:Xt,ZodRecord:cs,ZodMap:go,ZodSet:Qn,ZodFunction:gr,ZodLazy:ls,ZodLiteral:ds,ZodEnum:An,ZodNativeEnum:us,ZodPromise:kr,ZodEffects:Bt,ZodTransformer:Bt,ZodOptional:Zt,ZodNullable:Rn,ZodDefault:fs,ZodCatch:ps,ZodNaN:_o,BRAND:Ag,ZodBranded:Qa,ZodPipeline:As,ZodReadonly:hs,custom:cf,Schema:le,ZodSchema:le,late:Rg,get ZodFirstPartyTypeKind(){return Q},coerce:a_,any:jg,array:Lg,bigint:xg,boolean:uf,date:Cg,discriminatedUnion:Hg,effect:_l,enum:Xg,function:Zg,instanceof:Ig,intersection:Wg,lazy:Yg,literal:Qg,map:Kg,nan:Tg,nativeEnum:Jg,never:Dg,null:Mg,nullable:t_,number:df,object:Ug,oboolean:i_,onumber:o_,optional:e_,ostring:s_,pipeline:r_,preprocess:n_,promise:qg,record:zg,set:Vg,strictObject:Fg,string:lf,symbol:Og,transformer:_l,tuple:Gg,undefined:Pg,union:Bg,unknown:$g,void:Ng,NEVER:c_,ZodIssueCode:M,quotelessJson:tg,ZodError:kt});const bl=a.enum(["app_start","sign_in","window_focus","surface_open"]),ff=a.object({id:a.string().min(1),state:a.enum(["active","paused","disabled"])}).passthrough(),l_=a.object({tenant_id:a.string().min(1),tenant_name:a.string().optional(),eligible:a.boolean(),endpoint:ff.nullable()}).passthrough(),d_=a.object({code:a.string(),message:a.string(),details:a.record(a.unknown()).optional(),retry_after_seconds:a.number().optional()}).passthrough(),u_=a.object({code:a.string().min(1),count:a.number().int().nonnegative(),session:a.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),f_=a.object({in_force:a.boolean(),notice_pending:a.boolean().catch(!1)}).passthrough().optional().catch(void 0),Ix=a.object({capability:a.number(),consent_account_guard:a.boolean().optional(),state:a.enum(["ready","signed_out","unavailable","update_required"]),account_id:a.string().nullable(),tenant_id:a.string().nullable(),surface_state:a.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:a.object({settings:a.boolean(),inbox:a.boolean(),account_door:a.boolean(),onboarding:a.boolean()}),update_required:a.boolean(),local:a.object({enabled:a.boolean(),onboarding:a.string(),session:a.string()}),status:a.object({tenants:a.array(l_)}).passthrough().nullable(),consent:a.object({version:a.string().min(1).max(128),text:a.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:a.enum(["served","cached","embedded"])}).nullable(),error:d_.nullable(),state_note:a.string().nullable().optional(),read_only:a.boolean().optional(),trial_ended:a.object({tenant_id:a.string().min(1),trial_ended_at:a.string().min(1)}).passthrough().nullable().optional().catch(null),delivery_hold:u_,default_on:f_}).passthrough(),p_=a.object({version:a.string().min(1),consented_at:a.string().min(1),consented_via:a.string().min(1),current:a.boolean()}).passthrough(),Tx=a.object({endpoint:ff.extend({tenant_id:a.string().min(1),label:a.string().optional(),consent:p_.nullable().optional(),created_at:a.string().optional(),updated_at:a.string().optional()}).nullable(),settings:a.object({tenant_id:a.string().min(1),eligible:a.boolean(),consent_version:a.string().optional(),consent_required:a.boolean()}).passthrough(),default_on:a.boolean().optional().catch(void 0)}).passthrough(),h_=a.object({kind:a.enum(["endpoint","account"]).optional(),endpoint_id:a.string().min(1).optional(),account_id:a.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"),vl=a.object({direction:a.enum(["send","receive"]),effect:a.enum(["allow","deny"]),target:h_,id:a.string().optional()}).passthrough(),yl=a.object({mode:a.enum(["class_default","listed_only"]),allow:a.number(),deny:a.number()}).passthrough(),xx=a.object({allowlist:a.object({tenant_id:a.string().min(1),entries:a.array(vl)}).passthrough(),view:a.object({tenant_id:a.string().nullable(),entries:a.array(vl),directions:a.object({send:yl,receive:yl}),class_default:a.literal("cos_cos"),cues:a.object({allow_entry_switches_direction_to_listed_only:a.boolean(),listed_only_affects:a.string(),removing_allow_does_not_stop_open_thread:a.boolean(),deny_stops_pair_both_directions:a.boolean()}).passthrough()}).passthrough()}).passthrough(),Cx=a.object({onboarding:a.literal("seen")}).passthrough();function m_(e){return e?.default_on?.in_force===!0}function Ox(e,t){const n=g_(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function Px(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function Mx(e,t){if(!e||!t||m_(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 g_(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const __=8,Xi=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],b_=6*1024,v_=512;function bo(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const s=[];for(const o of n){if(s.length===v_)break;const c=new URLSearchParams({order_ids:o}).toString().length+1;if(r+c>b_)break;e.append("order_ids",o),s.push(o),r+=c}return s}function y_(e,t,n){return bo(new URLSearchParams(n),t,e)}const w_=/^\.+$/,k_=new RegExp("\\p{Cf}","u"),S_=/[/\\:]/,A=a.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),Ds=a.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),Ns=a.string().min(1).max(32768),E_=/^[a-f0-9]{12}$/,G=a.string().regex(E_),ri=a.string().regex(/^[a-f0-9]{12}$/),si=a.string().min(1).max(128),A_=a.string().min(1).max(4096),Or=a.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),oi=a.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),Ls=a.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),wl=a.string().regex(/^[a-f0-9]{32}$/),R_=/^(\/|[A-Za-z]:[\\/])/,ii=a.string().min(1).max(4096).regex(R_),kl=/^[a-f0-9]{32}$/,ue=a.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),Sl=a.string().min(1).max(512).nullish(),rr=a.string().regex(/^[A-Za-z0-9_-]{1,128}$/),Us=a.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),I_=["credential_finite_share","credential_inheritance"],El=/^sha256:[0-9a-f]{64}$/,Al={operation:a.enum(I_),requestDigest:a.string().regex(El),disclosureDigest:a.string().regex(El)},Pr=a.string().regex(/^la_[0-9a-f]{16}$/),Mr=a.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),Rl=a.object({data_b64:a.string().min(1).max(1e6),mime_type:a.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:a.string().max(4096).optional()}).strict(),T_=a.object({digest:a.string().regex(/^[0-9a-f]{32}$/),name:a.string().max(1024).optional(),mime_type:a.string().max(255).optional(),bytes:a.number().int().min(0).optional(),path:a.string().max(4096).optional()}).strict(),Il=2e5,Tl=8,x_=256,C_=100,xl=16,O_=256,P_=100,M_=200,j_=1e6,$_=a.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),tt=a.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),Fs=a.object({kind:a.enum(["agent","team"]),name:tt}).strict(),pf=a.enum(["claude","codex","omp"]),D_=a.record(a.string(),a.array(a.string().min(1).max(512)).max(5e3)),Cl={sources:a.array(pf).max(3).optional(),sessionIds:D_.optional(),all:a.boolean().optional(),includeSubagents:a.boolean().optional(),includeClearedSegments:a.boolean().optional(),includeMemory:a.boolean().optional(),includeInstructions:a.boolean().optional(),maxSessions:a.number().int().min(1).max(5e3).optional()},ai=a.object({provider:a.string().min(1).max(128),model_id:a.string().min(1).max(512),reasoning_effort:a.string().min(1).max(64).nullable(),fast_mode:a.boolean().nullable().optional()}).strict(),Ol=a.object({kind:a.enum(["role","specialist"]).optional(),description:a.string().max(8e3).optional(),instructions:a.string().max(8e3).optional(),tools:a.array(a.string().min(1).max(128)).max(256).optional(),effort:a.string().max(64).optional(),delegate:a.boolean().optional(),action_class:a.enum(["reactive","proactive"]).optional()}).strict(),Pl=a.object({name:a.string().min(1).max(64).optional(),description:a.string().max(8e3).optional(),manager:tt.optional(),members:a.array(a.object({role:tt,count:a.number().int().min(1).max(16),kind:a.enum(["agent","team"]),tier:a.enum(["lo","med","hi"]).nullable().optional(),effort:$_.nullable().optional()}).strict()).max(128).optional(),instructions:a.string().max(8e3).optional(),project:a.string().max(8e3).optional()}).strict(),N_=a.record(a.array(a.string().max(1024)).max(100)),ci=a.array(A).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),L_=a.array(a.object({kind:a.enum(["human","agent"]),account_id:A,endpoint_id:A.optional()}).strict()).max(50).refine(e=>new Set(e.map(t=>`${t.kind}:${t.account_id}:${t.endpoint_id??""}`)).size===e.length,"Duplicate mention"),Ml=a.enum(["minutes","hours","days"]);function U_(e){return!w_.test(e)}const jx=e=>to.safeParse(e).success,to=a.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(U_),jl=a.enum(["str","int","float","bool","list","dict"]),$l=a.string().max(16384),F_=2e3,Dl=a.string().min(1).max(F_),Nl=a.string().min(1).max(64),B_=a.string().min(1).max(64),H_=a.string().min(1).max(64),Ll=a.object({is_active:a.boolean().nullish(),one_time:a.boolean().nullish(),start_time_utc:a.string().max(64).nullish(),end_time_utc:a.string().max(64).nullish()}).strict(),W_=a.object({conversation_length:a.number().int().optional(),detail_length:a.number().int().optional(),max_learnings_history:a.number().int().optional(),hosting:a.string().max(256).optional(),model_name:a.string().max(1024).optional(),auto_save_conversation:a.boolean().optional()}).strict(),Ji=128,Ul=2e3,Fl=8e3,Bl=64,Hl=64,Do=e=>[...e].length,qi=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,G_=e=>e===9||e===10||e===11||e===12||e===13||e===133,z_=e=>e<=31||e>=127&&e<=159,K_=e=>k_.test(String.fromCodePoint(e)),V_=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,Bs=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},hf=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&qi(t[n].codePointAt(0)??0);)n++;for(;r>n&&qi(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},Z_=e=>{let t="",n=!1;for(const r of e){if(qi(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function Y_(e){const t=hf(e);if(!t)return"must not be empty";if(Do(t)>Ji)return`must be at most ${Ji} characters`;if(S_.test(t))return'must not contain "/", "\\" or ":"';if(Bs(t,V_))return"must not contain Unicode bidirectional override characters";if(Bs(t,G_))return"must not contain whitespace";if(Bs(t,z_))return"must not contain control characters";if(Bs(t,K_))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 $x(e){return Z_(hf(e).normalize("NFKC").toLowerCase())}function Q_(e){return e.trim()?Do(e)>Ul?`must be at most ${Ul} characters`:null:"must not be empty"}function X_(e){return e.trim()?Do(e)>Fl?`must be at most ${Fl} characters`:null:"must not be empty"}function J_(e){if(e.length>Hl)return`must hold at most ${Hl} items`;for(const t of e)if(!t.trim()||Do(t)>Bl)return`must hold items of 1 to ${Bl} characters`;return null}const q_=e=>Y_(e)===null,eb=a.string().refine(q_,{message:"That is not a name the hub can publish."}),tb=a.string().refine(e=>X_(e)===null,{message:"That instruction body cannot be published."}),nb=a.string().refine(e=>Q_(e)===null,{message:"That description cannot be published."}),rb=a.array(a.string()).refine(e=>J_(e)===null,{message:"That tool list cannot be published."}),li={requestId:ue.optional(),subscribe:a.boolean().optional(),autoPush:a.boolean().optional(),confirmPublicEgress:a.boolean().optional()},Wl=a.object({name:eb,description:nb,instructions:tb,kind:a.enum(["role","specialist"]),when_to_use:a.string(),tools:rb,effort:a.string(),delegate:a.boolean(),version:a.string(),categories:a.array(a.string()),tags:a.array(a.string())}).partial().strict(),sb=a.enum(["team","agent"]),ob=a.string().min(1).max(64),ib=a.string().min(1).max(256),mf=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,di=a.string().regex(mf,{message:"Letters, digits, dot, underscore and dash; no spaces."}),ab=["planning","active","qa","validation","done","paused","archived"],Gl=a.enum(ab),Hs=a.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),zl=a.array(a.string().min(1).max(24)).max(8),gn=a.string().min(1).max(64),cb=1e3,Kl=240,Vl=80,lb=256,db=100,ub=200,fb=/^[a-z0-9][a-z0-9_-]{0,23}$/;function Dx(e){return e?mf.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 Nx(e){return fb.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const Ws=a.enum(["agent","team","skill"]),ui=a.string().min(1).max(128).regex(/\S/),Zl=a.enum(Xi),pb=a.object({visible:a.array(Zl).max(Xi.length),more:a.array(Zl).max(Xi.length)}).strict(),sn=a.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),Yl=a.object({selectionToken:a.string().min(1).max(512),reconcileIds:a.array(sn).max(500).optional(),excludedIds:a.array(sn).max(500).optional()}).strict(),hb=a.object({operationToken:a.string().min(1).max(512),reconcileIds:a.array(sn).max(500).optional()}).strict(),Ql=a.union([a.object({throughSeq:a.number().int().min(0).optional(),receipt:a.literal(!0).optional(),reconcileIds:a.array(sn).max(500).optional(),items:a.array(a.object({id:sn,revision:a.number().int().min(1)}).strict()).min(1).max(500)}).strict(),a.object({sessionId:G,throughSeq:a.number().int().min(0),observed:a.array(a.object({id:sn,revision:a.number().int().min(1)}).strict()).max(500)}).strict(),a.object({all:a.literal(!0),throughSeq:a.number().int().min(0),observed:a.array(a.object({id:sn,revision:a.number().int().min(1)}).strict()).max(500)}).strict()]),mb={pointer:"pointerdown",key:"keydown",wheel:"wheel"},gb=a.discriminatedUnion("op",[a.object({op:a.literal("capabilities")}).strict(),a.object({op:a.literal("runtimes.list")}).strict(),a.object({op:a.literal("profiles.list")}).strict(),a.object({op:a.literal("profiles.get"),name:tt}).strict(),a.object({op:a.literal("imports.sources")}).strict(),a.object({op:a.literal("imports.sessions"),source:pf,includeSubagents:a.boolean().optional()}).strict(),a.object({op:a.literal("imports.preview"),...Cl}).strict(),a.object({op:a.literal("imports.start"),...Cl}).strict(),a.object({op:a.literal("imports.status"),jobId:a.string().min(1).max(128)}).strict(),a.object({op:a.literal("imports.cancel"),jobId:a.string().min(1).max(128)}).strict(),a.object({op:a.literal("profiles.update"),name:tt,requestId:ue,fields:Ol,expectedDefinitionRevision:Sl.optional()}).strict(),a.object({op:a.literal("profiles.install"),name:tt,requestId:ue}).strict(),a.object({op:a.literal("profiles.create"),name:tt,requestId:ue,fields:Ol.extend({description:a.string().max(8e3),instructions:a.string().min(1).max(8e3)})}).strict(),a.object({op:a.literal("hub.updates")}).strict(),a.object({op:a.literal("hub.skillPull"),requestId:ue,hubId:A,hubSource:a.string().min(1).max(2048),visibility:a.enum(["public","org"]),tenantId:A.nullable(),localAlias:tt,subscribe:a.boolean().optional(),autoPush:a.boolean().optional(),confirmPublicEgress:a.boolean().optional(),dryRun:a.boolean().optional(),adoptionStrategy:a.enum(["merge","keep-local","take-hub"]).optional(),allowLlm:a.boolean().optional(),confirm:a.boolean().optional(),adoptionReceipt:a.string().min(16).max(128).optional()}).strict(),a.object({op:a.literal("hub.skillSubscribe"),requestId:ue,hubId:A,hubSource:a.string().min(1).max(2048),visibility:a.enum(["public","org"]),tenantId:A.nullable(),localAlias:tt}).strict(),a.object({op:a.literal("hub.skillUnpull"),requestId:ue,linkId:a.string().min(1).max(256)}).strict(),a.object({op:a.literal("hub.skillPublish"),requestId:ue,dryRun:a.boolean(),sourceSkill:tt,localAlias:tt,visibility:a.enum(["public","org"]),tenantId:A.nullable(),subscribe:a.boolean(),autoPush:a.boolean(),confirmPublicEgress:a.boolean(),previewReceipt:a.string().min(1).max(4096).optional(),confirmPublish:a.literal(!0).optional()}).strict(),a.object({op:a.literal("hub.links"),kind:a.enum(["agent","team","skill"]).optional()}).strict(),a.object({op:a.literal("hub.policy"),requestId:ue,linkId:a.string().min(1).max(256),expectedPolicyRevision:a.string().min(1).max(256),subscribe:a.boolean().optional(),autoPush:a.boolean().optional(),confirmPublicEgress:a.boolean().optional()}).strict(),a.object({op:a.literal("hub.check"),requestId:ue,kind:Ws.optional(),name:tt.optional(),localId:ui.optional()}).strict(),a.object({op:a.literal("hub.apply"),requestId:ue,kind:Ws.optional(),name:tt.optional(),localId:ui.optional(),prefer:a.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:a.boolean().optional(),dryRun:a.boolean().optional(),resolveSource:a.literal(!0).optional(),hubSource:a.string().min(1).max(2048).optional(),visibility:a.enum(["public","org"]).optional(),tenantId:a.string().min(1).max(128).nullable().optional()}).strict(),a.object({op:a.literal("hub.applyAll"),requestId:ue,kind:Ws.optional()}).strict(),a.object({op:a.literal("hub.retry"),requestId:ue,kind:Ws.optional(),name:tt.optional(),localId:ui.optional()}).strict(),a.object({op:a.literal("hub.push"),requestId:ue,linkId:a.string().min(1).max(256),direction:a.literal("push"),dryRun:a.boolean(),previewReceipt:a.string().min(1).max(4096).optional(),confirmPublish:a.literal(!0).optional()}).strict(),a.object({op:a.literal("teams.list")}).strict(),a.object({op:a.literal("teams.get"),name:tt}).strict(),a.object({op:a.literal("teams.effective"),name:tt}).strict(),a.object({op:a.literal("teams.update"),name:tt,requestId:ue,fields:Pl,expectedDefinitionRevision:Sl.optional()}).strict(),a.object({op:a.literal("teams.create"),requestId:ue,fields:Pl.extend({name:a.string().min(1).max(64)})}).strict(),a.object({op:a.literal("sessions.list"),limit:a.number().int().min(1).max(500).optional(),include_archived:a.boolean().optional(),include_peers:a.boolean().optional(),scope_kind:sb.optional(),scope_name:ob.optional(),cursor:ib.optional(),with_counts:a.boolean().optional(),sort:a.literal("activity").optional()}).strict(),a.object({op:a.literal("delegated_cleanup_notice.ack")}).strict(),a.object({op:a.literal("sessions.search"),q:a.string().min(1).max(x_),limit:a.number().int().min(1).max(500).optional(),include_archived:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.archive"),sessionId:G,archived:a.boolean()}).strict(),a.object({op:a.literal("sessions.delete"),sessionId:G,confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.create"),requestId:ue,cwd:a.string().min(1).max(4096).optional(),target:Fs.optional(),purpose:a.literal("agents-config").optional(),model:ai.optional(),draftId:G.optional(),peer:rr.optional()}).strict(),a.object({op:a.literal("sessions.preview"),requestId:ue,cwd:a.string().min(1).max(4096),target:Fs.optional(),model:ai.optional()}).strict(),a.object({op:a.literal("sessions.draft"),requestId:ue,cwd:a.string().min(1).max(4096),target:Fs.optional(),model:ai.optional()}).strict(),a.object({op:a.literal("sessions.get"),sessionId:G,journalOrder:a.boolean().optional(),orderIds:a.array(a.string().min(1).max(128)).max(512).optional(),peerJournalSource:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.files"),sessionId:G,scope:a.enum(["family","self"]).optional(),kind:a.string().max(256).optional(),q:a.string().max(256).optional(),sort:a.enum(["recent","name","kind","modified","created","size"]).optional(),order:a.enum(["asc","desc"]).optional(),limit:a.number().int().min(1).max(200).optional(),cursor:a.string().max(8192).optional()}).strict(),a.object({op:a.literal("sessions.files.materialise"),sessionId:G,fileId:a.string().regex(/^[a-f0-9]{16}$/)}).strict(),a.object({op:a.literal("sessions.userAttachments"),sessionId:G}).strict(),a.object({op:a.literal("sessions.userAttachments.materialise"),sessionId:G,digest:a.string().regex(/^[a-f0-9]{32}$/)}).strict(),a.object({op:a.literal("sessions.history"),sessionId:G,beforeId:A.optional(),limit:a.number().int().min(1).max(500).optional(),openFrame:a.boolean().optional(),journalOrder:a.boolean().optional(),orderIds:a.array(a.string().min(1).max(128)).max(512).optional(),peerJournalSource:a.boolean().optional(),sourceRead:a.enum(["metadata","payload"]).optional(),expectedJournalGeneration:a.string().min(1).max(128).optional()}).strict(),a.object({op:a.literal("sessions.checkpoints"),sessionId:G}).strict(),a.object({op:a.literal("sessions.checkpoints.warm"),sessionId:G,ids:a.array(A).max(xl).optional(),limit:a.number().int().min(1).max(xl).optional()}).strict(),a.object({op:a.literal("sessions.find"),sessionId:G,q:a.string().min(1).max(O_),limit:a.number().int().min(1).max(M_).optional()}).strict(),a.object({op:a.literal("subagents.transcript"),sessionId:G,childId:G,beforeId:A.optional(),limit:a.number().int().min(1).max(500).optional()}).strict(),a.object({op:a.literal("sessions.message"),sessionId:G,requestId:ue,text:a.string().max(Il),images:a.array(Rl).max(Tl).optional(),files:a.array(T_).max(__).optional(),mode:a.enum(["prompt","steer"]).optional(),inputMode:a.enum(["typed","dictated","mixed"]).optional(),inputPath:a.string().max(1024).optional()}).strict(),a.object({op:a.literal("sessions.command"),sessionId:G,requestId:ue,command:a.string().regex(/^\/?[A-Za-z]+$/).max(64),args:a.string().max(Il).optional(),images:a.array(Rl).max(Tl).optional()}).strict(),a.object({op:a.literal("sessions.move"),sessionId:G,requestId:ue,cwd:a.string().min(1).max(4096)}).strict(),a.object({op:a.literal("sessions.answer"),sessionId:G,epoch:A.optional(),requestId:A.optional(),value:a.string().max(32768).optional(),approved:a.boolean().optional(),questionIndex:a.number().int().min(0).optional(),askId:A.optional(),answers:a.record(a.string(),a.array(a.string().max(32768))).optional(),decline:a.boolean().optional(),revise:a.boolean().optional(),dismiss:a.boolean().optional(),reason:a.enum(["answered_in_chat","moot"]).optional()}).strict(),a.object({op:a.literal("sessions.seen"),sessionId:G,completionToken:a.string().uuid()}).strict(),a.object({op:a.literal("attention.seen"),items:a.array(a.object({sessionId:G,completionToken:a.string().uuid()}).strict()).min(1).max(500)}).strict(),a.object({op:a.literal("sessions.notified"),sessionId:G,completionToken:a.string().uuid()}).strict(),a.object({op:a.literal("tags.list")}).strict(),a.object({op:a.literal("tags.replace"),tags:a.array(a.object({id:a.string().optional(),name:a.string()}).strict())}).strict(),a.object({op:a.literal("sessions.tags"),expected_revision:a.string().optional(),sessionId:G,tags:a.array(a.string()),primary:a.string().nullable()}).strict(),a.object({op:a.literal("sessions.pin"),sessionId:G,pinned:a.boolean()}).strict(),a.object({op:a.literal("sessions.watch"),sessionId:G,subscriptionId:a.string().regex(kl),visible:a.boolean(),canNotify:a.boolean()}).strict(),a.object({op:a.literal("sessions.warm"),sessionId:G}).strict(),a.object({op:a.literal("sessions.interrupt"),sessionId:G,requestId:ue}).strict(),a.object({op:a.literal("supplements.cancel"),sessionId:G,job:ri,anchor:si}).strict(),a.object({op:a.literal("supplements.restart"),sessionId:G,job:ri,anchor:si}).strict(),a.object({op:a.literal("supplements.steer"),sessionId:G,job:ri,anchor:si,text:a.string().min(1).max(500)}).strict(),a.object({op:a.literal("sessions.variables.list"),sessionId:G}).strict(),a.object({op:a.literal("sessions.variables.create"),sessionId:G,key:to,value:$l,type:jl}).strict(),a.object({op:a.literal("sessions.variables.update"),sessionId:G,key:to,value:$l,type:jl}).strict(),a.object({op:a.literal("sessions.variables.delete"),sessionId:G,key:to}).strict(),a.object({op:a.literal("sessions.presence"),subscriptionId:a.string().regex(/^[a-f0-9]{1,64}$/),canNotify:a.boolean(),canNotifyKinds:a.array(a.enum(["complete","error"])).max(4),sessionId:a.string().regex(/^([a-f0-9]{12})?$/),window:a.object({exists:a.boolean(),focused:a.boolean(),visible:a.boolean(),minimized:a.boolean()}).strict()}).strict(),a.object({op:a.literal("legacy.models"),provider:a.string().max(128).optional(),sort:a.enum(["id","name","provider","recommended"]).optional(),direction:a.enum(["ascending","descending"]).optional()}).strict(),a.object({op:a.literal("legacy.models.providers")}).strict(),a.object({op:a.literal("auth.probe"),provider:A}).strict(),a.object({op:a.literal("legacy.agent.upload"),agentId:A}).strict(),a.object({op:a.literal("agent.publish"),agentId:A,document:Wl.optional(),...li,visibility:a.literal("org").optional(),tenantId:A.optional()}).strict(),a.object({op:a.literal("agent.republish"),agentId:A,hubAgentId:A,expectedRemoteRevision:a.string().min(1).max(512).optional(),document:Wl.optional(),...li,visibility:a.literal("org").optional(),tenantId:A.optional()}).strict(),a.object({op:a.literal("team.publish"),teamId:A,...li,visibility:a.literal("org").optional(),tenantId:A.optional()}).strict(),a.object({op:a.literal("team.pull"),teamId:A,tenantId:A.optional()}).strict(),a.object({op:a.literal("agent.nameAvailability"),name:a.string().min(1).max(Ji)}).strict(),a.object({op:a.literal("legacy.agents.list"),page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(500).optional(),name:a.string().max(256).optional(),sort:a.string().max(64).optional(),direction:a.enum(["asc","desc"]).optional()}).strict(),a.object({op:a.literal("legacy.agent.get"),agentId:A}).strict(),a.object({op:a.literal("legacy.agent.history"),agentId:A,page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(500).optional()}).strict(),a.object({op:a.literal("legacy.jobs.list"),agentId:A.optional(),status:a.string().max(64).optional()}).strict(),a.object({op:a.literal("legacy.job.get"),jobId:A}).strict(),a.object({op:a.literal("legacy.schedules.list"),page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(100).optional()}).strict(),a.object({op:a.literal("legacy.agent.schedules.list"),agentId:A,page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(100).optional()}).strict(),a.object({op:a.literal("legacy.agent.schedule.create"),agentId:A,schedule:Ll.extend({prompt:a.string().max(64e3),interval:a.number().int().min(1),unit:Ml})}).strict(),a.object({op:a.literal("legacy.schedule.get"),scheduleId:A}).strict(),a.object({op:a.literal("legacy.schedule.edit"),scheduleId:A,schedule:Ll.extend({prompt:a.string().max(64e3).nullish(),interval:a.number().int().min(1).nullish(),unit:Ml.nullish()})}).strict(),a.object({op:a.literal("legacy.schedule.remove"),scheduleId:A}).strict(),a.object({op:a.literal("legacy.agent.create"),agent:a.record(a.unknown())}).strict(),a.object({op:a.literal("legacy.agent.update"),agentId:A,update:a.record(a.unknown())}).strict(),a.object({op:a.literal("legacy.agent.delete"),agentId:A}).strict(),a.object({op:a.literal("legacy.agent.conversation.clear"),agentId:A}).strict(),a.object({op:a.literal("legacy.agent.systemPrompt.get"),agentId:A}).strict(),a.object({op:a.literal("legacy.agent.systemPrompt.update"),agentId:A,systemPrompt:a.string().max(j_)}).strict(),a.object({op:a.literal("legacy.agent.download"),agentId:A}).strict(),a.object({op:a.literal("legacy.job.cancel"),jobId:A}).strict(),a.object({op:a.literal("commands.list")}).strict(),a.object({op:a.literal("commands.entities"),sessionId:G,command:A,name:a.string().max(128).optional()}).strict(),a.object({op:a.literal("models.catalogue"),live:a.boolean().optional(),scope:a.enum(["usable","all"]).optional()}).strict(),a.object({op:a.literal("usage.get"),provider:A.optional(),live:a.boolean().optional(),refresh:a.boolean().optional()}).strict(),a.object({op:a.literal("quota.notice"),provider:A.optional(),model:a.string().min(1).max(200).optional(),refresh:a.boolean().optional()}).strict(),a.object({op:a.literal("analytics.get"),sessionId:G.optional(),sinceMs:a.number().int().nonnegative().optional(),untilMs:a.number().int().nonnegative().optional(),days:a.number().int().min(1).max(366).optional()}).strict(),a.object({op:a.literal("analytics.models"),sessionId:G.optional(),sinceMs:a.number().int().nonnegative().optional(),untilMs:a.number().int().nonnegative().optional(),days:a.number().int().min(1).max(366).optional()}).strict(),a.object({op:a.literal("info.get")}).strict(),a.object({op:a.literal("sessions.report"),sessionId:G,recentLimit:a.number().int().min(0).max(50).optional()}).strict(),a.object({op:a.literal("skills.list"),sessionId:G.optional(),cwd:A_.optional(),name:Or.optional()}).strict(),a.object({op:a.literal("skills.create"),requestId:ue,name:Or,copyFrom:Or}).strict(),a.object({op:a.literal("skills.update"),requestId:ue,name:Or,expectedFingerprint:a.string().regex(/^[a-f0-9]{64}$/),files:a.array(a.object({path:a.string().min(1).max(240),content:a.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),a.object({op:a.literal("skills.remove"),requestId:ue,name:Or,discardLocalChanges:a.boolean()}).strict(),a.object({op:a.literal("sessions.failovers"),sessionId:G}).strict(),a.object({op:a.literal("sessions.credential"),sessionId:G,action:a.enum(["list","store","forget"]),key:Ds.optional(),value:Ns.optional(),confirmed:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.fork"),sessionId:G,requestId:ue,message:a.string().max(2e5).optional(),boundary:a.enum(["next_safe","at_entry"]).optional(),entryId:a.string().max(128).optional(),autoTag:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.stop"),requestId:ue,targets:a.array(G).min(1).max(100),confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.aside"),sessionId:G,requestId:ue,text:a.string().min(1).max(32768),asideId:ue.optional(),subscriptionId:a.string().regex(kl).optional()}).strict(),a.object({op:a.literal("sessions.adopt"),sessionId:G,requestId:ue,asideId:ue,confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.aside.get"),sessionId:G,asideId:ue}).strict(),a.object({op:a.literal("sessions.aside.close"),sessionId:G,asideId:ue}).strict(),a.object({op:a.literal("wakes.list"),limit:a.number().int().min(1).max(500).optional(),includeDormant:a.boolean().optional()}).strict(),a.object({op:a.literal("wakes.create"),requestId:ue,sessionId:G.optional(),cwd:a.string().min(1).max(4096).optional(),target:Fs.optional(),message:Dl,in:a.string().min(1).max(64).optional(),at:a.string().min(1).max(64).optional(),every:a.string().min(1).max(64).optional(),until:a.string().min(1).max(64).optional(),limit:a.number().int().min(1).optional(),title:a.string().min(1).max(200).optional()}).strict(),a.object({op:a.literal("wakes.edit"),sessionId:G,wakeId:Nl,message:Dl.optional(),in:a.string().min(1).max(64).optional(),at:a.string().min(1).max(64).optional(),every:a.string().min(1).max(64).optional(),until:a.string().min(1).max(64).optional(),limit:a.number().int().min(1).optional()}).strict(),a.object({op:a.literal("wakes.remove"),sessionId:G,wakeId:Nl}).strict(),a.object({op:a.literal("monitors.cancel"),sessionId:G,monitorId:B_}).strict(),a.object({op:a.literal("jobs.cancel"),sessionId:G,jobId:H_}).strict(),a.object({op:a.literal("mcp.list"),sessionId:G}).strict(),a.object({op:a.literal("mcp.credentials.store"),sessionId:G,name:a.string().min(1).max(256),values:a.record(a.string().min(1).max(128),a.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:a.array(a.string().min(1).max(128)).max(32)}).strict(),a.object({op:a.literal("mcp.control"),sessionId:G,control:a.object({action:a.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:oi.optional(),scope:a.enum(["global","project"]).optional(),command:a.string().min(1).max(4096).optional(),args:a.array(a.string().max(8192)).max(128).optional(),env:a.record(Ls).optional(),url:a.string().max(4096).optional(),headers:a.record(Ls).optional(),oauth:a.boolean().optional(),confirmed:a.boolean().optional(),operation_id:wl.optional()}).strict()}).strict(),a.object({op:a.literal("mcp.catalog"),cwd:ii.optional(),sessionId:G.optional()}).strict(),a.object({op:a.literal("mcp.catalog.control"),cwd:ii.optional(),control:a.object({action:a.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:oi.optional(),scope:a.enum(["global","project"]).optional(),command:a.string().min(1).max(4096).optional(),args:a.array(a.string().max(8192)).max(128).optional(),env:a.record(Ls).optional(),url:a.string().max(4096).optional(),headers:a.record(Ls).optional(),confirmed:a.boolean().optional(),operation_id:wl.optional()}).strict()}).strict(),a.object({op:a.literal("mcp.catalog.credentials"),header:a.string().min(1).max(128).optional(),cwd:ii.optional(),name:oi,values:a.record(a.string().min(1).max(128),a.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:a.array(a.string().min(1).max(128)).max(32)}).strict(),a.object({op:a.literal("radient.request"),control:a.object({operation:a.enum(["account","prices","credits","usage","provision","application.create","agents.list","agents.get","agents.create","agents.update","agents.delete","agents.like","agents.unlike","agents.liked","agents.like_count","agents.favourite","agents.unfavourite","agents.favourited","agents.favourite_count","agents.download_count","agents.statuses","comments.list","comments.create","comments.update","comments.delete","account.agents","memberships.list","org_agents.list","org_team.get","org_teams.list","org_skills.list","org_skill.get","signup.resend","team_trial.eligibility","team_trial.start","team_trial.status"]),request_id:ue.optional(),tenant_id:A.optional(),account_id:A.optional(),agent_id:A.optional(),comment_id:A.optional(),team_id:A.optional(),skill_id:A.optional(),query:a.record(a.union([a.string().max(1024),a.number().int()])).optional(),payload:a.record(a.unknown()).optional(),confirmed:a.boolean().optional()}).strict()}).strict(),a.object({op:a.literal("providers.list")}).strict(),a.object({op:a.literal("accounts.list")}).strict(),a.object({op:a.literal("accounts.remove"),accountId:a.number().int().positive(),confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("tunnel.setup.read"),credentialId:a.number().int().positive().optional()}).strict(),a.object({op:a.literal("tunnel.setup.plan"),credentialId:a.number().int().positive().optional()}).strict(),a.object({op:a.literal("tunnel.setup.run"),credentialId:a.number().int().positive(),acceptMonthlyPrice:a.string().min(1).max(64).optional()}).strict(),a.object({op:a.literal("auth.start"),provider:A}).strict(),a.object({op:a.literal("auth.status"),id:A}).strict(),a.object({op:a.literal("auth.input"),id:A,promptId:A,value:Ns}).strict(),a.object({op:a.literal("auth.cancel"),id:A}).strict(),a.object({op:a.literal("auth.key"),provider:A,value:Ns}).strict(),a.object({op:a.literal("auth.logout"),provider:A}).strict(),a.object({op:a.literal("agent_messages.status"),boundary:bl}).strict(),a.object({op:a.literal("agent_messages.enable"),expected_account_id:A,tenant_id:A,state:a.literal("active"),consent_version:a.string().min(1).max(128),consented_via:a.literal("dialog")}).strict(),a.object({op:a.literal("agent_messages.settings"),tenant_id:A.optional()}).strict(),a.object({op:a.literal("agent_messages.settings.put"),expected_account_id:A,tenant_id:A.optional(),consent_version:a.string().min(1).max(128).optional(),consented_via:a.enum(["dialog","settings"]).optional(),label:a.string().min(1).max(128).optional(),state:a.enum(["active","paused","disabled"])}).strict(),a.object({op:a.literal("agent_messages.onboarding.dismiss")}).strict(),a.object({op:a.literal("agent_messages.allowlist.get"),tenant_id:A.optional()}).strict(),a.object({op:a.literal("agent_messages.allowlist.put"),expected_account_id:A,tenant_id:A.optional(),entries:a.array(a.object({direction:a.enum(["send","receive"]),effect:a.enum(["allow","deny"]),target:a.object({endpoint_id:A.optional(),account_id:A.optional()}).strict().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id")}).strict()).max(200)}).strict(),a.object({op:a.literal("team_bridge.conversations.list"),scope:a.literal("account").optional(),tenant_id:A.optional(),limit:a.number().int().min(1).max(100).optional(),cursor:a.string().min(1).max(512).optional(),before:a.string().min(1).max(64).optional(),status:a.enum(["open","archived"]).optional()}).strict(),a.object({op:a.literal("team_bridge.conversations.get"),conversation_id:A,tenant_id:A.optional()}).strict(),a.object({op:a.literal("team_bridge.conversations.create"),expected_account_id:A.optional(),tenant_id:A.optional(),kind:a.enum(["dm","group","channel"]),name:a.string().min(1).max(128).optional(),topic:a.string().min(1).max(512).optional(),visibility:a.enum(["private","tenant"]).optional(),agent_capable:a.boolean().optional(),members:a.array(a.object({account_id:A,kind:a.enum(["human","agent"]),endpoint_id:A.optional(),display_label:a.string().min(1).max(64)}).strict()).max(500)}).strict(),a.object({op:a.literal("team_bridge.conversations.lifecycle"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A,action:a.enum(["archive","unarchive","join","leave"])}).strict(),a.object({op:a.literal("team_bridge.conversations.join"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional()}).strict(),a.object({op:a.literal("team_bridge.conversations.leave"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional()}).strict(),a.object({op:a.literal("team_bridge.conversations.notify"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),notify:a.enum(["all","mention","mute"])}).strict(),a.object({op:a.literal("team_bridge.conversations.agent_notify"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),notify:a.enum(["all","mention","mute"])}).strict(),a.object({op:a.literal("team_bridge.conversations.members.add"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),members:a.array(a.object({account_id:A,kind:a.enum(["human","agent"]),endpoint_id:A.optional(),display_label:a.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),a.object({op:a.literal("team_bridge.conversations.members.remove"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A,account_id:A}).strict(),a.object({op:a.literal("team_bridge.conversations.delete"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A}).strict(),a.object({op:a.literal("team_bridge.conversations.consent"),expected_account_id:A.optional(),conversation_id:A,account_id:A,decision:a.enum(["accept","decline","withdraw"]),consent_version:a.string().min(1).max(128).optional(),endpoint_id:A.optional(),tenant_id:A.optional()}).strict(),a.object({op:a.literal("team_bridge.owner_audit.conversations"),expected_account_id:A,tenant_id:A,limit:a.number().int().min(1).max(100).optional(),cursor:a.string().min(1).optional()}).strict(),a.object({op:a.literal("team_bridge.owner_audit.messages"),expected_account_id:A,tenant_id:A,conversation_id:A,limit:a.number().int().min(1).max(100).optional(),before_seq:a.number().int().nonnegative().optional()}).strict(),a.object({op:a.literal("team_bridge.owner_audit.replies"),expected_account_id:A,tenant_id:A,conversation_id:A,message_id:A,limit:a.number().int().min(1).max(100).optional(),after_seq:a.number().int().nonnegative().optional(),before_seq:a.number().int().positive().optional(),order:a.enum(["asc","desc"]).optional()}).strict(),a.object({op:a.literal("team_bridge.messages.list"),conversation_id:A,tenant_id:A.optional(),limit:a.number().int().min(1).max(100).optional(),before_seq:a.number().int().nonnegative().optional(),endpoint_id:A.optional()}).strict(),a.object({op:a.literal("team_bridge.reactions.toggle"),conversation_id:A,message_id:A,expected_account_id:A,tenant_id:A,emoji:a.string().min(1),active:a.boolean()}).strict(),a.object({op:a.literal("team_bridge.messages.send"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),client_ref:A,body:a.string(),agent_label:a.string().min(1).max(64).optional(),thread_root_id:A.optional(),attachment_ids:ci.optional(),mentions:L_.optional()}).strict(),a.object({op:a.literal("team_bridge.messages.replies"),conversation_id:A,message_id:A,expected_account_id:A,tenant_id:A,limit:a.number().int().min(1).max(100).optional(),after_seq:a.number().int().nonnegative().optional(),before_seq:a.number().int().positive().optional(),order:a.enum(["asc","desc"]).optional()}).strict(),a.object({op:a.literal("team_bridge.scheduled.list"),tenant_id:A}).strict(),a.object({op:a.literal("team_bridge.scheduled.create"),tenant_id:A,conversation_id:A,client_ref:A,body:a.string(),send_at:a.string().datetime({offset:!0}),attachment_ids:ci.optional(),thread_root_id:A.optional()}).strict(),a.object({op:a.literal("team_bridge.scheduled.update"),tenant_id:A,scheduled_id:A,body:a.string().optional(),send_at:a.string().datetime({offset:!0}).optional(),attachment_ids:ci.optional(),expected_version:a.number().int().nonnegative().optional()}).strict(),a.object({op:a.literal("team_bridge.attachments.delete"),tenant_id:A,conversation_id:A,attachment_id:A,expected_account_id:A}).strict(),a.object({op:a.literal("team_bridge.scheduled.cancel"),tenant_id:A,scheduled_id:A}).strict(),a.object({op:a.literal("team_bridge.read"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),seq:a.number().int().nonnegative().optional(),muted:a.boolean().optional()}).strict(),a.object({op:a.literal("team_bridge.thread_read"),expected_account_id:A,conversation_id:A,message_id:A,tenant_id:A,seq:a.number().int().nonnegative()}).strict(),a.object({op:a.literal("team_bridge.unread"),scope:a.literal("account").optional(),tenant_id:A.optional()}).strict(),a.object({op:a.literal("team_bridge.directory"),tenant_id:A}).strict(),a.object({op:a.literal("team_bridge.status"),boundary:bl.optional()}).strict(),a.object({op:a.literal("settings.list")}).strict(),a.object({op:a.literal("settings.edit"),key:Ds,value:a.unknown().refine(e=>e!==void 0,"A setting value is required."),base:N_.optional()}).strict(),a.object({op:a.literal("settings.reset"),key:Ds}).strict(),a.object({op:a.literal("tts.paths")}).strict(),a.object({op:a.literal("config.get")}).strict(),a.object({op:a.literal("config.update"),value:W_}).strict(),a.object({op:a.literal("instructions.get")}).strict(),a.object({op:a.literal("instructions.update"),content:a.string().max(64e3)}).strict(),a.object({op:a.literal("credentials.list")}).strict(),a.object({op:a.literal("credentials.update"),key:Ds,value:Ns}).strict(),a.object({op:a.literal("peers.list")}).strict(),a.object({op:a.literal("networks.list")}).strict(),a.object({op:a.literal("networks.invite"),networkId:rr,role:a.enum(["read","drive","admin"]),deviceId:rr.optional()}).strict(),a.object({op:a.literal("networks.member.remove"),networkId:rr,deviceId:rr,confirm:a.string().min(1).max(256)}).strict(),a.object({op:a.literal("sessions.transfer"),sessionId:G,to:a.union([a.literal("local"),rr]),keep:a.boolean().optional(),waitS:a.number().min(0).max(300).optional(),requestId:ue.optional()}).strict(),a.object({op:a.literal("approvals.list")}).strict(),a.object({op:a.literal("approvals.approve"),approvalId:Us}).strict(),a.object({op:a.literal("approvals.deny"),approvalId:Us}).strict(),a.object({op:a.literal("approvals.approveCredential"),approvalId:Us,...Al}).strict(),a.object({op:a.literal("approvals.applyCredential"),approvalId:Us,...Al}).strict(),a.object({op:a.literal("asks.list")}).strict(),a.object({op:a.literal("projects.list")}).strict(),a.object({op:a.literal("projects.get"),key:gn}).strict(),a.object({op:a.literal("projects.create"),name:di,description:a.string().max(Kl).optional(),status:Gl.optional(),tags:zl.optional()}).strict(),a.object({op:a.literal("projects.update"),key:gn,fields:a.object({name:di.optional(),title:a.string().max(80).optional(),owner:a.string().max(80).optional(),team:a.string().max(80).optional(),description:a.string().max(Kl).optional(),status:Gl.optional(),progress:a.string().max(cb).optional(),tags:zl.optional(),start_date:Hs.optional(),target_date:Hs.optional(),completed_at:Hs.optional(),estimate:a.number().positive().max(1e3).optional(),estimate_unit:a.enum(["points","days"]).optional()}).strict(),force_done:a.boolean().optional()}).strict(),a.object({op:a.literal("projects.delete"),key:gn,confirmed_name:di}).strict(),a.object({op:a.literal("projects.link"),key:gn,sessionId:G}).strict(),a.object({op:a.literal("projects.unlink"),key:gn,sessionId:G}).strict(),a.object({op:a.literal("projects.milestone"),key:gn,name:a.string().min(1).max(Vl),targetDate:Hs.optional(),completed:a.boolean().optional()}).strict(),a.object({op:a.literal("projects.milestone.remove"),key:gn,name:a.string().min(1).max(Vl)}).strict(),a.object({op:a.literal("projects.request_update"),key:gn}).strict(),a.object({op:a.literal("projects.search"),q:a.string().min(1).max(lb),limit:a.number().int().min(1).max(ub).optional()}).strict(),a.object({op:a.literal("aida.status")}).strict(),a.object({op:a.literal("aida.control"),action:a.enum(["open","pause","resume","greet","status"])}).strict(),a.object({op:a.literal("code_requests.list"),sessionId:G}).strict(),a.object({op:a.literal("code_requests.refresh"),sessionId:G,keys:a.array(a.string().min(1).max(512)).max(256).optional(),force:a.boolean().optional()}).strict(),a.object({op:a.literal("static.sign"),route:a.enum(["images","videos","audio","html"]),path:a.string().min(1),ttlS:a.number().int().min(1).max(3600).optional()}).strict(),a.object({op:a.literal("library.list"),scope:a.enum(["final","all"]).optional(),q:a.string().max(512).optional(),category:a.string().min(1).max(64).optional(),kind:a.string().min(1).max(64).optional(),origin_group:a.enum(["generated","created","mentioned"]).optional(),origin:a.string().min(1).max(64).optional(),tag:a.string().min(1).max(128).optional(),tag_mode:a.enum(["all","any"]).optional(),highlighted:a.boolean().optional(),organized:a.boolean().optional(),favorite:a.boolean().optional(),session:a.string().min(1).max(12).optional(),session_id:a.string().min(1).max(512).optional(),sort:a.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:a.enum(["asc","desc"]).optional(),limit:a.number().int().min(1).max(200).optional(),cursor:a.string().max(512).optional()}).strict(),a.object({op:a.literal("library.get"),id:Pr}).strict(),a.object({op:a.literal("library.update"),id:Pr,fields:a.object({name:a.string().max(200).optional(),description:a.string().max(2e3).optional(),favorite:a.boolean().optional(),locked:a.boolean().optional(),archived:a.boolean().optional()}).strict()}).strict(),a.object({op:a.literal("library.tags")}).strict(),a.object({op:a.literal("library.tags.create"),name:a.string().trim().min(1).max(24),category:a.string().min(1).max(64).optional()}).strict(),a.object({op:a.literal("library.tags.update"),id:Mr,name:a.string().trim().min(1).max(24).optional(),category:a.string().min(1).max(64).optional()}).strict(),a.object({op:a.literal("library.tags.delete"),id:Mr}).strict(),a.object({op:a.literal("library.tags.merge"),id:Mr,into:Mr}).strict(),a.object({op:a.literal("library.tags.assign"),id:Pr,tags:a.array(Mr).max(64),primary:a.string().max(128).optional()}).strict(),a.object({op:a.literal("library.chat.link"),id:Pr,sessionId:G}).strict(),a.object({op:a.literal("library.chat.clear"),id:Pr}).strict(),a.object({op:a.literal("library.librarian"),action:a.enum(["status","open","pause","resume","run"]).optional()}).strict(),a.object({op:a.literal("sidebar_layout.get")}).strict(),a.object({op:a.literal("sidebar_layout.set"),layout:pb}).strict(),a.object({op:a.literal("notifications.list"),preview:a.literal(!0).optional(),includeAskReads:a.boolean().optional(),countSessionIds:a.array(G).max(50).optional(),kind:a.enum(["all","asks","updates"]).optional(),bulkPriority:a.enum(["any","high","normal_up"]).optional(),state:a.enum(["unread","all","dismissed"]).optional(),source:a.enum(["notify","ask"]).optional(),priority:a.enum(["high","normal","low"]).optional(),sessionId:G.optional(),throughSeq:a.number().int().min(0).optional(),cursor:a.string().min(1).max(64).optional(),limit:a.number().int().min(1).max(100).optional()}).strict(),a.object({op:a.literal("notifications.get"),id:sn}).strict(),a.object({op:a.literal("notifications.count")}).strict(),a.object({op:a.literal("notifications.read"),verb:a.enum(["read","unread","undo"]),target:a.union([Ql,Yl,hb])}).strict(),a.object({op:a.literal("notifications.dismiss"),verb:a.enum(["dismiss","undismiss"]),target:a.union([Ql,Yl])}).strict(),a.object({op:a.literal("notifications.seen"),items:a.array(a.object({id:sn,revision:a.number().int().min(1),anchorId:a.string().min(1).max(256),visibleSinceMs:a.number().int().min(0)}).strict()).min(1).max(50),evidence:a.object({sessionId:G,inputKind:a.enum(["pointer","key","wheel"]),inputAtMs:a.number().int().min(0),visibleSinceMs:a.number().int().min(0)}).strict()}).strict()]);gb.superRefine((e,t)=>{if(e.op==="team_bridge.conversations.consent"&&e.decision==="withdraw"!=(e.consent_version===void 0)&&t.addIssue({code:a.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:a.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:a.ZodIssueCode.custom,message:"Undo requires an operation token, and only undo accepts one",path:["target"]}),(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){t.addIssue({code:a.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:a.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:a.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:a.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:a.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,s=e.op!=="hub.check";if(n&&r||s&&!n&&!r||r&&e.kind===void 0){t.addIssue({code:a.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:a.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:a.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:a.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:a.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:a.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:a.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:a.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:a.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:a.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:a.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:a.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:a.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:a.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:a.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:a.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:a.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:a.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:a.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:a.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:a.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:a.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const Tt={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},_b={runtimeUnreachable:"runtime_unreachable"},No="runtime_busy",gf="runtime_retiring";a.object({data:a.object({aside_id:a.string().optional(),status:a.union([a.enum(["adopted","queued"]),a.string()]).optional()}).passthrough()}).passthrough();const _f=a.object({name:a.string(),description:a.string().nullish(),source:a.string().nullish(),link_id:a.string().nullish(),editable:a.boolean().nullish(),installed:a.boolean().nullish(),fingerprint:a.string().nullish(),form:a.string().nullish()}).passthrough(),bb=a.object({path:a.string(),size:a.number().nullish(),preview:a.string().nullish(),preview_truncated:a.boolean().nullish()}).passthrough(),vb=_f.extend({body:a.string().nullish(),body_in_detail:a.boolean().nullish(),body_length:a.number().nullish(),body_bytes:a.number().nullish(),body_truncated:a.boolean().nullish(),files:a.array(bb).nullish(),files_total:a.number().nullish(),files_truncated:a.boolean().nullish(),publish_budget:a.object({limit:a.number(),total:a.number()}).passthrough().nullish()}).passthrough(),Lx=a.object({skills:a.array(_f),scope:a.string().nullish(),detail:a.string().nullish(),skill_detail:vb.nullish(),warning_count:a.number().nullish(),version:a.string().nullish()}).passthrough(),Ux="aside_adopt_refused",yb=["session_closed","open_tool_batch","turn_running"];function Fx(e){if(typeof e!="object"||e===null)return;const t=e.reason;return yb.find(n=>n===t)}const wb={[Tt.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[Tt.refused]:"ui.common.errors.desktop_refusal.refused",[Tt.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[Tt.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed"},ea={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 Lo(e){return e!==void 0&&Object.values(Tt).includes(e)}function kb(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return Tt.refused;if(t===503)return Tt.planeClosed}}const Bx=a.object({step:a.string(),blocked_on:a.string(),configured:a.boolean(),ready:a.boolean(),verified:a.boolean(),url:a.string().nullable(),credential_id:a.number().int().positive().nullable(),identity_label:a.string().nullable(),credential_choices:a.array(a.object({id:a.number().int().positive(),identity_label:a.string().nullable().optional()}).passthrough()).default([]),quote:a.object({monthly_price_usd:a.string().nullable(),positive_balance:a.boolean(),eligible:a.boolean(),account_valid:a.boolean()}).passthrough().nullable(),receipts:a.array(a.object({step:a.string(),ok:a.boolean(),text:a.string()})).default([]),remedy:a.object({kind:a.string(),text:a.string(),command:a.string().nullable().optional(),url:a.string().nullable().optional()}).nullable(),source:a.string(),in_progress:a.boolean().default(!1),progress:a.array(a.string()).default([]),active_credential_id:a.number().int().positive().nullable().default(null),billing_outcome:a.string().optional(),reservation_outcome:a.string().optional(),failure_stage:a.string().optional()}).passthrough(),Hx=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),Sb=88e4,Eb=11e5,Ab=2e4,Rb=9e4,Ib=new Set(["analytics.get","analytics.models","sessions.report"]),Tb=new Set(["usage.get"]),xb=new Set(["networks.list","peers.list"]),Cb=new Set([...Ib,...Tb,...xb]),Ob=90,Pb=30,Mb=300,jb=10,bf=15,$b=1e4;function Db(e){const n=e.to==="local"||e.keep?Mb:Pb,r=Math.max(0,e.waitS??0);return(Ob+n+jb+bf)*1e3+r*1e3}const Nb=18e4,Lb=Nb+15e3,Ub=120,Fb=135e3,Bb=93e4,vf=(Ub+30+bf)*1e3,Hb=6e4,Wb=5*vf,Gb=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function zb(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 vf;case"hub.check":return Hb;case"hub.applyAll":return Wb;default:return null}}function Kb(e){if(typeof e!="string"&&e.op==="sessions.transfer")return Db(e)+$b;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return Lb;if(t==="tunnel.setup.run")return Bb;if(t==="tunnel.setup.plan")return Fb;const n=zb(t);return n!==null?n:Cb.has(t)?Rb:Ab}const Vb=5e3;function yf(e){return Kb(e)+Vb}const Xa="deadline_exceeded",wf="foreground_required",kf="View these completions in the foreground before marking them read.",Zb=new Set(["capabilities","agent_messages.status","agent_messages.settings","agent_messages.allowlist.get","team_bridge.conversations.list","team_bridge.conversations.get","team_bridge.messages.list","team_bridge.messages.replies","team_bridge.owner_audit.conversations","team_bridge.owner_audit.messages","team_bridge.owner_audit.replies","team_bridge.unread","team_bridge.directory","team_bridge.status","accounts.list","analytics.get","analytics.models","approvals.list","commands.entities","commands.list","config.get","credentials.list","hub.updates","hub.links","info.get","instructions.get","legacy.agent.get","legacy.agent.history","legacy.agent.schedules.list","legacy.agents.list","legacy.job.get","legacy.jobs.list","legacy.models","legacy.models.providers","legacy.schedule.get","legacy.schedules.list","mcp.catalog","mcp.list","models.catalogue","networks.list","peers.list","profiles.get","profiles.list","projects.search","providers.list","quota.notice","runtimes.list","sessions.aside.get","sessions.checkpoints","sessions.failovers","sessions.find","sessions.get","sessions.history","sessions.files","sessions.userAttachments","sessions.list","sessions.preview","sessions.report","sessions.search","sessions.variables.list","skills.list","subagents.transcript","teams.effective","teams.get","teams.list","tunnel.setup.plan","tunnel.setup.read","usage.get"]),Yb=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Qb(e,t){const n=Math.round(t/1e3),r=Xa;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.`}:Gb.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:Zb.has(e)?{code:r,message:Yb.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 Wx=Sb,Gx=Eb;a.object({state:a.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:a.string(),kind:a.enum(["balance","subscription","radient","none"]),model_free:a.boolean(),title:a.string(),body:a.string(),actions:a.array(a.object({id:a.enum(["open_url","resend_verification","refresh"]),label:a.string(),url:a.string().nullable().optional()})),resets_at_ms:a.number().int().nullable().optional(),checked_at_ms:a.number().int(),age_ms:a.number().int().nullable().optional(),source:a.enum(["cached","live"])});function Xb(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function Xl(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 fi(e){return{...e.requestId?{request_id:e.requestId}:{},...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}}function pi(e){if(e.visibility==="org"!=!!e.tenantId)throw new Error('A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.')}function Jl(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 jr(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 hi(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function Jb(e){switch(e.op){case"capabilities":return{path:"/v1/capabilities",method:"GET"};case"runtimes.list":return{path:"/v1/desktop/runtimes?probe=false",method:"GET"};case"peers.list":return{path:"/v1/desktop/peers",method:"GET"};case"networks.list":return{path:"/v1/desktop/networks",method:"GET"};case"asks.list":return{path:"/v1/desktop/asks",method:"GET"};case"networks.invite":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/invite`,method:"POST",body:{role:e.role,device:e.deviceId??null}};case"networks.member.remove":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/members/${encodeURIComponent(e.deviceId)}`,method:"DELETE",body:{confirm:e.confirm}};case"sessions.transfer":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/transfer`,method:"POST",body:{to:e.to,keep:e.keep??!1,wait_s:e.waitS??0,...e.requestId?{request_id:e.requestId}:{}}};case"approvals.list":return{path:"/v1/desktop/approvals",method:"GET"};case"approvals.approve":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/approve`,method:"POST"};case"approvals.deny":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/deny`,method:"POST"};case"approvals.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:Jl(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:Jl(e)};case"imports.status":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"GET"};case"imports.cancel":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"DELETE"};case"profiles.create":return{path:"/v1/desktop/profiles",method:"POST",body:{request_id:e.requestId,name:e.name,...e.fields}};case"profiles.update":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"hub.updates":return{path:"/v1/desktop/hub/updates",method:"GET"};case"hub.skillPull":return{path:"/v1/desktop/hub/skills/pull",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.adoptionStrategy!==void 0?{adoption_strategy:e.adoptionStrategy}:{},...e.allowLlm!==void 0?{allow_llm:e.allowLlm}:{},...e.confirm!==void 0?{confirm:e.confirm}:{},...e.adoptionReceipt!==void 0?{adoption_receipt:e.adoptionReceipt}:{}}};case"hub.skillSubscribe":return{path:"/v1/desktop/hub/skills/subscribe",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias}};case"hub.skillUnpull":return{path:"/v1/desktop/hub/skills/unpull",method:"POST",body:{request_id:e.requestId,link_id:e.linkId}};case"hub.skillPublish":return{path:"/v1/desktop/hub/skills/publish",method:"POST",body:{request_id:e.requestId,dry_run:e.dryRun,source_skill:e.sourceSkill,local_alias:e.localAlias,visibility:e.visibility,tenant_id:e.tenantId,subscribe:e.subscribe,auto_push:e.autoPush,confirm_public_egress:e.confirmPublicEgress,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"hub.links":return{path:`/v1/desktop/hub/links${e.kind?`?kind=${e.kind}`:""}`,method:"GET"};case"hub.policy":return{path:`/v1/desktop/hub/links/${encodeURIComponent(e.linkId)}`,method:"PATCH",body:{request_id:e.requestId,expected_policy_revision:e.expectedPolicyRevision,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}};case"hub.check":return{path:"/v1/desktop/hub/updates/check",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{}}};case"hub.apply":return{path:"/v1/desktop/hub/updates/apply",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{},...e.prefer?{prefer:e.prefer}:{},...e.acknowledgeUnknownBaseline!==void 0?{acknowledge_unknown_baseline:e.acknowledgeUnknownBaseline}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.resolveSource===!0?{resolve_source:!0,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId??null}:{}}};case"hub.applyAll":return{path:"/v1/desktop/hub/updates/apply-all",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{}}};case"hub.retry":return{path:"/v1/desktop/hub/updates/retry",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{}}};case"hub.push":return{path:"/v1/desktop/hub/updates/push",method:"POST",body:{request_id:e.requestId,link_id:e.linkId,direction:e.direction,dry_run:e.dryRun,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"teams.list":return{path:"/v1/desktop/teams",method:"GET"};case"teams.get":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"GET"};case"teams.effective":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}/effective`,method:"GET"};case"teams.create":return{path:"/v1/desktop/teams",method:"POST",body:{request_id:e.requestId,...e.fields}};case"teams.update":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"sessions.list":{const t=new URLSearchParams;return t.set("limit",String(e.limit??100)),e.include_archived&&t.set("include_archived","true"),e.scope_kind&&t.set("scope_kind",e.scope_kind),e.scope_name&&t.set("scope_name",e.scope_name),e.cursor&&t.set("cursor",e.cursor),e.with_counts&&t.set("with_counts","true"),e.include_peers&&t.set("include_peers","true"),e.sort&&t.set("sort",e.sort),{path:`/v1/desktop/sessions?${t}`,method:"GET"}}case"delegated_cleanup_notice.ack":return{path:"/v1/desktop/delegated-cleanup-notice/ack",method:"POST"};case"sessions.search":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??C_)});return e.include_archived&&t.set("include_archived","true"),{path:`/v1/desktop/sessions/search?${t}`,method:"GET"}}case"sessions.archive":return{path:`/v1/desktop/sessions/${e.sessionId}/archive`,method:"POST",body:{archived:e.archived}};case"sessions.delete":return{path:`/v1/desktop/sessions/${e.sessionId}`,method:"DELETE",body:{confirmed:!0}};case"sessions.create":return{path:"/v1/desktop/sessions",method:"POST",body:{request_id:e.requestId,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.peer?{peer:e.peer}:{},...e.target?{target:e.target}:{},...e.model?{model:e.model}:{},...e.draftId?{draft_id:e.draftId}:{},...e.purpose?{purpose:e.purpose}:{}}};case"sessions.preview":return{path:"/v1/desktop/sessions/preview",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.draft":return{path:"/v1/desktop/sessions/draft",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.get":{const t=new URLSearchParams;return e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),bo(t,`/v1/desktop/sessions/${e.sessionId}`,e.orderIds??[])),{path:`/v1/desktop/sessions/${e.sessionId}${t.size?`?${t}`:""}`,method:"GET"}}case"sessions.files":{const t=new URLSearchParams({limit:String(e.limit??200)});for(const n of["scope","kind","q","sort","order","cursor"]){const r=e[n];r!==void 0&&t.set(n,r)}return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files?${t}`,method:"GET"}}case"sessions.files.materialise":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files/${encodeURIComponent(e.fileId)}/materialise`,method:"POST"};case"sessions.userAttachments":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/user-attachments`,method:"GET"};case"sessions.userAttachments.materialise":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/user-attachments/${encodeURIComponent(e.digest)}/materialise`,method:"POST"};case"sessions.history":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.openFrame&&(t.set("open_frame","1"),t.set("supplements","1")),e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),e.sourceRead==="metadata"?t.set("source_read","metadata"):e.sourceRead==="payload"&&e.expectedJournalGeneration&&t.set("source_read","payload"),e.expectedJournalGeneration&&t.set("expected_journal_generation",e.expectedJournalGeneration),bo(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??P_)});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),{path:`/v1/desktop/sessions/${e.sessionId}/children/${e.childId}/transcript?${t}`,method:"GET"}}case"sessions.message":return{path:`/v1/desktop/sessions/${e.sessionId}/messages`,method:"POST",body:{request_id:e.requestId,text:e.text,images:e.images??[],...e.files?.length?{files:e.files}:{},mode:e.mode??"prompt",...e.inputMode?{input_mode:e.inputMode}:{},...e.inputPath?{input_path:e.inputPath}:{}}};case"sessions.command":return{path:`/v1/desktop/sessions/${e.sessionId}/commands`,method:"POST",body:{request_id:e.requestId,command:e.command,args:e.args??"",images:e.images??[]}};case"sessions.answer":return e.askId!==void 0?{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{ask_id:e.askId,answers:e.answers,decline:e.decline,...e.revise===!0?{revise:!0}:{},...e.dismiss===!0?{dismiss:!0,...e.reason!==void 0?{reason:e.reason}:{}}:{}}}:{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{epoch:e.epoch,request_id:e.requestId,value:e.value,approved:e.approved,question_index:e.questionIndex}};case"sessions.seen":return{path:`/v1/desktop/sessions/${e.sessionId}/seen`,method:"POST",body:{completion_token:e.completionToken}};case"attention.seen":return{path:"/v1/desktop/attention/seen",method:"POST",body:{items:e.items.map(t=>({session_id:t.sessionId,completion_token:t.completionToken}))}};case"sessions.notified":return{path:`/v1/desktop/sessions/${e.sessionId}/notified`,method:"POST",body:{completion_token:e.completionToken}};case"tags.list":return{path:"/v1/desktop/tags",method:"GET"};case"tags.replace":return{path:"/v1/desktop/tags",method:"PUT",body:{tags:e.tags}};case"sessions.tags":return{path:`/v1/desktop/sessions/${e.sessionId}/tags`,method:"PUT",body:{tags:e.tags,primary:e.primary,...e.expected_revision===void 0?{}:{expected_revision:e.expected_revision}}};case"sessions.pin":return{path:`/v1/desktop/sessions/${e.sessionId}/pin`,method:"POST",body:{pinned:e.pinned}};case"sessions.watch":return{path:`/v1/desktop/sessions/${e.sessionId}/watch`,method:"POST",body:{subscription_id:e.subscriptionId,visible:e.visible,can_notify:e.canNotify}};case"sessions.presence":return{path:"/v1/desktop/presence",method:"POST",body:{subscription_id:e.subscriptionId,can_notify_kinds:e.canNotifyKinds,session_id:e.sessionId,window:e.window,can_notify:e.canNotify}};case"sessions.move":return{path:`/v1/desktop/sessions/${e.sessionId}/working-directory`,method:"POST",body:{request_id:e.requestId,cwd:e.cwd}};case"sessions.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/warm`,method:"POST",body:{}};case"sessions.interrupt":return{path:`/v1/desktop/sessions/${e.sessionId}/interrupt`,method:"POST",body:{request_id:e.requestId}};case"supplements.cancel":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/cancel`,method:"POST",body:{anchor:e.anchor}};case"supplements.restart":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/restart`,method:"POST",body:{anchor:e.anchor}};case"supplements.steer":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/steer`,method:"POST",body:{anchor:e.anchor,text:e.text}};case"sessions.variables.list":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"GET"};case"sessions.variables.create":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"POST",body:{key:e.key,value:e.value,type:e.type}};case"sessions.variables.update":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"PATCH",body:{value:e.value,type:e.type}};case"sessions.variables.delete":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"DELETE"};case"legacy.models":{const t=new URLSearchParams;return e.provider&&t.set("provider",e.provider),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:t.size>0?`/v1/models?${t}`:"/v1/models",method:"GET"}}case"legacy.models.providers":return{path:"/v1/models/providers",method:"GET"};case"auth.probe":return{path:`/v1/auth/providers/${e.provider}/probe`,method:"POST"};case"legacy.agent.upload":return{path:`/v1/agents/${e.agentId}/upload`,method:"POST"};case"agent.publish":{pi(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"POST",body:{document:e.document??{},...fi(e)}}}case"agent.republish":{pi(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"PUT",body:{hub_agent_id:e.hubAgentId,document:e.document??{},...fi(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{pi(e);const t=new URLSearchParams;return e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId)),{path:`/v1/teams/${e.teamId}/publish${t.size?`?${t}`:""}`,method:"POST",body:fi(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,...Xb(e),message:e.message,...Xl(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...Xl(e)}};case"wakes.remove":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"DELETE"};case"monitors.cancel":return{path:`/v1/desktop/monitors/${encodeURIComponent(e.sessionId)}/${encodeURIComponent(e.monitorId)}`,method:"DELETE"};case"jobs.cancel":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/jobs/${encodeURIComponent(e.jobId)}/cancel`,method:"POST"};case"legacy.jobs.list":{const t=new URLSearchParams;return e.agentId&&t.set("agent_id",e.agentId),e.status&&t.set("status",e.status),{path:t.size>0?`/v1/jobs?${t}`:"/v1/jobs",method:"GET"}}case"legacy.job.get":return{path:`/v1/jobs/${e.jobId}`,method:"GET"};case"legacy.schedules.list":return{path:`/v1/schedules?${new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)})}`,method:"GET"};case"legacy.agent.schedules.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/schedules?${t}`,method:"GET"}}case"legacy.agent.schedule.create":return{path:`/v1/agents/${e.agentId}/schedules`,method:"POST",body:e.schedule};case"legacy.schedule.get":return{path:`/v1/schedules/${e.scheduleId}`,method:"GET"};case"legacy.schedule.edit":return{path:`/v1/schedules/${e.scheduleId}`,method:"PATCH",body:e.schedule};case"legacy.schedule.remove":return{path:`/v1/schedules/${e.scheduleId}`,method:"DELETE"};case"legacy.agent.create":return{path:"/v1/agents",method:"POST",body:e.agent};case"legacy.agent.update":return{path:`/v1/agents/${e.agentId}`,method:"PATCH",body:e.update};case"legacy.agent.delete":return{path:`/v1/agents/${e.agentId}`,method:"DELETE"};case"legacy.agent.conversation.clear":return{path:`/v1/agents/${e.agentId}/conversation`,method:"DELETE"};case"legacy.agent.systemPrompt.get":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"GET"};case"legacy.agent.systemPrompt.update":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"PUT",body:{system_prompt:e.systemPrompt}};case"legacy.agent.download":return{path:`/v1/agents/${e.agentId}/download`,method:"GET"};case"legacy.job.cancel":return{path:`/v1/jobs/${e.jobId}`,method:"DELETE"};case"commands.list":return{path:"/v1/desktop/commands",method:"GET"};case"commands.entities":return{path:`/v1/desktop/sessions/${e.sessionId}/command-entities?command=${encodeURIComponent(e.command)}${e.name?`&name=${encodeURIComponent(e.name)}`:""}`,method:"GET"};case"models.catalogue":{const t=e.scope?`&scope=${e.scope}`:"";return{path:`/v1/desktop/models?live=${e.live??!1}${t}`,method:"GET"}}case"usage.get":{const t=new URLSearchParams({live:String(e.live??!1),refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),{path:`/v1/desktop/usage?${t}`,method:"GET"}}case"quota.notice":{const t=new URLSearchParams({refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),e.model&&t.set("model",e.model),{path:`/v1/desktop/quota-notice?${t}`,method:"GET"}}case"analytics.get":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics?${t}`,method:"GET"}}case"analytics.models":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics/models?${t}`,method:"GET"}}case"info.get":return{path:"/v1/desktop/info",method:"GET"};case"sessions.report":{const t=new URLSearchParams({recent_limit:String(e.recentLimit??12)});return{path:`/v1/desktop/sessions/${e.sessionId}/report?${t}`,method:"GET"}}case"skills.list":{const t=new URLSearchParams;e.sessionId&&t.set("session_id",e.sessionId),e.cwd&&t.set("cwd",e.cwd),e.name&&t.set("name",e.name);const n=t.toString();return{path:`/v1/desktop/skills${n?`?${n}`:""}`,method:"GET"}}case"skills.create":return{path:"/v1/desktop/skills",method:"POST",body:{request_id:e.requestId,name:e.name,copy_from:e.copyFrom}};case"skills.update":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"PUT",body:{request_id:e.requestId,expected_fingerprint:e.expectedFingerprint,files:e.files}};case"skills.remove":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"DELETE",body:{request_id:e.requestId,discard_local_changes:e.discardLocalChanges}};case"sessions.failovers":return{path:`/v1/desktop/sessions/${e.sessionId}/failovers`,method:"GET"};case"sessions.credential":return{path:`/v1/desktop/sessions/${e.sessionId}/credentials`,method:"POST",body:{action:e.action,key:e.key,value:e.value,confirmed:e.confirmed}};case"sessions.fork":return{path:`/v1/desktop/sessions/${e.sessionId}/fork`,method:"POST",body:{request_id:e.requestId,message:e.message,boundary:e.boundary,entry_id:e.entryId,auto_tag:e.autoTag}};case"sessions.stop":return{path:"/v1/desktop/stop",method:"POST",body:{request_id:e.requestId,targets:e.targets,confirmed:e.confirmed}};case"sessions.aside":return{path:`/v1/desktop/sessions/${e.sessionId}/asides`,method:"POST",body:{request_id:e.requestId,text:e.text,aside_id:e.asideId,subscription_id:e.subscriptionId}};case"sessions.adopt":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}/adopt`,method:"POST",body:{request_id:e.requestId,confirmed:e.confirmed}};case"sessions.aside.get":case"sessions.aside.close":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}`,method:e.op==="sessions.aside.get"?"GET":"DELETE"};case"mcp.list":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"GET"};case"mcp.credentials.store":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp/credentials`,method:"POST",body:{name:e.name,values:e.values,confirmed_replace:e.confirmedReplace}};case"mcp.control":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"POST",body:e.control};case"mcp.catalog":{const t=new URLSearchParams;e.cwd&&t.set("cwd",e.cwd),e.sessionId&&t.set("session_id",e.sessionId);const n=t.toString();return{path:n?`/v1/desktop/mcp?${n}`:"/v1/desktop/mcp",method:"GET"}}case"mcp.catalog.control":return{path:"/v1/desktop/mcp",method:"POST",body:{...e.control,...e.cwd?{cwd:e.cwd}:{}}};case"mcp.catalog.credentials":return{path:"/v1/desktop/mcp/credentials",method:"POST",body:{name:e.name,values:e.values,...e.header?{header:e.header}:{},confirmed_replace:e.confirmedReplace,...e.cwd?{cwd:e.cwd}:{}}};case"radient.request":return{path:"/v1/desktop/radient",method:"POST",body:e.control};case"providers.list":return{path:"/v1/auth/providers",method:"GET"};case"accounts.list":return{path:"/v1/auth/status",method:"GET"};case"accounts.remove":return{path:`/v1/auth/accounts/${e.accountId}`,method:"DELETE"};case"tunnel.setup.read":return{path:e.credentialId===void 0?"/v1/desktop/tunnel/setup":`/v1/desktop/tunnel/setup?credential_id=${e.credentialId}`,method:"GET"};case"tunnel.setup.plan":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"plan",...e.credentialId!==void 0?{credential_id:e.credentialId}:{}}};case"tunnel.setup.run":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"run",credential_id:e.credentialId,...e.acceptMonthlyPrice!==void 0?{accept_monthly_price:e.acceptMonthlyPrice}:{}}};case"auth.start":return{path:"/v1/auth/login",method:"POST",body:{provider:e.provider}};case"auth.status":return{path:`/v1/auth/operations/${e.id}`,method:"GET"};case"auth.input":return{path:`/v1/auth/operations/${e.id}/input`,method:"POST",body:{prompt_id:e.promptId,value:e.value}};case"auth.cancel":return{path:`/v1/auth/operations/${e.id}`,method:"DELETE"};case"auth.key":return{path:`/v1/auth/providers/${e.provider}/key`,method:"PUT",body:{value:e.value}};case"auth.logout":return{path:`/v1/auth/providers/${e.provider}/credentials`,method:"DELETE"};case"agent_messages.status":return{path:`/v1/desktop/team-bridge/status?boundary=${e.boundary}`,method:"GET"};case"agent_messages.enable":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,state:e.state,consent_version:e.consent_version,consented_via:e.consented_via}};case"agent_messages.settings":return{path:`/v1/desktop/team-bridge/settings${hi(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${hi(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)}${hi(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"?"":jr(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${jr(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)}${jr(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)}${jr(e)}`,method:"DELETE"};case"team_bridge.conversations.consent":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}/consent`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},decision:e.decision,...e.consent_version?{consent_version:e.consent_version}:{},...e.endpoint_id?{endpoint_id:e.endpoint_id}:{}}};case"team_bridge.owner_audit.conversations":case"team_bridge.owner_audit.messages":case"team_bridge.owner_audit.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit));let n="/v1/desktop/team-bridge/owner-audit/conversations";return e.op==="team_bridge.owner_audit.conversations"?e.cursor!==void 0&&t.set("cursor",e.cursor):(n+=`/${encodeURIComponent(e.conversation_id)}/messages`,e.op==="team_bridge.owner_audit.messages"?e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)):(n+=`/${encodeURIComponent(e.message_id)}/replies`,e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order))),{path:`${n}?${t}`,method:"GET"}}case"team_bridge.messages.list":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.endpoint_id&&t.set("endpoint_id",e.endpoint_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages${n}`,method:"GET"}}case"team_bridge.reactions.toggle":{const t=`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/reactions/${encodeURIComponent(e.emoji)}`;return e.active?{path:t,method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id}}:{path:`${t}${jr(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.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"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"config.get":return{path:"/v1/config",method:"GET"};case"config.update":return{path:"/v1/config",method:"PATCH",body:e.value};case"instructions.get":return{path:"/v1/config/system-prompt",method:"GET"};case"instructions.update":return{path:"/v1/config/system-prompt",method:"PATCH",body:{content:e.content}};case"credentials.list":return{path:"/v1/credentials",method:"GET"};case"credentials.update":return{path:"/v1/credentials",method:"PATCH",body:{key:e.key,value:e.value}};case"library.list":{const t=new URLSearchParams;e.scope&&t.set("scope",e.scope),e.q&&t.set("q",e.q),e.category&&t.set("category",e.category),e.kind&&t.set("kind",e.kind),e.origin_group&&t.set("origin_group",e.origin_group),e.origin&&t.set("origin",e.origin),e.tag&&t.set("tag",e.tag),e.tag_mode&&t.set("tag_mode",e.tag_mode),e.highlighted!==void 0&&t.set("highlighted",e.highlighted?"1":"0"),e.organized!==void 0&&t.set("organized",e.organized?"1":"0"),e.favorite!==void 0&&t.set("favorite",e.favorite?"1":"0"),e.session&&t.set("session",e.session),e.session_id&&t.set("session_id",e.session_id),e.sort&&t.set("sort",e.sort),e.order&&t.set("order",e.order),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);const n=t.toString();return{path:`/v1/desktop/library/assets${n?`?${n}`:""}`,method:"GET"}}case"library.get":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"GET"};case"library.update":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"PATCH",body:e.fields};case"library.tags":return{path:"/v1/desktop/library/tags",method:"GET"};case"library.tags.create":return{path:"/v1/desktop/library/tags",method:"POST",body:{name:e.name,...e.category!==void 0?{category:e.category}:{}}};case"library.tags.update":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"PATCH",body:{...e.name!==void 0?{name:e.name}:{},...e.category!==void 0?{category:e.category}:{}}};case"library.tags.delete":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"DELETE"};case"library.tags.merge":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}/merge`,method:"POST",body:{into:e.into}};case"library.tags.assign":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/tags`,method:"PUT",body:{tags:e.tags,...e.primary!==void 0?{primary:e.primary}:{}}};case"library.chat.link":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"PUT",body:{session_id:e.sessionId}};case"library.chat.clear":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"DELETE"};case"library.librarian":{const t=e.action??"status";return t==="status"?{path:"/v1/desktop/librarian",method:"GET"}:{path:"/v1/desktop/librarian",method:"POST",body:{op:t}}}case"projects.list":return{path:"/v1/desktop/projects",method:"GET"};case"projects.get":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"GET"};case"projects.create":return{path:"/v1/desktop/projects",method:"POST",body:{name:e.name,...e.description!==void 0?{description:e.description}:{},...e.status!==void 0?{status:e.status}:{},...e.tags!==void 0?{tags:e.tags}:{}}};case"projects.update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"PATCH",body:{...e.fields,...e.force_done===!0?{force_done:!0}:{}}};case"projects.delete":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"DELETE",body:{confirm:e.confirmed_name}};case"projects.link":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links`,method:"POST",body:{session_id:e.sessionId}};case"projects.unlink":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links/${encodeURIComponent(e.sessionId)}`,method:"DELETE"};case"projects.milestone":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones`,method:"POST",body:{name:e.name,...e.targetDate!==void 0?{target_date:e.targetDate}:{},...e.completed!==void 0?{completed:e.completed}:{}}};case"projects.milestone.remove":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones/${encodeURIComponent(e.name)}`,method:"DELETE"};case"projects.request_update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/request-update`,method:"POST"};case"projects.search":return{path:`/v1/desktop/projects/search?${new URLSearchParams({q:e.q,limit:String(e.limit??db)})}`,method:"GET"};case"aida.status":return{path:"/v1/desktop/aida",method:"GET"};case"aida.control":return{path:"/v1/desktop/aida",method:"POST",body:{op:e.action}};case"code_requests.list":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests`,method:"GET"};case"code_requests.refresh":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests/refresh`,method:"POST",body:{...e.keys!==void 0?{keys:e.keys}:{},...e.force!==void 0?{force:e.force}:{}}};case"static.sign":return{path:"/v1/static/sign",method:"POST",body:{route:e.route,path:e.path,ttl_s:e.ttlS}};case"sidebar_layout.get":return{path:"/v1/desktop/sidebar-layout",method:"GET"};case"sidebar_layout.set":return{path:"/v1/desktop/sidebar-layout",method:"PUT",body:{layout:e.layout}};case"notifications.list":{const t=new URLSearchParams;e.preview&&t.set("preview","true"),e.includeAskReads&&t.set("include_ask_reads","true");for(const n of e.countSessionIds??[])t.append("count_session_ids",n);return e.kind&&t.set("kind",e.kind),e.bulkPriority&&t.set("bulk_priority",e.bulkPriority),e.state&&t.set("state",e.state),e.source&&t.set("source",e.source),e.priority&&t.set("priority",e.priority),e.sessionId&&t.set("session_id",e.sessionId),e.cursor&&t.set("cursor",e.cursor),e.throughSeq!==void 0&&t.set("through_seq",String(e.throughSeq)),e.limit!==void 0&&t.set("limit",String(e.limit)),{path:`/v1/desktop/notifications${t.size?`?${t}`:""}`,method:"GET"}}case"notifications.get":return{path:`/v1/desktop/notifications/${encodeURIComponent(e.id)}`,method:"GET"};case"notifications.count":return{path:"/v1/desktop/notifications/count",method:"GET"};case"notifications.read":case"notifications.dismiss":return{path:"/v1/desktop/notifications",method:"PATCH",body:{op:e.verb,...qb(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:mb[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function qb(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 zx=64,Kx=64*1024*1024,Vx="superseded_completion_token",Zx="store_busy",ev="session_is_remote",tv="owner_build_behind";function Yx(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 fr(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 nv(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const Qx=e=>typeof e?.goal_status=="string",Xx=e=>(e?.goal??"").trim().length>0;function rv(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function sv(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 Yr={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 ov(e){return e?e===Yr.notPaired?"notPaired":e===Yr.serverDown?"serverDown":e===Yr.frameBudget?"frameTooLarge":"lost":"lost"}const ql=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(g=>g(t,h))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d))},l=t=e(r,s,c);return c},iv=e=>e?ql(e):ql,av=e=>e;function cv(e,t=av){const n=ol.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return ol.useDebugValue(n),n}const ed=e=>{const t=iv(e),n=r=>cv(t,r);return Object.assign(n,t),n},Rs=e=>e?ed(e):ed;function Sf(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var o;const i=l=>l===null?null:JSON.parse(l,void 0),c=(o=n.getItem(s))!=null?o:null;return c instanceof Promise?c.then(i):i(c)},setItem:(s,o)=>n.setItem(s,JSON.stringify(o,void 0)),removeItem:s=>n.removeItem(s)}}const ta=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return ta(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return ta(r)(n)}}}},lv=(e,t)=>(n,r,s)=>{let o={storage:Sf(()=>localStorage),partialize:b=>b,version:0,merge:(b,_)=>({..._,...b}),...t},i=!1;const c=new Set,l=new Set;let d=o.storage;if(!d)return e((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),n(...b)},r,s);const u=()=>{const b=o.partialize({...r()});return d.setItem(o.name,{state:b,version:o.version})},f=s.setState;s.setState=(b,_)=>{f(b,_),u()};const h=e((...b)=>{n(...b),u()},r,s);s.getInitialState=()=>h;let g;const y=()=>{var b,_;if(!d)return;i=!1,c.forEach(R=>{var k;return R((k=r())!=null?k:h)});const p=((_=o.onRehydrateStorage)==null?void 0:_.call(o,(b=r())!=null?b:h))||void 0;return ta(d.getItem.bind(d))(o.name).then(R=>{if(R)if(typeof R.version=="number"&&R.version!==o.version){if(o.migrate){const k=o.migrate(R.state,R.version);return k instanceof Promise?k.then(O=>[!0,O]):[!0,k]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,R.state];return[!1,void 0]}).then(R=>{var k;const[O,L]=R;if(g=o.merge(L,(k=r())!=null?k:h),n(g,!0),O)return u()}).then(()=>{p?.(g,void 0),g=r(),i=!0,l.forEach(R=>R(g))}).catch(R=>{p?.(void 0,R)})};return s.persist={setOptions:b=>{o={...o,...b},b.storage&&(d=b.storage)},clearStorage:()=>{d?.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>y(),hasHydrated:()=>i,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(l.add(b),()=>{l.delete(b)})},o.skipHydration||y(),g||h},Uo=lv,dv=(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 uv(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,s)=>typeof r=="number"&&Number.isFinite(r)?r:s;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 Ef=Rs()(Uo(e=>({notice:null,receive:t=>e(n=>dv(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:Sf(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function Ja(e){return v(wb[e])}async function Af(e){if(window.api?.desktop)try{return await fv(window.api.desktop.request(e),e)}catch(n){throw n instanceof Oe?n:bv(n)?new In(kf,wf):new Oe(null,"Desktop controls could not reach the backend process.",n)}let t;try{t=await fetch("/__desktop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(n){throw new Oe(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new Oe(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function fv(e,t){const n=yf(t);let r;return Promise.race([e,new Promise((s,o)=>{r=setTimeout(()=>{const i=Qb(t.op,n);o(new Oe(null,i.message,void 0,i.code))},n)})]).finally(()=>clearTimeout(r))}const Rf="This server did not answer the request for its desktop controls.",pv=()=>v("ui.common.errors.desktop_refusal_placeholder");class Oe extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,s,o,i){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=s,this.retryAfterMs=o,this.detail=i}}class In extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function qa(e,t){return e instanceof Oe||e instanceof In?Lo(e.code)?Ja(e.code):e.message===Rf?pv():e.message:t}function hv(e,t,n,r){return typeof r=="string"?r:n===ea.noCredential?Tt.noCredential:n===ea.transportFailed?Tt.transportFailed:kb(Jb(e).path,t)}async function Ze(e){const t=await Af(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 Oe(t.status,r??Rf,void 0,hv(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"&&mv(n?.result),n?.result}function mv(e){if(typeof e!="object"||e===null)return;const t=uv(e.delegated_cleanup_notice);t&&Ef.getState().receive(t)}async function gv(){try{await Ze({op:"delegated_cleanup_notice.ack"})}catch{}}async function Jx(){Ef.getState().dismiss(),await gv()}function _v(e){return e instanceof Oe&&e.code===Xa}function qx(e){if(!(e instanceof Oe))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===tv:e.code===ev}function eC(e){return e instanceof In&&e.code===wf}function bv(e){return e instanceof Error&&e.message.includes(kf)}async function tC(e){const t=await Af(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function nC(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await Ze({op:"auth.status",id:e});if(!n.auth_url)throw new Error("This sign-in is no longer waiting for a browser.");const r=new URL(n.auth_url);if(r.username||r.password||r.protocol!=="https:"&&!(r.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(r.hostname)))throw new Error("The provider returned an invalid sign-in address.");window.open(r.href,"_blank","noopener,noreferrer")}function vv(e,t){const n=window.api?.desktop?.stream;if(n){const o=n.subscribe(e,t);return()=>o.dispose()}const r=new URLSearchParams({session:e.sessionId});e.epoch&&r.set("epoch",e.epoch),e.afterSeq!==void 0&&r.set("after_seq",String(e.afterSeq)),r.set("frontend_replace","1"),e.openFrame===!0&&r.set("open_frame","1"),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),bo(r,"/__desktop/stream",e.orderIds??[]));const s=new EventSource(`/__desktop/stream?${r}`);return s.onmessage=o=>{t({kind:"data",data:o.data})},s.onerror=()=>{s.readyState===EventSource.CLOSED&&(t({kind:"error",detail:Yr.ended}),s.close())},()=>{s.close(),t({kind:"end"})}}async function rC(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}),s=r.headers.get("content-type")??"";if(!r.ok){let o="The media request failed.",i;if(s.includes("application/json"))try{const l=(await r.json())?.detail;if(typeof l=="string")o=l;else if(typeof l=="object"&&l!==null){const d=l;typeof d.text=="string"&&d.text.trim()?o=d.text:typeof d.message=="string"&&d.message.trim()&&(o=d.message),typeof d.code=="string"&&(i=d.code)}}catch{}return{status:r.status,kind:"error",detail:o,code:i!==void 0&&Lo(i)?i:o===ea.noCredential?Tt.noCredential:void 0}}return s.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:s||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function sC(e){return e.kind==="error"?Lo(e.code)?new In(Ja(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function yv(e){if(_v(e))return"deadline";const t=e instanceof Oe?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const If={unreachable:"",deadline:"",unauthorized:"",get outdated(){return v("ui.common.connection.backend.remedy_outdated")},unknown:""},na={get unreachable(){return v("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return v("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return v("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return v("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function wv(e,t){const n=yv(t);return[e,na[n],If[n]].filter(Boolean).join(" ")}const ra={get successor(){return v("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return v("ui.common.connection.backend.pairing_unpaired")}},kv={get successor(){return v("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return v("ui.common.connection.backend.pane_unpaired")}};function oC(e,t){return e!=="unpaired"?null:kv[t??"unpaired"]}function iC(e,t){return e!=="unpaired"?null:ra[t??"unpaired"]}function aC(e){const{kind:t,unpaired:n,answered:r,cause:s=null,servedByThisApp:o=!1}=e;return s==="pre-handshake"?o:s!==null||n?!1:r?o:t==="outdated"}function cC(e){const{kind:t,unpaired:n,missing:r,answered:s,cause:o=null}=e;if(o!==null)return ra[o];if(!s){if(t==="unreachable")return v("ui.common.connection.backend.compatibility_unreachable",{diagnosis:na.unreachable});if(t==="unauthorized")return v("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return v("ui.common.connection.backend.compatibility_deadline",{diagnosis:na.deadline});if(t==="outdated")return v("ui.common.connection.backend.compatibility_outdated",{remedy:If.outdated})}return n?ra.unpaired:s?v("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):v("ui.common.connection.backend.compatibility_unknown")}const Sv=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function lC(e,t=null){return t!==null||!e?!0:Sv.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function Ev(e,t){return t instanceof Oe&&t.status===null?!1:e<1}function dC(e,t){return t instanceof Oe&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const Av={get successor(){return v("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.card_credential_refused")},get unpaired(){return v("ui.common.connection.backend.card_unpaired")}};function uC(e,t,n){return e===null?{sentence:wv(t,n),remedy:!0}:{sentence:Av[e],remedy:ef(e)}}const Tf={settings:["desktop","settings"],capabilities:["desktop","capabilities"],providers:["desktop","auth","providers"],commands:["desktop","commands"],accounts:["desktop","auth","accounts"],catalogue:["desktop","models"],credentials:e=>["desktop","credentials",e]},Rv=3e4,Iv=15e3;function Tv(e){return e?.desktop_available===!0}function fC(){const{client:e,provided:t}=eg();return qu({enabled:t,queryKey:Tf.capabilities,queryFn:async()=>{try{return await Ze({op:"capabilities"})}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>Tv(n.state.data)?Rv:Iv,refetchIntervalInBackground:!0},e)}function xv(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function pC(e,t,n=1){return xv(e,t,n)==="enabled"}function hC(e){return qu({queryKey:Tf.providers,queryFn:()=>Ze({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:Ev})}const $r=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function Cv(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(i=>{const c=$r(i);return c===null||!n.has(c)});for(const i of t.upserted??[]){const c=$r(i);if(c===null){r.push(i);continue}const l=r.findIndex(d=>$r(d)===c);l===-1?r.push(i):r[l]=i}if(!t.order)return r;const s=new Map;for(const i of r){const c=$r(i);c!==null&&s.set(c,i)}const o=[];for(const i of t.order){const c=String(i),l=s.get(c);l&&(o.push(l),s.delete(c))}for(const i of r){const c=$r(i);c!==null&&s.has(c)?(o.push(i),s.delete(c)):c===null&&o.push(i)}return o}const sa=e=>({revision:At(e),demand:e.orderDemand}),Hn=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Sr(e,t,n,r,s,o={}){let i=e;const c=t.journal_generation;if(t.reconcile===!0){const h=typeof c=="string"&&c.length>0?c:void 0;return i.orderNeedsReconcile&&i.orderWantedGeneration===h?i.journalMode?i:{...i,journalMode:!0}:{...i,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"&&!i.journalMode?{...i,journalMode:!0}:i;if(r&&t.journal_order_state==="ready"&&s&&i.orderNeedsReconcile&&i.orderDemand===s.demand&&(i={...i,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),c!==i.journalGeneration&&!r)return i.orderNeedsReconcile&&i.orderWantedGeneration===c?i:{...i,orderNeedsReconcile:!0,orderWantedGeneration:c,orderDemand:{generation:c}};let l=i.journalMode?i:{...i,journalMode:!0};if(c!==i.journalGeneration&&(l={...i,journalMode:!0,journalGeneration:c,orderRevision:(i.orderRevision??0)+1,journalPositions:new Map,orderNeedsReconcile:i.orderNeedsReconcile,orderWantedGeneration:i.orderWantedGeneration,orderDemand:i.orderDemand},o.peer===!0)){const h=(i.orderRevision??0)+1,g=new Map;for(const y of i.records){const b=y.sourceEntryId??(y.kind==="tool"||y.kind==="supplement"?null:y.id);typeof b=="string"&&b.length>0&&b.length<=128&&g.set(b,h)}l={...l,...g.size>0?{journalBodyOwed:g}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(h,g,y)=>{if(!Hn(y))return;const b=d.get(h);b&&b.seq>=y||(d===u&&(d=new Map(d)),d.set(h,{entryId:g,seq:y}))};for(const[h,g]of Object.entries(t.journal_ordinals??{}))f(h,h,g);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 ec(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 s=n,o=r;return t.tool_calls.forEach((i,c)=>{!i||typeof i.id!="string"||(n.get(i.id)!==t.id&&(n===s&&(n=new Map(n)),n.set(i.id,t.id)),r.get(i.id)!==c&&(r===o&&(r=new Map(r)),r.set(i.id,c)))}),n===s&&r===o?e:{...e,journalCallOwners:n,journalCallSlots:r}}function xf(e,t){const n=new Set(e.map(o=>o.id));let r=!1,s;for(let o=0;o<e.length;o++){const i=e[o];if(i.kind==="user"&&i.provisional===!0){s=i;continue}if(i.sourcePrecedes!==void 0){if(i.sourceAdmissionAnchor!==void 0){const{sourceAdmissionAnchor:c,...l}=i;e[o]=l,r=!0}s=e[o];continue}!t(i)&&s&&(i.sourceAdmissionAnchor===void 0||!n.has(i.sourceAdmissionAnchor))&&(e[o]={...i,sourceAdmissionAnchor:s.id},r=!0),s=e[o]}return r}function Cf(e,t,n,r,s){const o=[],i=new Set;let c=e,l;for(;c!==void 0;){if(s.has(c.id)){l=s.get(c.id);break}if(n(c)){l=r(c);break}if(c.kind==="user"&&c.provisional===!0||i.has(c.id))break;i.add(c.id),o.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of o)s.set(d,l);return l}const Ov=Number.MAX_SAFE_INTEGER;function Pv(e,t){const n=new Map,r=new Map,s=new Map;for(const o of e){if(o.sourcePrecedes===void 0)continue;const i=t(o);if(i!==void 0)r.set(o.sourcePrecedes,i);else{const c=r.get(o.sourcePrecedes);c!==void 0&&n.set(o.id,{seq:c,slot:Ov})}}for(let o=e.length-1;o>=0;o--){const i=e[o];if(i.sourcePrecedes===void 0)continue;const c=t(i);if(c!==void 0)s.set(i.sourcePrecedes,c);else if(!n.has(i.id)){const l=s.get(i.sourcePrecedes);l!==void 0&&n.set(i.id,{seq:l,slot:-1})}}return n}function Of(e,t){return{floor:Mv(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:Pv(e,t)}}function Pf(e,t,n,r){if(r===void 0||e.sourcePrecedes===void 0)return;const s=r.page.get(e.id);if(s!==void 0)return s;const o=new Set;let i=1,c=t.get(e.sourcePrecedes);for(;c!==void 0&&!o.has(c.id);){o.add(c.id);const l=n(c);if(l!==void 0)return{seq:l,slot:-i};const d=r.page.get(c.id);if(d!==void 0)return{seq:d.seq,slot:d.slot-i};i+=1,c=c.sourcePrecedes?t.get(c.sourcePrecedes):void 0}return r.floor===void 0?void 0:{seq:r.floor,slot:-i}}function Mf(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:r}=n,s=new Set;let o=1,i=t.get(e.sourcePrecedes);for(;i!==void 0&&!s.has(i.id);){if(i.sourcePrecedes===void 0){const c=r.get(i.id);return c===void 0?void 0:{slot:c,depth:o}}s.add(i.id),o+=1,i=t.get(i.sourcePrecedes)}}function Mv(e,t){let n;for(const r of e){if(r.sourcePrecedes!==void 0)continue;const s=t(r);s!==void 0&&(n===void 0||s<n)&&(n=s)}return n}function jf(e,t){const n=new Map;return r=>{if(!r)return;const s=t(r);if(s===void 0)return;const o=[],i=new Set;let c=r,l=!0;for(;c;){if(n.has(c.id)){l=n.get(c.id)===!0;break}if(i.has(c.id)||t(c)===void 0){l=!1;break}i.add(c.id),o.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of o)n.set(d,l);return l?s:void 0}}function vo(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const s=new Map;t.forEach((i,c)=>{if(i.kind!=="tool")return;const l=n.get(i.toolCallId);if(l===void 0||!r.has(i.toolCallId))return;const d=s.get(l);d?d.push(c):s.set(l,[c])});let o=t;for(const i of s.values()){if(i.length<2)continue;const c=i.map(l=>t[l]).sort((l,d)=>(r.get(l.toolCallId)??0)-(r.get(d.toolCallId)??0));c.every((l,d)=>l===t[i[d]])||(o===t&&(o=t.slice()),i.forEach((l,d)=>{o[l]=c[d]}))}return o}function $f(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return jv(e,t);const n=e.journalGeneration,r=e.journalPositions;let s=!1,o=!1;const i=t.map(b=>{b.sourcePrecedes!==void 0&&(o=!0);let p=[r?.get(b.sourceEntryId??b.id),r?.get(b.id)].filter(O=>O!==void 0).sort((O,L)=>L.seq-O.seq)[0];if(b.journalGeneration===n&&Hn(b.journalSeq)&&(!p||b.journalSeq>p.seq)&&(p={entryId:b.sourceEntryId??b.id,seq:b.journalSeq}),!p||!n||!(b.kind==="user"&&(b.provisional===!0||b.local===!0))&&b.sourceEntryId===p.entryId&&b.journalSeq===p.seq&&b.journalGeneration===n)return b;s=!0;let k={...b,sourceEntryId:p.entryId,journalSeq:p.seq,journalGeneration:n};if(k.kind==="user"){const{provisional:O,local:L,...P}=k;k=P}return k});xf(i,b=>b.journalGeneration===n&&Hn(b.journalSeq))&&(s=!0);const l=new Map,d=new Map(i.map(b=>[b.id,b])),u=jf(d,b=>b!==void 0&&b.journalGeneration===n&&Hn(b.journalSeq)?b.journalSeq:void 0),f=b=>u(b)!==void 0,h=o?Of(i,u):void 0,g=(b,_)=>{const p=u(b);if(b.kind==="user"&&b.provisional===!0&&p===void 0)return[1,0,0,0,_];const R=b.kind==="supplement"?b.anchor:b.kind==="tool"?e.journalCallOwners?.get(b.toolCallId)??e.argsByCall.get(b.toolCallId)?.anchorId:void 0,k=typeof R=="string"?u(d.get(R)):void 0,O=k===void 0&&p===void 0?Pf(b,d,u,h):void 0,L=p===void 0&&O===void 0?Cf(b,d,f,u,l):void 0,P=k??p??O?.seq??L;if(P===void 0){const T=Mf(b,d,h);return[1,T?.slot??_,T?-T.depth:0,0,_]}return[0,P,k!==void 0?1:p!==void 0?0:O!==void 0?O.slot:2,p??Number.MAX_SAFE_INTEGER,_]},y=i.map((b,_)=>({record:b,index:_,rank:g(b,_)}));return y.sort((b,_)=>{for(let p=0;p<b.rank.length;p++){const R=b.rank[p]-_.rank[p];if(R)return R}return 0}),!s&&y.every((b,_)=>b.index===_)?vo(e,t):vo(e,y.map(b=>b.record))}function jv(e,t){const n=e.journalGeneration,r=e.journalPositions,s=new Map;let o=!1;for(const p of t){p.sourcePrecedes!==void 0&&(o=!0);let k=[r?.get(p.sourceEntryId??p.id),r?.get(p.id)].filter(O=>O!==void 0).sort((O,L)=>L.seq-O.seq)[0];p.journalGeneration===n&&Hn(p.journalSeq)&&(!k||p.journalSeq>k.seq)&&(k={entryId:p.sourceEntryId??p.id,seq:p.journalSeq}),k&&s.set(p.id,k)}const i=p=>p===void 0?void 0:s.get(p.id)??r?.get(p.sourceEntryId??p.id)??r?.get(p.id);let c=!1;const l=t.slice();xf(l,p=>p.journalGeneration===n&&Hn(p.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(p=>[p.id,p])),h=jf(f,p=>i(p)?.seq),g=p=>h(p)!==void 0,y=o?Of(l,h):void 0,b=(p,R)=>{const k=h(p);if(p.kind==="user"&&p.provisional===!0&&k===void 0)return[1,0,0,0,R];const O=p.kind==="supplement"?p.anchor:p.kind==="tool"?e.journalCallOwners?.get(p.toolCallId)??e.argsByCall.get(p.toolCallId)?.anchorId:void 0,L=typeof O=="string"?h(f.get(O)):void 0,P=L===void 0&&k===void 0?Pf(p,f,h,y):void 0,T=k===void 0&&P===void 0?Cf(p,f,g,h,u):void 0,m=L??k??P?.seq??T;if(m===void 0){const w=Mf(p,f,y);return[1,w?.slot??R,w?-w.depth:0,0,R]}return[0,m,L!==void 0?1:k!==void 0?0:P!==void 0?P.slot:2,k??Number.MAX_SAFE_INTEGER,R]},_=l.map((p,R)=>({record:p,index:R,rank:b(p,R)}));return _.sort((p,R)=>{for(let k=0;k<p.rank.length;k++){const O=p.rank[k]-R.rank[k];if(O)return O}return 0}),!c&&_.every((p,R)=>p.index===R)?vo(e,t):vo(e,_.map(p=>p.record))}function Gt(e){const t=e.records.filter(s=>s.kind==="user"&&s.provisional===!0),n=e.records.filter(s=>s.journalGeneration!==e.journalGeneration||!Hn(s.journalSeq)),r=[...t,...n].map(s=>s.sourceEntryId??(s.kind==="tool"||s.kind==="supplement"?null:s.id));if(r.push(...tc(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let s=r.length-1;s>=0;s--){const o=r[s];typeof o=="string"&&e.journalSourceVoid.has(o)&&r.splice(s,1)}return[...new Set(r.filter(s=>typeof s=="string"&&s.length>0&&s.length<=128))]}function tc(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const s=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof s=="string"&&s.length>0&&s.length<=128&&t.add(s)}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 Df(e,t){const n=e.journalPositions;return Gt(e).filter(r=>!n?.has(r)&&!t?.has(r))}const At=e=>e.orderRevision??0;async function $v(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"?tc(c):l==="lookup"?Df(c):Gt(c);let s=e.getTranscript().journalGeneration,o=0,i=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=sa(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",h=y_(r(c,f).filter(_=>!n(f).has(_)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),g=await e.read(h,f);if(!e.isCurrent()||At(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(g,d,l),!e.isCurrent())return{kind:"stale"};const y=e.getTranscript(),b=e.page(g);if(b.journal_order_state==="ready"&&b.journal_generation===y.journalGeneration){b.journal_generation!==s&&(t.clear(),s=b.journal_generation);for(const R of h)n(f).add(R);if(y.orderNeedsReconcile){if(y.orderDemand===l.demand||o===1)return{kind:"waiting"};o++,t.clear();continue}if(f==="payload"){const R=(b.source_retry_ids??[]).filter(k=>typeof k=="string"&&k.length>0&&k.length<=128);if(R.length>0&&h.length>1&&i===0){i++;for(const k of R)n("payload").delete(k);continue}}const _=e.sweep?.(y,n);if(_?.kind==="none")return{kind:"complete",transcript:y};const p=_?.kind??"authority";if(r(y,p).some(R=>!n(p).has(R)))continue;return{kind:"complete",transcript:y}}if(!y.orderNeedsReconcile||y.orderDemand===l.demand||o===1)return{kind:"waiting"};o++,t.clear()}}function jt(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const s=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof s=="string"&&s?s:e.id}function mi(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function td(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function mC(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 o of t){if(!o.settled||typeof o.run_key!="string"||o.run_key.length===0)continue;const i=mi(o.action_count);if(i===null)continue;const c={actions:i,workedSeconds:td(o.worked_seconds),failed:mi(o.failed_count)??0,complete:o.complete!==!1,openingUserId:typeof o.opening_user_id=="string"&&o.opening_user_id.length>0?o.opening_user_id:null,closingAnswerId:typeof o.closing_answer_id=="string"&&o.closing_answer_id.length>0?o.closing_answer_id:null,crossSessionActions:mi(o.cross_session_action_count),crossSessionWorkedSeconds:td(o.cross_session_worked_seconds)};n.set(o.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 o of e.entries)r.add(jt(o));const s=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:s?jt(s):null}}}function Dv(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(o=>o.opening_user_id===n.id))return null;const s=Math.round((n.ts??0)*1e3);return s>0?{id:n.id,tsMs:s}:null}function Nv(e,t,n){const r=Dv(e),s=e?.entries;if(r===null||!s||s.length===0)return!1;const o=Math.round((s[s.length-1].ts??0)*1e3);if(!(o>r.tsMs))return!1;for(const[i,c]of t)if(!n.has(i)&&(c===null||!(c>r.tsMs)||!(c<o)))return!1;return!0}const nc=new Set,Tn="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",rc=new RegExp(`[${Tn}]`),Lv=new RegExp(`[${Tn}]+`),gC=new RegExp(`[${Tn}]+`,"g"),Uv=new RegExp(`^[${Tn}]+|[${Tn}]+$`,"g"),Fv=new RegExp(`^[${Tn}]+`),_C=new RegExp(`[^${Tn}]`);function Yt(e){return e.replace(Uv,"")}function ms(e){return e.replace(Fv,"")}function Nf(e,t){return t===0||rc.test(e[t-1])}function Lf(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&Nf(e,n)&&t.push(n);return t}function sc(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
2
+ `,n-1)+1,s=e.indexOf(`
3
+ `,n),o=s===-1?e.length:s;let i=e.slice(r,o);return i.endsWith("\r")&&(i=i.slice(0,-1)),{line:i,lineStart:r,column:n-r}}function Bv(e,t){if(t.size===0)return null;for(const n of Lf(e)){const r=e.slice(n+1),s=r.indexOf(" ");if(s!==-1&&t.has(r.slice(0,s).toLowerCase()))return n}return null}function oc(e,t,n){const r=Bv(e,n);let s=null;for(const o of Lf(e)){if(o===r)return t>o?o:s;o<=t&&(s=o)}return s}function Hv(e,t=null,n=nc){const{line:r,lineStart:s,column:o}=sc(e,t),i=oc(r,o,n);if(i===null)return null;let c=i+1;for(;c<r.length&&!rc.test(r[c]);)c++;return o>c?null:{start:s+i,query:r.slice(i+1,c),end:s+c}}function bC(e,t=null,n=nc){const{line:r,lineStart:s,column:o}=sc(e,t),i=oc(r,o,n);return i===null?null:{start:s+i,end:s+r.length}}function Wv(e,t,n=null,r=nc){const{line:s,lineStart:o,column:i}=sc(e,n),c=r.size>0?r:new Set(t.map(g=>g.toLowerCase())),l=oc(s,i,c);if(l===null)return null;const d=s.slice(l+1),u=d.indexOf(" ");if(u===-1)return null;const f=d.slice(0,u);if(!t.some(g=>g.toLowerCase()===f.toLowerCase()))return null;const h=l+1+f.length;return i<=h?null:{value:d.slice(u+1),start:o+h+1,end:o+s.length,tokenStart:o+l}}function nd(e,t){return Yt(e.slice(0,t))===""}function vC(e,t,n,r){const s=Wv(e,r,t,n);if(s!==null&&nd(e,s.tokenStart))return"argument";const o=Hv(e,t,n);return o!==null&&nd(e,o.start)?"command":null}function yC(e,t,n,r){let s=t,o=n;const i=c=>c>=0&&c<e.length&&`
4
+ `.includes(e[c]);return r===""?s>0&&i(s-1)?s-=1:i(o)&&(o+=1):s===0&&i(o)&&(o+=1),{text:`${e.slice(0,s)}${r}${e.slice(o)}`,caret:s+r.length}}const Gv=1e3,zv=900,Kv=40,Uf=3;function Vv(e,t){let n=0,r=-2,s=0;for(const o of e){const i=t.indexOf(o,s);if(i<0)return 0;n+=i===r+1?2:1,r=i,s=i+1}return n<=0?0:Math.max(1,Math.min(Kv,n))}function Ff(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n?n===r?Gv:r.startsWith(n)?zv:Vv(n,r):0}function Zv(e){const n=Yt(e).split(Lv).pop()??"";return n.startsWith("/")?n.slice(1):n}function Yv(e,t){const n=Zv(e),r=[];return t.forEach((s,o)=>{let i=0,c=s.name;for(const l of[s.name,...s.aliases]){const d=Ff(n,l);d>i&&(i=d,c=l)}i>0&&r.push({score:i,index:o,name:c,command:s})}),r.sort((s,o)=>o.score-s.score||s.index-o.index),r.map(s=>({name:s.name,command:s.command}))}function wC(e,t){if(!e)return t.map(o=>({name:o.name,command:o}));const n=Yv(`/${e}`,t);if(e.length>=Uf)return n;const r=e.toLowerCase(),s=n.filter(({name:o})=>o.toLowerCase().startsWith(r));return s.length>0?s:n}function rd(e,t){if(!e)return t.map(r=>({name:r.name,choice:r}));const n=[];return t.forEach((r,s)=>{const o=Math.max(0,...[r.name,...r.aliases??[]].map(i=>Ff(e,i)));o>0&&n.push({score:o,order:s,choice:r})}),n.sort((r,s)=>s.score-r.score||r.order-s.order),n.map(r=>({name:r.choice.name,choice:r.choice}))}const sd=/^-+/;function kC(e,t,n,r,s){if(s)return!0;const o=Yt(e).toLowerCase(),i=Yt(t).toLowerCase();return o===i||o.length>0&&o.replace(sd,"")===i.replace(sd,"")?!0:!r&&n<=1}const Qv=new RegExp("\\p{Ll}","u");function Bf(e){for(const t of e)if(Qv.test(t))return!0;return!1}function SC(e,t,n){if(n){if(!e)return t.map(i=>({name:i.name,choice:i}));const r=rd(e,t);if(e.length>=Uf)return r;const s=e.toLowerCase(),o=r.filter(i=>i.name.toLowerCase().startsWith(s));return o.length>0?o:r}return Bf(e)?rd(e,t).filter(r=>r.name.startsWith(e)):[]}const Xv=/<skill name="([^"]*)" invocation="([^"]*)">/,Jv=/[A-Za-z0-9]/,qv=/[A-Za-z0-9._-]/,ey=/[._-]/;function ty(e,t){if(t>=e.length||!Jv.test(e[t]))return t;let n=t+1;for(;n<e.length&&qv.test(e[n]);)n++;return n}function ny(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!Nf(e,n)){n+=1;continue}const r=ty(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 ry(e,t,n,r,s,o){let i=n;for(;;){const c=e.slice(t+1,i);if(r.has(c))return{end:i,name:c};if(o||Bf(c)){const l=s.get(c.toLowerCase());if(l!==void 0)return{end:i,name:l}}if(i>t+2&&ey.test(e[i-1])){i-=1;continue}return null}}function sy(e,t,n={}){return Hf(e,t,n.skipSpans??[],!0)}function EC(e,t,n={}){return Hf(e,t,n.skipSpans??[],!1)}function Hf(e,t,n,r){const s=new Set(t),o=new Map;for(const l of t)o.has(l.toLowerCase())||o.set(l.toLowerCase(),l);const i=[],c=new Set;for(const l of ny(e)){if(n.some(([f,h])=>f<=l.start&&l.start<h))continue;const d=ms(e.slice(0,l.start))==="",u=ry(e,l.start,l.end,s,o,d);u===null||r&&c.has(u.name)||(c.add(u.name),i.push({start:l.start,end:u.end,text:e.slice(l.start,u.end),name:u.name,leading:d}))}return i}const pr="<operator-skills>",yo="</operator-skills>",zr=`
5
+
6
+ `,Wf="The user invoked the following skills directly. Follow them for this request. Their reference files, if any, are listed at the end of each body and are read with `skill://<name>/<path>`.",ic="​",oy=pr.replace("<",`<${ic}`),iy=yo.replace("<",`<${ic}`),ay=`<${ic}skill name=`,cy=/^<skill name="([^"]*)">/;function ly(e){return e.replace(/<\/operator-skills>/g,iy).replace(/<operator-skills>/g,oy).replace(/<skill name="/g,ay)}function AC(e){const t=e.map(({name:n,body:r})=>`<skill name="${n}">
7
+ ${ly(r)}
8
+ </skill>`);return pr+zr+Wf+zr+t.join(zr)+zr+yo}function ac(e){const t=[],n=pr+zr+Wf;let r=0;for(;;){const s=e.indexOf(n,r);if(s===-1)return t;const o=e.indexOf(yo,s+n.length),i=e.indexOf(pr,s+pr.length);if(o===-1||i!==-1&&i<o){r=s+pr.length;continue}const c=o+yo.length;t.push([s,c]),r=c}}function dy(e){const t=[];for(const[n,r]of ac(e)){let s=0;for(const o of e.slice(n,r).split(`
9
+ `)){if(s>0){o.startsWith("</skill>")&&(s-=1);continue}const i=cy.exec(o);i!==null&&(t.push(i[1]),s=1)}}return t}function RC(e,t){const n=ac(e),r=sy(e,t,{skipSpans:n});if(r.length===0)return[];const s=new Set(dy(e));return r.filter(o=>!s.has(o.name))}const od=new RegExp(`[${Tn}]+$`);function Gf(e){const t=ac(e);if(t.length===0)return e;const n=[];let r=0;for(const[o,i]of[...t].sort((c,l)=>c[0]-l[0])){if(i<=r)continue;const c=Math.max(o,r);n.push(e.slice(r,c).replace(od,"")),r=i}n.push(e.slice(r).replace(od,""));let s="";for(const o of n)o&&(s&&!rc.test(o[0])&&(s+=" "),s+=o);return s}function IC(e){if(!e||Yt(e)==="")return!1;let t=ms(e);if(t.startsWith("---")){const n=t.slice(3),r=n.indexOf(`
10
+ ---`);r!==-1&&(t=n.slice(r+4))}return Yt(t)!==""}function uy(e){return e.replace(/&#10;/g,`
11
+ `).replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&quot;/g,'"').replace(/&amp;/g,"&")}const et=[];for(let e=0;e<256;++e)et.push((e+256).toString(16).slice(1));function fy(e,t=0){return(et[e[t+0]]+et[e[t+1]]+et[e[t+2]]+et[e[t+3]]+"-"+et[e[t+4]]+et[e[t+5]]+"-"+et[e[t+6]]+et[e[t+7]]+"-"+et[e[t+8]]+et[e[t+9]]+"-"+et[e[t+10]]+et[e[t+11]]+et[e[t+12]]+et[e[t+13]]+et[e[t+14]]+et[e[t+15]]).toLowerCase()}let gi;const py=new Uint8Array(16);function hy(){if(!gi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");gi=crypto.getRandomValues.bind(crypto)}return gi(py)}const my=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),id={randomUUID:my};function gy(e,t,n){if(id.randomUUID&&!e)return id.randomUUID();e=e||{};const r=e.random??e.rng?.()??hy();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,fy(r)}const zf=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,oa=e=>{let t=e;for(;;){const n=zf.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},ad=e=>{const t=[];let n=e;for(;;){const r=zf.exec(n);if(r===null)break;t.push({id:gy(),text:r[1]}),n=n.slice(r[0].length)}return{replies:t,remainingContent:n.trim()}};function Fo(e){return cc(e)?.skill}const _y=/^\s/,by=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,vy=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function yy(e){const t=ms(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 wy(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function cd(e,t){const n=[];for(let r=1;r<e.length;r+=1){const s=e[r];if(t==='"'&&s==="\\"&&r+1<e.length){n.push(s,e[r+1]),r+=1;continue}if(s!==t){n.push(s);continue}if(t==="'"&&e[r+1]==="'"){n.push(s,s),r+=1;continue}const o=e.slice(r+1).trim();if(o!==""&&!o.startsWith("#"))return null;const i=n.join(""),c=t==="'"?i.replace(/''/g,"'"):wy(i);return c===""?null:c}return null}function ky(e){const t=e.split(`
13
+ `);for(const[n,r]of t.entries()){if(!r.startsWith("description:"))continue;const s=r.slice(12).trim(),o=s!==""&&by.test(s),i=[];s!==""&&!o&&i.push(s);for(let u=n+1;u<t.length;u+=1){const f=t[u];if(f.trim()!==""){if(!_y.test(f))break;i.push(f.trim())}}if(i.length===0)return null;const c=i.join(" ");if(o)return c.trim()===""?null:c.trim();if(c.startsWith('"'))return cd(c,'"');if(c.startsWith("'"))return cd(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function cc(e){const{prefix:t,rest:n}=oa(e),r=n.slice(0,n.length-ms(n).length),s=ms(n),o=vy.exec(s);if(o===null)return null;const i=Xv.exec(s.slice(o[0].length));if(i===null||i.index!==0||i[1]!==o[1])return null;const c=o[0].length+i[0].length,l=s.indexOf("</skill>",c);if(l===-1)return null;const d=s.slice(c,l),u=yy(d),f=u===null?null:ky(d.slice(0,u)),h=i[1],g=uy(i[2]);return{text:t+r+g,skill:{name:h,token:`$${h}`,request:Yt(s.slice(l+8)),purpose:f,body:Yt(u===null?d:d.slice(u))}}}function TC(e){const t=cc(e);if(t!==null)return t.text;const n=Gf(e);return n===e?e:Yt(n)}function Sy(e){const t=cc(e);if(t===null){const r=Gf(e);if(r===e)return null;const{prefix:s}=oa(e);return{replies:ad(e).replies,text:r.slice(s.length).trimStart()}}const{prefix:n}=oa(e);return{replies:ad(e).replies,text:t.text.slice(n.length).trimStart()}}function xC(e){return Sy(e)?.text??e}const Ey=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"]]),Ay=/\blabel=(['"])(.*?)\1/,Ry=/\bjob=(['"])(.*?)\1/,Iy=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function ia(e){const t=typeof e.text=="string"?e.text:"",n=Iy.exec(t);let r=n?.[2];const s=r?.indexOf(`
14
+
15
+ `)??-1,i=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&s>=0?Ey.get((r??"").slice(0,s)):void 0;n?.[1]==="parent-message"&&i&&(r=(r??"").slice(s+2));const c=typeof e.direction=="string"?e.direction:n?.[1]==="subagent-message"?"to_parent":i?"to_child":"";return{body:typeof e.body=="string"?e.body:r?.trim()?r:t,envelope:t,direction:c,label:Er(e.label??(n&&Ay.exec(n[0].split(`
16
+ `,1)[0])?.[2])),jobId:Er(e.job_id??(n&&Ry.exec(n[0].split(`
17
+ `,1)[0])?.[2])),sender:Xf(e).sender,expectsReply:typeof e.expects_reply=="boolean"?e.expects_reply:e.expects_reply===void 0&&i?i==="ask":null,steer:typeof e.steer=="boolean"?e.steer:e.steer===void 0&&i?i==="steer":null}}function CC(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 Ty(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 OC(e){return Ty(e)!==null}const Kf=/\s+/,xy=/[\\/]+$/,Cy=/[\\/]/,Vf=`
18
+
19
+ `,Oy=" — cancel with wake(",Py=120,Zf=/(?:\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,My=new RegExp("\\p{Cf}","gu"),jy=4096;function Er(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(Zf,"").replace(My,"").split(Kf).filter(Boolean).join(" ").slice(0,Py)}const PC={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function Yf(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(xy,"");if(t){const n=t.split(Cy).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function Qf(e){const{name:t,quoted:n}=Yf(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function $y(e){const{name:t,quoted:n}=Yf(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 MC(e,t){return t.trim()?!0:$y(e)!==Qf(e)}function Dy(e){for(const t of e.slice(0,jy).split(`
20
+ `)){const n=Er(t);if(n)return n}return""}function jC(e,t){const n=Qf(e),r=Dy(t);return r?`${n} · ${r}`:n}function _i(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const Ny=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,Ly=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,Uy=/^<peer-session-message[^>]*>/,Fy=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function Xf(e){const t=String(e.text??e.detail??""),n=Ny.exec(t.trim()),r={};if(n)for(const d of n[1].matchAll(Fy))r[d[1]]=d[2]??d[3]??d[4]??"";const s=n?n[2]:"",i=(String(e.body??"").trim()||s||(n?"":t.trim().replace(Uy,""))).replace(Ly,"").trim(),c=e.sender??{},l=(d,u)=>Er(d)||Er(u);return{body:i,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 By(e){return!!e.wake_catchup}function Hy(e){return e.hidden===!0}function $C(e){let t=e.split(Vf)[0]??"";t=t.split(Kf).filter(Boolean).join(" "),t=t.split(Oy)[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 DC(e){const t=e.indexOf(Vf);return t===-1?"":e.slice(t+2).trim()}const Gs=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},Dr=e=>typeof e=="string"?Er(e):"";function Wy(e){const t=Gs(e.bridge_receipt),n=t.v===1,r=Gs(n?t.sender:e.sender),s=n?Gs(t.conversation):{},o=n?t.attachment_count:void 0;return{sender:{name:Dr(r.name),...r.kind==="human"||r.kind==="agent"?{kind:r.kind}:{},...Dr(r.organization)?{organization:Dr(r.organization)}:{}},conversation:{...s.kind==="dm"||s.kind==="group"||s.kind==="channel"?{kind:s.kind}:{},...Dr(s.label)?{label:Dr(s.label)}:{}},...typeof o=="number"&&Number.isSafeInteger(o)&&o>=0?{attachmentCount:o}:{}}}const Gy=new Set(["channel_post","channel_create","channel_history","channel_thread","react","shared_history"]),zy=new Set(["channel_post","dm","send","reply"]),Ky=new Set(["take_up","ack","send","reply","channels","channel_create","channel_post","channel_history","react","channel_thread","directory","dm","shared_conversations","shared_history"]),Vy=/^(?:bcv|bcmsg|acc|ep)_/i,Zy=/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]|\x9b[0-?]*[ -/]*[@-~]/g,Yy=/[\x00-\x08\x0e-\x1f\x7f-\x9f]/g,Qy=new RegExp("(?![\\u200c\\u200d])\\p{Cf}","gu"),Xy=/[\t\n\r\v\f ]+/,Jy=/\r\n|\r|\n/,qy=/^bcv_\S+$/,e0=200;function gs(e){return typeof e!="string"?null:e.replace(Zy,"").replace(Yy,"").replace(Qy,"").split(Xy).filter(Boolean).join(" ").slice(0,e0)||null}function Ln(e){const t=gs(e);return t&&!Vy.test(t)?t:null}const t0=/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d{1,9}[.)]\s+)+/u,n0=/!?\[([^\]]*)\]\([^)]*\)/gu,r0=/\*\*|__|~~|`+/gu,s0=/(?<![\p{L}\p{N}_*])[*_](?=[^\s*_])|(?<=[^\s*_])[*_](?![\p{L}\p{N}_*])/gu,o0=/^[-=*_~`#> ]*$/;function i0(e){return e.replace(t0,"").replace(n0,"$1").replace(r0,"").replace(s0,"")}function bi(e){if(typeof e!="string")return null;for(const t of e.split(Jy)){const n=gs(i0(t));if(n&&!o0.test(n))return n}return null}const ln=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function Jf(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 a0(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 qf(e){return Gy.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function ep(e,t,n){const r=Ln(n?.conversation_label);if(r)return r;if(e==="dm"&&typeof n?.content=="string"){const i="direct message to ";if(n.content.startsWith(i)){const c=n.content.slice(i.length),l=c.indexOf(" in bcv_"),d=l>0?Ln(c.slice(0,l)):null;if(d)return d}}if(e==="channel_create"){const i=ln(Jf(n?.content)),c=Ln(i?.name);if(c)return c}if(e==="channel_create"){const i=Ln(t.name);if(i)return i}const s=qf(e);if(s!=="person"&&s!=="dm")return null;const o=ln(t.to);return Ln(o?.name)}function c0(e,t,n){const r=qf(e);return r==="none"||r==="message"||r==="directory"?{kind:r,label:null}:{kind:r,label:ep(e,t,n)}}function l0(e){if(Array.isArray(e))return e.length;const t=ln(e);if(!t)return null;for(const n of["conversations","items","data"])if(Array.isArray(t[n]))return t[n].length;return null}function d0(e,t){if(!t)return null;const n=Jf(t.content),r=ln(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 s=ln(r.root)?1:0,o=Array.isArray(r.replies)?r.replies.length:null;return o===null&&s===0?null:s+(o??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"?l0(n):null}function u0(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=gs(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 Bo(e,t){const n=e??{},r=gs(n.op)??"",s=ln(t),o=Ky.has(r),i=zy.has(r)||r==="take_up"?bi(n.body)??bi(n.text)??bi(s?.text):null;return{op:r,action:a0(r,n,s),target:o?c0(r,n,s):{kind:"none",label:null},preview:i,count:o&&s?.ok===!0?d0(r,s):null,emoji:r==="react"?gs(n.emoji):null,...o?u0(r,s):{outcome:null,code:null}}}function tp(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&qy.test(n.trim()))return n.trim();return null}const f0=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"]),np=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return f0.has(t)?t:"unknown"},p0={channel_post:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function aa(e){return p0[np(e)]()}function rp(e,t=null){const{kind:n}=e.target,r=e.target.label??Ln(t);return r?n==="channel"&&!r.startsWith("#")?`#${r}`:r:e.op==="shared_history"?"":n==="channel"?v("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?v("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?v("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?v("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function ca(e,t,n,r){const s=tp(t,r),o=!e.target.label&&s&&n?n(s):null,i=rp(e,o),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?i:v("ui.chat.canonical.tool_row.bridge.summary.messages",{target:i,count:e.count}).trim();switch(np(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?v("ui.chat.canonical.tool_row.bridge.target.thread",{target:i}):i;return c(d,e.preview)}case"dm":case"send":case"reply":case"take_up":return c(i,e.preview);case"channels":case"shared_conversations":return e.count===null?"":v("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":v("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(i,e.emoji);case"channel_create":case"ack_working":case"ack_done":return i;default:return e.op}}function h0(e){return e.outcome==="refused"?e.code?v("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):v("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?v("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):v("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const m0=["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 sp(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const r=ln(t);if(!r)return n??null;const{_images:s,...o}=r;return n&&_0(n,o)?n:o}function g0(e){const t=ln(e);if(!t)return null;const n=t.destination_type==="conversation_dm"?"dm":t.state==="created"?"channel_create":"channel_post";return ep(n,{},t)}function op(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:ln(t)?g0(t):n??null}function _0(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 b0={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"},v0=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function ld(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function NC(e,t){const n=e.args??{},r=e.details??null,s=Bo(n,r),o=s.target.label===null&&e.label&&s.target.kind!=="none"&&s.target.kind!=="message"&&s.target.kind!=="directory"?{...s,target:{...s.target,label:e.label}}:s,i=tp(n,r),c=!o.target.label&&i&&t?t(i):null,l=rp(o,c),d=o.outcome==="refused"||o.outcome==="failed",u=e.failed||d?aa(o.action).failed:null,f=u??aa(o.action).settled,h=ca({...o,preview:null,emoji:null},n,t,r),g=o.target.label??Ln(c)??v("ui.chat.canonical.tool_row.bridge.fallback.teammate"),y=o.op==="dm"?v("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:g}):h?v("ui.chat.canonical.tool_row.bridge.detail.headline.target",{verb:f,target:h}):f,b=[n.body,n.text,r?.text].find(S=>typeof S=="string"&&S.trim()!==""),_=typeof r?.seq=="number"?r.seq:null,p=ld(r?.error),R=(o.target.kind==="channel"||o.target.kind==="dm")&&l?l:v("ui.chat.canonical.tool_row.bridge.fallback.conversation"),k=p?p.replace(v0,(S,x)=>x.toLowerCase()==="bcv"?R:"…"):null,O=o.outcome==="refused"||o.outcome==="failed"?k&&o.code?v(o.outcome==="refused"?"ui.chat.canonical.tool_row.bridge.detail.outcome.refused":"ui.chat.canonical.tool_row.bridge.detail.outcome.failed",{code:o.code,error:k}):k:o.outcome==="unconfirmed"?k:r?.ok===!0&&_!==null?v("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:_}):null,L=[],P=new Set,T=(S,x)=>{const N=ld(x);N===null||P.has(S)||(P.add(S),L.push({key:S,value:N}))};for(const S of m0)T(S,r?.[S]);p&&p!==k&&T("error",p);for(const[S,x]of Object.entries(b0))T(x,n[S]);const m=typeof r?.content=="string"&&r.content||e.output||null,w=m&&m.trim()===p?null:m;return{tokens:o,summary:ca(o,n,t,r),failedVerb:u,failureWord:h0(o),headline:y,body:b??null,outcome:O,internals:L,raw:w}}const y0=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),w0=new Set(["true","yes","y","t","on","1"]),k0={hub:{steps:e=>{const t=_r(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=_r(e);return t!==null&&t>0?`· ${lp(t/1e3)}`:""}}};function _r(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 dd="mcp__",S0=/^\/(?:Users|home)\/[^/]+\//,E0=/\s+/;function A0(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(S0,"~/")}function wt(e){return typeof e=="string"?A0(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function R0(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function I0(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(E0).filter(Boolean).join(" ")||"?"}function T0(e){return[R0(e),wt(I0(e))||"?",wt(e.message)].filter(Boolean).join(" · ")}const x0=new Set(["delivered","mailbox","unconfirmed","failed"]);function C0(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:r}=Bo({op:n},t);return r==="inbox_only"?"inbox_only":r==="awaiting_acceptance"?"awaiting_acceptance":r==="unconfirmed"?"unconfirmed":null}function O0(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return C0(e);const n=e.delivery;if(!n||typeof n!="object")return null;const r=n.state;return typeof r=="string"&&x0.has(r)?r:null}function ip(e,t,n){return!e||typeof e!="object"?t??null:O0(e,n)}function P0(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 M0=["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 j0(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],s=t[n];if(!(!!r&&typeof r=="object")||!(!!s&&typeof s=="object")){if(r!==s)return!1;continue}const c=r,l=s;if(c.message!==l.message||c.timestamp!==l.timestamp)return!1}return!0}const $0=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function D0(e,t){return e===t?!0:!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return!n||typeof n!="object"||!s||typeof s!="object"?n===s:$0.every(o=>o==="cost"?n.cost?.basis===s.cost?.basis:n[o]===s[o])})}function N0(e,t){for(const n of M0){const r=e[n],s=t[n];if(n==="artifacts"){if(!D0(r,s))return!1;continue}if(n==="cost"){const o=i=>i&&typeof i=="object"?i.basis:void 0;if(o(r)!==o(s))return!1;continue}if(n==="log_lines"){if(!j0(r,s))return!1;continue}if(r!==s)return!1}return!0}function la(e,t){const n=P0(e);return n?t&&N0(n,t)?t:n:t??null}const L0={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},U0={mailbox:"In their mailbox. The wake got no answer, so they will read it on their next turn.",unconfirmed:"No wake answer and not yet in their transcript — it may still arrive. Check before resending."},F0={mailbox:"Delivered to their mailbox. The wake got no answer, so they will read the message on their next turn. Do not send it again.",unconfirmed:"Not confirmed: there was no answer and the message is not in their transcript. It may still arrive, so check before resending.",failed:"Nothing was delivered. Fix the cause named below, or retry the send."},B0={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function ap(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const Is=e=>e.trim().toLowerCase()==="bridge";function LC(e,t=""){return e?e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&Is(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):L0[e]??null:null}function UC(e,t){return e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&Is(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function FC(e,t=""){if(e)return e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&Is(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):U0[e]}function BC(e,t=""){return e?e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&Is(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):B0[e]??null:null}function HC(e,t=""){return e?e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&Is(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):F0[e]??null:null}function WC(e){return ap(e)?"partial":null}function GC(e){return e==="failed"?"Attempted":null}function zC(e,t){return e!==!0?!1:!ap(t)}function ud(e){const t=_r(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:wt(e.session)||wt(e.target)||"?"}function H0(e){const t=wt(e.query);if(t){const i=_r(e.steps);return i!==null&&Number.isInteger(i)&&i>=0?`search ${t} · ${i} around`:`search ${t}`}const n=_r(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=_r(e.head);if(r!==null&&Number.isInteger(r)&&r>=0)return`first ${r}`;if(e.digest===!0)return"digest";const s=wt(e.before_id);if(s)return`before ${s}`;const o=wt(e.around_id);return o?`around ${o}`:""}function W0(e){const t=V0(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 ud(e);if(t==="peek")return[ud(e),H0(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 KC(e,t,n,r){const s=e.trim();if(s.toLowerCase()==="bridge")return ca(Bo(t,n),t,r,n);if(!t)return s;if(s==="send")return T0(t)||s;if(s.toLowerCase()==="sessions"){const c=W0(t);if(c!==null)return c||s}const o=Z0(s)?Object.entries(t).filter(([c])=>!dp.has(c)):Object.entries(t);let i=o.filter(([c])=>y0.has(c)).map(([,c])=>wt(c)).filter(Boolean);if(i.length===0){const c=k0[s.toLowerCase()];i=o.map(([l,d])=>c?.[l]?.(d)||wt(d)).filter(Boolean)}return i.slice(0,2).join(" ")||s}function cp(e){const t=e.trim();if(!t.toLowerCase().startsWith(dd))return t;const n=t.slice(dd.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function G0(e,t){return e===t||e===cp(t)}const z0=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,K0="… ";function VC(e,t=!1){if(!e||t)return null;for(const n of e.split(`
23
+ `)){const r=n.trim();if(r&&!z0.test(r))return`${K0}${r.slice(0,160)}`}return null}function lp(e){const t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;if(t<3600){const s=Math.floor(t/60),o=t%60;return o===0?`${s}m`:`${s}m${o}s`}if(t<86400){const s=Math.floor(t/3600),o=Math.floor(t%3600/60);return o===0?`${s}h`:`${s}h${o}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 ZC(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`:lp(t)}function fd(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 YC(e){return e<1024?`${e} B`:e<1024*1024?`${fd(e/1024)} KB`:`${fd(e/(1024*1024))} MB`}function pd(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const hd={read:"read",glob:"read",grep:"read",web_fetch:"read",web_read:"read",web_search:"read",browser:"read",lsp:"read",list_variables:"read",read_variable:"read",write:"mutate",edit:"mutate",bash:"exec",eval:"exec",console:"exec",task:"meta",agent:"meta",team:"meta",hub:"meta",todo:"meta",send:"meta",wake:"meta",ask:"meta",wait:"meta",jobs:"meta",secret:"meta",network:"meta",project:"meta",team_delete:"meta",project_delete:"meta",sessions:"meta",bridge:"meta"};function QC(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(hd,t)?hd[t]:"plain"}function V0(e){if(!e)return"";for(const t of dp){const n=e[t];if(typeof n=="string"&&n.trim()){const r=n.trim().toLowerCase(),s=e.remove,o=s===!0||s===1||typeof s=="string"&&w0.has(s.toLowerCase());return r==="milestone"&&o?"milestone-remove":t==="op"&&(r==="react"||r==="ack")?Bo(e).action:r}}return""}const dp=new Set(["op","action","method"]),Z0=e=>Object.prototype.hasOwnProperty.call(up,e.trim().toLowerCase()),Y0={bash:{settled:"Ran",running:"Running"},eval:{settled:"Ran Python",running:"Running Python"},read:{settled:"Read",running:"Reading"},write:{settled:"Wrote",running:"Writing"},edit:{settled:"Edited",running:"Editing"},glob:{settled:"Listed",running:"Listing"},grep:{settled:"Searched",running:"Searching"},web_search:{settled:"Searched the web",running:"Searching the web"},web_fetch:{settled:"Fetched",running:"Fetching"},web_read:{settled:"Read",running:"Reading"},browser:{settled:"Browsed",running:"Browsing"},list_variables:{settled:"Listed variables",running:"Listing variables"},read_variable:{settled:"Read variable",running:"Reading variable"},ask:{settled:"Asked",running:"Asking"},send:{settled:"Sent",running:"Sending"},wait:{settled:"Waited for jobs",running:"Waiting for jobs"},team_delete:{settled:"Deleted team",running:"Deleting team"},project_delete:{settled:"Deleted project",running:"Deleting project"},peer:{settled:"Received",running:"Receiving"},task:{settled:"Delegated",running:"Delegating"}},up={agent:{list:{settled:"Listed agents",running:"Listing agents"},show:{settled:"Viewed agent",running:"Viewing agent"},search:{settled:"Searched agents",running:"Searching agents"},install:{settled:"Installed agent",running:"Installing agent"},reset:{settled:"Reset agent",running:"Resetting agent"},create:{settled:"Created agent",running:"Creating agent"},update:{settled:"Updated agent",running:"Updating agent"},sync:{settled:"Synced agents",running:"Syncing agents"}},team:{list:{settled:"Listed teams",running:"Listing teams"},show:{settled:"Viewed team",running:"Viewing team"},create:{settled:"Created team",running:"Creating team"},update:{settled:"Updated team",running:"Updating team"}},hub:{list:{settled:"Listed subagents",running:"Listing subagents"},peek:{settled:"Peeked at",running:"Peeking at"},send:{settled:"Messaged",running:"Messaging"},ask:{settled:"Asked",running:"Asking"},steer:{settled:"Steered",running:"Steering"},pause:{settled:"Paused",running:"Pausing"},cancel:{settled:"Cancelled",running:"Cancelling"},resume:{settled:"Resumed",running:"Resuming"}},secret:{store:{settled:"Stored secret",running:"Storing secret"},retrieve:{settled:"Retrieved secret",running:"Retrieving secret"},list:{settled:"Listed secrets",running:"Listing secrets"},describe:{settled:"Described secret",running:"Describing secret"},update:{settled:"Updated secret",running:"Updating secret"},delete:{settled:"Deleted secret",running:"Deleting secret"}},project:{list:{settled:"Listed projects",running:"Listing projects"},show:{settled:"Viewed project",running:"Viewing project"},create:{settled:"Created project",running:"Creating project"},update:{settled:"Updated project",running:"Updating project"},link:{settled:"Linked session to",running:"Linking session to"},unlink:{settled:"Unlinked session from",running:"Unlinking session from"},milestone:{settled:"Updated milestone",running:"Updating milestone"},"milestone-remove":{settled:"Removed milestone",running:"Removing milestone"}},todo:{view:{settled:"Read todos",running:"Reading todos"},init:{settled:"Updated todos",running:"Updating todos"},add:{settled:"Updated todos",running:"Updating todos"},done:{settled:"Updated todos",running:"Updating todos"},block:{settled:"Updated todos",running:"Updating todos"},drop:{settled:"Updated todos",running:"Updating todos"}},wake:{create:{settled:"Scheduled",running:"Scheduling"},list:{settled:"Listed wakes",running:"Listing wakes"},cancel:{settled:"Cancelled wake",running:"Cancelling wake"}},jobs:{list:{settled:"Listed jobs",running:"Listing jobs"},peek:{settled:"Peeked at",running:"Peeking at"},cancel:{settled:"Cancelled job",running:"Cancelling job"}},network:{status:{settled:"Checked network status",running:"Checking network status"},ls:{settled:"Listed networks",running:"Listing networks"},show:{settled:"Viewed network",running:"Viewing network"},peers:{settled:"Listed network peers",running:"Listing network peers"},log:{settled:"Read network log",running:"Reading network log"},doctor:{settled:"Diagnosed network",running:"Diagnosing network"},init:{settled:"Created network",running:"Creating network"},invite:{settled:"Invited device",running:"Inviting device"},join:{settled:"Joined network",running:"Joining network"},member_rm:{settled:"Removed device",running:"Removing device"},disconnect:{settled:"Left network",running:"Leaving network"},panic:{settled:"Raised panic",running:"Raising panic"}},console:{list:{settled:"Listed consoles",running:"Listing consoles"},create:{settled:"Opened console",running:"Opening console"},status:{settled:"Checked console",running:"Checking console"},read:{settled:"Read console",running:"Reading console"},screenshot:{settled:"Captured console",running:"Capturing console"},input:{settled:"Typed in console",running:"Typing in console"},keys:{settled:"Sent keys",running:"Sending keys"},resize:{settled:"Resized console",running:"Resizing console"},secure:{settled:"Updated secure input",running:"Updating secure input"},close:{settled:"Closed console",running:"Closing console"}},lsp:{definitions:{settled:"Found definition",running:"Finding definition"},references:{settled:"Found references",running:"Finding references"},symbols:{settled:"Listed symbols",running:"Listing symbols"},rename_preview:{settled:"Previewed rename",running:"Previewing rename"}},sessions:{list:{settled:"Listed sessions",running:"Listing sessions"},info:{settled:"Viewed session",running:"Viewing session"},spawn:{settled:"Spawned session",running:"Spawning session"},resume:{settled:"Resumed session",running:"Resuming session"},stop:{settled:"Stopped session",running:"Stopping session"},peek:{settled:"Peeked at session",running:"Peeking at session"}}};function Q0(e,t){const n=e.trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(n==="bridge"){const{settled:i,running:c}=aa(r);return{settled:i,running:c,named:!0}}const s=r?up[n]?.[r]:void 0;if(s)return{...s,named:!0};const o=Y0[n];return o?{...o,named:!0}:{settled:v("ui.chat.canonical.tool_row.generic_verb.settled"),running:v("ui.chat.canonical.tool_row.generic_verb.running"),named:!1}}function XC(e,t,n,r,s="",o=null){const i=Q0(e,s),c=G0(t,e)?n??"":t;return{verb:r?i.running:o??i.settled,object:i.named?c:[cp(e),c].filter(Boolean).join(" ")}}const X0=new Set(["write","edit"]);function J0(e){return X0.has(e.trim().toLowerCase())}function JC(e){return J0(e.toolName)&&e.diff!==null&&!e.isError}function fp(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 q0(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 pp(e,t){return e===null||q0(e,t)?t:e}function hp(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:pd(n.added),removed:pd(n.removed)}}function ew(e){return e.length>=2&&da(e[0])==="---"&&da(e[1])==="+++"?e.slice(2):e.slice()}const tw=/\s+$/;function da(e){return e.replace(tw,"")}function nw(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const rw=40;function qC(e){const t=ew(e),n=t.slice(0,rw);return{lines:n.map(r=>{const s=da(r);return{text:s,marker:s.slice(0,1),kind:nw(s)}}),hidden:t.length-n.length}}function e1(e){return`… ${e} more diff line${e===1?"":"s"}`}const sw=`Continue working toward this goal:
25
+
26
+ `,ow=`
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.`,iw=`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.`,[aw="",cw=""]=iw.split("{goal}"),lw="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.",dw="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.",uw="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 mp(e){const t=e.trim();return t===lw||t===dw||t===uw||t.startsWith(sw)&&t.endsWith(ow)||t.startsWith(aw.trim())&&t.endsWith(cw.trim())}const fw=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function pw(e,t){const n=t?.match(fw)?.[0]??null;if(!e||typeof e!="object")return n;const r=e,s=r.cost_usd,o=r.billing_basis;if(typeof s!="number"||!Number.isFinite(s)||s<0)return n;if(o!=="billed"&&o!=="estimated")return null;const i=Number(s.toFixed(4));return`Cost ${i===0&&s>0?"<$0.0001":`$${i}`} (${o}).`}function gp(e){return e}const ua="supplement_v1",hw="superseded",wo=120,lc=480,mw=20,t1=500,gw=10,_w=["outside","sensitive","missing","too-large"];function _p(e,t){const n=[];let r=0;if(Array.isArray(e))for(const o of e.slice(0,gw)){if(!o||typeof o!="object")continue;const i=o,c=i.reason;if(!_w.includes(c)){r+=1;continue}n.push({name:typeof i.name=="string"?i.name:"",reason:c})}const s=typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;return{withheld:n,withheldMore:s+r}}function dc(e){return`supplement:${e}`}function bw(e){const t=e.payload??{};if(String(t.custom_type??"")!==ua)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?dc(r):null}function ko(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function vw(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:ko(t.size_bytes)??0,mtime:ko(t.mtime)??0,why:typeof t.why=="string"?t.why:"",...t.pinned===!0?{pinned:!0}:{}}}function bp(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=vw(n);r&&t.push(r)}return t}function yw(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!wp(n))return null;const r=ko(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?wo:Math.min(lc,Math.max(wo,Math.round(r)))}}function vp(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=yw(n);r&&t.push(r)}return t}function ww(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return wp(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:ko(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 yp(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=ww(n);r&&t.push(r)}return t}const kw=/^[a-f0-9]{32}$/,Sw=/\s+/,Ew=/\.0$/;function wp(e){return typeof e=="string"&&kw.test(e)}const Aw={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function md(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 n1(e,t){const n=e.state;if(e.error===hw||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?Aw[r]??r:r}const r1="Preparing highlights…",s1="Highlights cancelled",o1="Couldn't prepare highlights",i1="Adjust…",a1="Cancel",c1="Retry",Rw=64,Iw={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 l1(e){return typeof e=="string"&&e?Iw[e]??"":""}function vi(e){return typeof e!="string"?"":e.replace(Zf,"").split(Sw).filter(Boolean).join(" ")}function d1(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function Tw(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return`${Math.trunc(e)} B`;const t=[["KB",1024],["MB",1024**2],["GB",1024**3]];for(const[n,r]of t)if(e<r*1024||n==="GB")return`${(e/r).toFixed(1).replace(Ew,"")} ${n}`;return""}function u1(e){const t=vi(e.name)||vi(e.path),n=vi(e.path);return{name:t,path:n===t?"":n,size:Tw(e.sizeBytes)}}function yi(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function f1(e,t,n=e){return t?`Hide ${yi(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${yi(e,"graphic")}`:`Show ${yi(e,"graphic")}`}function p1(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const xw="supplement",Cw=1,Ow=["ready","resize","error","pong"],Pw=["resize","error","pong"],Mw=64,uc=300,h1=5e3,m1=2e4;function g1(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==xw||n.v!==Cw)return null;const r=n.t;if(typeof r!="string"||!Ow.includes(r))return null;const s=r;if(Pw.includes(s)&&(!t||t.length>Mw||n.n!==t))return null;if(s==="error"){const o=n.msg;if(typeof o!="string"||o.length>uc)return null}if(s==="resize"){const o=n.h;if(typeof o!="number"||!Number.isFinite(o)||o<0)return null}return{lo:"supplement",v:1,t:s,...typeof n.n=="string"?{n:n.n}:{},...typeof n.h=="number"?{h:n.h}:{},...typeof n.msg=="string"?{msg:n.msg}:{}}}function _1(){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 jw=["--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"],$w=120;function Dw(e=typeof document>"u"?null:document.documentElement){if(!e||typeof getComputedStyle!="function")return{mode:"dark",vars:{}};const t=getComputedStyle(e),n={};for(const s of jw){const o=t.getPropertyValue(s).trim();o&&(n[s]=o.slice(0,$w))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function b1(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(Dw()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function v1(e){return`data:text/html;base64,${Nw(e)}`}function Nw(e){const t=Lw(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let s=0;s<t.length;s+=3){const o=t[s]??0,i=t[s+1]??0,c=t[s+2]??0;r+=n[o>>2],r+=n[(o&3)<<4|i>>4],r+=s+1<t.length?n[(i&15)<<2|c>>6]:"=",r+=s+2<t.length?n[c&63]:"="}return r}function Lw(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 y1(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function Uw(e){return Math.min(lc,Math.max(wo,e.heightHint))}function Fw(e){return Math.min(lc,Math.max(wo,e))}function w1(e,t,n){let r=0;const s=[];for(let o=0;o<e.length;o+=1){const i=e[o],c=n?.get(i.attachment),l=c!==void 0?Fw(c):Uw(i);if(o>0&&(!s.every(u=>n?.get(u.attachment)!==void 0)||r+l>t))break;r+=l,s.push(i)}return{visible:s,hidden:e.slice(s.length)}}const Bw=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,kp=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,Hw=/kind=(auth|quota)\b/,Ww=/kind=(transient|timeout)\b/;function Sp(e){const t=i=>typeof i=="string"&&Bw.test(i)&&!i.includes("://")?i:"",n=t(e.model),r=Array.isArray(e.attempts)?e.attempts.map(t).filter(Boolean).slice(0,8):void 0,s=Array.isArray(e.detail)?e.detail.filter(i=>typeof i=="string"&&(kp.test(i)||i==="prepared:unsupported")).slice(0,8):void 0,o=typeof e.cause=="string"?e.cause.slice(0,Rw):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...s?{detail:s}:{},...o?{cause:o}:{}}}function k1(e){if(!kp.exec(e))return"";const n=e.split(" "),r=n[1].replace(":",""),s=n[3].slice(7),o=n[4].slice(5);return`Attempt ${r}: ${o}${s==="None"?"":` (HTTP ${s})`}`}function S1(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return Hw.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":Ww.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 Gw(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return Ep(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:bp(e.files),..."withheld"in e||"withheld_more"in e?_p(e.withheld,e.withheld_more):{}}:{},...n==="done"?{components:vp(e.components),sounds:yp(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,uc)}:{},...Sp(e),live:!Ap(n)}:null}function zw(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!Ep(n))return null;const r=typeof e.files_more=="number"&&Number.isInteger(e.files_more)&&e.files_more>=0?e.files_more:0,s=Array.isArray(e.more)?e.more.filter(i=>typeof i=="string").slice(0,mw):[];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:bp(e.files),filesMore:r,more:s,components:vp(e.components),sounds:yp(e.sounds),..._p(e.withheld,e.withheld_more),...Sp(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,uc)}:{}}}function gd(e,t,n){const r=zw(t);if(!r)return null;const s=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return Rp(s,r,e)}function Ep(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Ap(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Kw(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.path===s.path&&n.name===s.name&&n.kind===s.kind&&n.sizeBytes===s.sizeBytes&&n.mtime===s.mtime&&n.why===s.why&&(n.pinned??!1)===(s.pinned??!1)})}function Vw(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.attachment===s.attachment&&n.title===s.title&&n.source===s.source&&n.mime===s.mime&&n.heightHint===s.heightHint})}function Zw(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.attachment===s.attachment&&n.mime===s.mime&&n.title===s.title&&n.durationS===s.durationS&&n.origin===s.origin&&(n.path??"")===(s.path??"")&&(n.pinned??!1)===(s.pinned??!1)})}function Yw(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 Rp(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&md(t.state)<md(e.state)))return null;const r=!e||t.version>e.version,s=t.files!==void 0?t.files:e?.files??[],o=t.components!==void 0?t.components:e?.components??[],i=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??""),g=t.dismissed??(r?!1:e?.dismissed??!1),y=t.live!==void 0?t.live===!0?!0:Ap(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:dc(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:Kw(s,e?.files??[])?e?.files??[]:s,filesMore:d,more:Qw(u,e?.more??[])?e?.more??[]:u,components:Vw(o,e?.components??[])?e?.components??[]:o,sounds:Zw(i,e?.sounds??[])?e?.sounds??[]:i,withheld:Yw(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:g,live:y}}function Qw(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const E1=e=>e.kind===void 0||e.kind==="image",$t={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function Ip(e){return e==="skipped"||e==="aborted"}function _d(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function bd(e,t,n,r){return _d(n.args)??(r?.kind==="tool"?r.args:null)??_d(e.argsByCall.get(t)?.arguments)}function Tp(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function xp(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 zs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function zt(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!Tp(n)&&xp(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Fn(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Qr;const s=[];for(const o of r){const i=xp(o);if(o.type==="document"||i===null&&!Tp(o))continue;const c={id:`${t}:${s.length}`,data:typeof o.data=="string"&&o.data?o.data:null,attachment:typeof o.attachment=="string"&&o.attachment?o.attachment:null,mimeType:typeof o.content_type=="string"&&o.content_type||typeof o.mime_type=="string"&&o.mime_type||"image/png"};i!==null&&(c.kind=i,c.width=zs(o.width),c.height=zs(o.height),c.sizeBytes=zs(o.size_bytes),c.durationS=zs(o.duration_s),c.name=typeof o.name=="string"&&o.name?o.name:null,c.sourceUrl=typeof o.source_url=="string"&&o.source_url?o.source_url:null),s.push(c)}return s.length===0?Qr:n&&fc(n,s)?n:s}const Qr=[],fa=[];function Cp(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:fa;const s=[];for(const o of r){const i=typeof o.filename=="string"&&typeof o.mime_type=="string"&&typeof o.attachment=="string"&&o.type===void 0;o.type!=="document"&&!i||s.push({id:`${t}:doc:${s.length}`,attachment:typeof o.attachment=="string"&&o.attachment?o.attachment:null,filename:typeof o.filename=="string"&&o.filename?o.filename:o.name??"Attached file",mimeType:o.mime_type??"application/octet-stream",path:typeof o.path=="string"&&o.path?o.path:null,storedPath:typeof o.stored_path=="string"&&o.stored_path?o.stored_path:null,bytes:typeof o.bytes=="number"?o.bytes:0,...o.injection?{injection:o.injection}:{}})}return s.length===0?n?.length?n:fa:n&&Xw(n,s)?n:s}function Xw(e,t){return e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.id===s.id&&n.attachment===s.attachment&&n.filename===s.filename&&n.mimeType===s.mimeType&&n.path===s.path&&n.storedPath===s.storedPath&&n.bytes===s.bytes&&n.injection===s.injection})}function vd(e){let t=0;for(const n of e)n.kind!==void 0&&(t+=1),n.width!=null&&(t+=1),n.height!=null&&(t+=1),n.sizeBytes!=null&&(t+=1),n.durationS!=null&&(t+=1),n.name!=null&&(t+=1),n.sourceUrl!=null&&(t+=1);return t}function Op(e,t,n){if(t.length===0)return e;if(e.length===0||fc(e,t))return t;const r=vd(e),s=vd(t);return r!==s?r>s?e:t:n==="incoming"?e:t}function Jw(e,t){return Op(e,t,"incoming")}function fc(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 qw(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const dn=new Set;function pc(e){return e.kind==="user"&&e.provisional===!0}function Pp(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{pc(n)&&r<t&&(t=r)}),t}function _s(e,t=dn,n){if(n?.journalMode)return $f(n,e).map(gp);const r=e.map((i,c)=>({record:i,position:c})),s=Pp(e),o=i=>pc(i.record)||i.position>s&&!t.has(i.record.id);return r.sort((i,c)=>{const l=o(i),d=o(c);return l!==d?l?1:-1:l?i.position-c.position:i.record.ts!==c.record.ts?i.record.ts-c.record.ts:i.position-c.position}).map(i=>i.record)}function ek(e,t,n){if(!n||t<=0)return dn;let r=null;for(const s of e){if(!pc(s)||!(t>s.ts))continue;let o=!1,i=!1;for(const c of e)if(c.ts>s.ts?o=!0:c.ts<s.ts&&_c(c)&&(i=!0),o&&i)break;o&&i&&(r??=new Set,r.add(s.id))}return r??dn}function tk(e){const{provisional:t,...n}=e;return n}function pa(e,t){const n=e,r=t,s=Object.keys(n);if(s.length!==Object.keys(r).length)return!1;for(const o of s)if(n[o]!==r[o]){if(o==="images"){const i=n[o],c=r[o];if(Array.isArray(i)&&Array.isArray(c)&&fc(i,c))continue}if(o==="frame"){const i=n[o],c=r[o];if(i!==void 0&&c!==void 0&&i.epoch===c.epoch&&i.seq===c.seq)continue}if(o==="skill"){const i=n[o],c=r[o];if(i!==void 0&&c!==void 0&&nk(i,c))continue}return!1}return!0}function nk(e,t){return e.name===t.name&&e.token===t.token&&e.request===t.request&&e.purpose===t.purpose&&e.body===t.body}function je(e,t){const n=e.index.get(t.id);if(n!==void 0){const o=e.records[n];if(pa(o,t))return e;const i=e.records.slice();if(i[n]=e.journalMode?{...t,...o.sourceEntryId?{sourceEntryId:t.sourceEntryId??o.sourceEntryId}:{},...o.sourceAdmissionAnchor&&!t.sourceAdmissionAnchor?{sourceAdmissionAnchor:o.sourceAdmissionAnchor}:{},...o.sourcePrecedes&&!t.sourcePrecedes?{sourcePrecedes:o.sourcePrecedes}:{},...o.journalGeneration?{journalGeneration:t.journalGeneration??o.journalGeneration,journalSeq:t.journalSeq??o.journalSeq}:{}}:t,!e.journalMode)return{...e,records:i};const c=_s(i,dn,e);return{...e,records:c,index:St(c)}}const r=e.journalMode?_s([...e.records,t],dn,e):[...e.records,t],s=St(r);return{...e,records:r,index:s}}function hc(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 wi(e,t){const n=`tool:${t}`,r=e.index.get(n);if(r===void 0)return e;const s=e.records[r];return s.kind==="tool"&&(s.phase==="composing"||s.phase==="queued")?hc(e,o=>o.id===n):e}function rk(e,t,n){const r=e.index.get(`tool:${t}`);if(r===void 0)return e;const s=e.records[r];if(!(s.kind==="tool"&&(s.phase==="composing"||s.phase==="queued")))return e;const o=e.records.slice();return o[r]=n,{...e,records:o,index:St(o)}}const sk=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function Mp(e){const t=e.trim()||"compaction did not run";return{text:`Compaction did not run${t.includes(":")?" — ":": "}${t}`,level:t.startsWith("compaction failed")?"error":"warning"}}function ok(e,t){const n=xd(e),r=xd(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const jp="Context compacted",ik=12e4;function $p(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,s=new Set,o=new Map,i=(d,u)=>{r.add(u.id),s.add(d.id),o.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&&i(d,u)}const l=[];for(const d of c)if(!s.has(d.id))for(const u of n){if(u.before!==void 0)continue;const f=Math.abs(u.ts-d.ts);f>ik||l.push({live:d,durable:u,distance:f})}l.sort((d,u)=>d.distance-u.distance);for(const{live:d,durable:u}of l)s.has(d.id)||r.has(u.id)||i(d,u);return s.size===0?e:e.filter(d=>!s.has(d.id)).map(d=>{const u=o.get(d.id);return u===void 0||d.kind!=="compaction"&&d.kind!=="notice"||u===d.text?d:{...d,text:u}})}function ak(e){const t=$p(e.records);return t===e.records?e:{...e,records:t,index:St(t)}}const ck="peer_message",lk="ask_response",dk="ask_timeout",Dp="Completed — runtime retired/disposed",Np="Retired for an update — a turn was in flight and was cut; its earlier output is kept",uk="wake_prompt",fk="session_mcp_unavailable",pk=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),hk=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,yd=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,mk=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."]),Lp=/^\[[^\]]{1,32}\]\s*/,So="Reason:",gk=/[\n;,(]| [—–] /,_k=/^\d+\.$/,bk=/[A-Z]/,vk=/\s/,Xr=160;function no(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",...Ek(t,n)};let r;return e===fk?r=yk(t):pk.has(e)?r=kk(t.trim().replace(Lp,"")):r=Ak(t),{level:"info",category:null,provider:null,...r}}function yk(e){const t=e.trim().replace(Lp,"").split(`
33
+ `).map(c=>c.trim()),n=t[0]??"",r=t[1]?.startsWith(So)?t[1]:null,s=t.slice(r?2:1).filter(Boolean).join(`
34
+ `),o=(r?`${n} ${r}`:n).trim();if(o.length<=Xr)return{headline:o,detail:s||null};const i=r===null?null:wk(r);if(i!==null){const c=(f,h)=>`${So} ${[f,h].filter(Boolean).join(" ")}`,l=f=>[f,s].filter(Boolean).join(`
35
+ `)||null,d=`${n} ${c(i.leading,i.clause)}`;if(d.length<=Xr)return{headline:d,detail:l(i.rest)};const u=`${n} ${c("",i.clause)}`;if(u.length<=Xr)return{headline:u,detail:l([i.leading,i.rest].filter(Boolean).join(" "))}}return{headline:Fp(o),detail:[r,s].filter(Boolean).join(`
36
+ `)||null}}function wk(e){const t=e.startsWith(So)?e.slice(So.length):e,n=t.indexOf("/mcp");if(n<0)return null;const r=t.slice(n),s=r.search(gk),o=(s<0?r:r.slice(0,s)).trim();return o?{leading:t.slice(0,n).trim(),clause:o,rest:(s<0?"":r.slice(s)).trim()}:null}function kk(e){const t=e.trim(),n=Sk(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 Sk(e){for(let t=0;t<e.length-1;t++)if(".!?…".includes(e[t])&&vk.test(e[t+1])&&!_k.test(e.slice(0,t+1))&&bk.test(e.slice(t+1).trimStart()[0]??""))return t+1;return-1}function Ek(e,t){const n=e.split(`
37
+ `),r=n[0].match(hk),o=(typeof t.raw=="string"?t.raw.trim():"")||(r?n[0].slice(r[0].length):n[0]).trim()||e.trim(),i=n.slice(1).join(`
38
+ `).trim();return{provider:(r?.[1]??"").trim()||null,category:(r?.[2]??"").trim()||null,headline:o,detail:i||null}}function Up(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 s=n.body;if(typeof s!="string"||!s.trim())return null;const o={...n};for(const i of["expects_reply","steer"])typeof o[i]!="boolean"&&(o[i]=null);for(const i of["label","job_id"])i in o&&typeof o[i]!="string"&&delete o[i];return o}function Ak(e){const t=Rk(e),n=e.split(`
39
+ `).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function Rk(e){const t=e.split(`
40
+ `).map(c=>c.trim()).filter(Boolean),n=c=>!yd.test(c)&&!Ik(c),r=t.find(n),s=t.find(c=>yd.test(c)&&!c.startsWith("</"));let o=r??s??e.trim();const i=t.indexOf(o);if(i>=0&&o.endsWith(":")){const c=t.slice(i+1).find(n);c&&(o=`${o} ${c}`)}return Fp(o)}function Ik(e){return mk.has(e.replace(/\s+/g," ").trim().toLowerCase())}function Fp(e){const t=e.trim();if(t.length<=Xr)return t;const n=t.slice(0,Xr),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const Tk="harness_injected",Bp=e=>!e||typeof e!="object"?!1:e[Tk]===!0;function Hp(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function Wp(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const xk="ask";function wd(e,t){return t===!0&&String(e??"")===xk}function Ck(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function Gp(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const i=t?.kind==="compaction"?t.text:jp,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:r,text:i,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const i=n.details??{},c=Mp(String(i.detail??""));return{kind:"notice",id:e.id,ts:r,text:c.text,level:c.level}}if(e.type==="custom"&&n.custom_type==="completion_attention"){const i=n.details??{};if(typeof i.anchor=="string"){if(i.kind==="closed")return{kind:"notice",id:i.anchor,ts:r,complete:!0,text:Dp,level:"info"};if(i.kind==="retired")return{kind:"notice",id:i.anchor,ts:r,complete:!0,text:Np,level:"warning"};if(i.kind==="error"||i.kind==="interrupted")return{kind:"notice",id:i.anchor,ts:r,complete:!0,text:i.kind==="error"?"Stopped with an error":"Interrupted",level:i.kind==="error"?"error":"warning"}}}if(e.type==="custom"&&n.custom_type===ua){const i=n.details??{};return gd(r,i,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const i=String(n.custom_type??"");if(sk.has(i))return null;const c=n.details??{};if(i==="hub_message"){const u=ia(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&_i(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:i,text:u.envelope,attribution:"user",...no(i,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(h=>f[h]===u[h])?f:u,images:Fn(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(i===ck){const{body:u,sender:f}=Xf(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&_i(t.sender,f)?t.sender:f}}if(i===uk){if(By(c)||Hy(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(i===lk){const u=c.answers,f={};if(u&&typeof u=="object")for(const[y,b]of Object.entries(u))f[String(y)]=Array.isArray(b)?b.map(_=>String(_)):[];const h=c.questions,g=Array.isArray(h)?h.flatMap(y=>{if(!y||typeof y!="object")return[];const b=y;return[{id:String(b.id??""),question:String(b.question??""),secret:b.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:r,askId:String(c.ask_id??""),status:String(c.status??"answered"),by:c.by&&typeof c.by=="object"?c.by:null,reason:typeof c.reason=="string"?c.reason:null,questions:g,answers:f,secretLost:c.secret_lost===!0}}if(i===dk){const u=Number(c.waited_s);return{kind:"ask_timeout",id:e.id,ts:r,askId:String(c.ask_id??""),waitedS:Number.isFinite(u)&&u>0?u:0,urgent:c.urgent===!0}}if(i===ua)return gd(r,c,t);const d=(i==="audio_settle_v1"&&c.terminal===!0?pw(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:i,text:d,...i==="team_bridge_message"?{bridgeReceipt:Wy(c)}:{},attribution:n.attribution??"system",...no(i,d,c)}:null}const o=String(n.role??"");if(o==="user"){const i=Up(n.provider_payload);if(i){const u=ia({...i,text:zt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&_i(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",...no("hub_message",u.envelope||u.body,{...i,text:zt(n)}),receipt:f&&Object.keys(u).every(g=>f[g]===u[g])?f:u,images:Fn(n,e.id,h)}}}if(Bp(n.provider_payload))return null;const c=zt(n);if(mp(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=Fo(c),d=Cp(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Fn(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(o==="assistant"){const i=Array.isArray(n.tool_calls)?n.tool_calls:[],c=zt(n);return!c&&i.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:i.length>0,stopReason:n.stop_reason??null,error:!!n.is_error}}if(o==="tool"){const i=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(Wp(l))return null;const d=Ip(l.__fault);return{kind:"tool",id:`tool:${i}`,ts:r,toolCallId:i,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:zt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Fn(n,`tool:${i}`,t?.kind==="tool"?t.images:void 0),...hp(c.details,t?.kind==="tool"?t:null),diff:pp(fp(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:ip(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:sp(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:op(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:la(c.details,t?.kind==="tool"?t.details??null:null)}}return null}function Ok(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 Pk=/^(?:tool|compaction|local):/;function Mk(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)&&!Pk.test(t.id))return t.id}return null}function jk(e,t){const n=bw(t);if(n)return e.records[e.index.get(n)??-1]}function mc(e){const t=$f(e,e.records);if(t===e.records)return e;const n=t.map(gp);return{...e,records:n,index:St(n)}}const bs=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function zp(e,t,n,r){const s={...e,sourceEntryId:t,journalSeq:r,journalGeneration:n};if(e.kind==="user"&&(e.provisional===!0||e.local===!0)){const{provisional:o,local:i,...c}=s;return c}return s}function $k(e){const t=new Set,n=new Set;for(const r of e.records){const s=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof s!="string"||s.length<1||s.length>128||(t.add(s),r.journalGeneration===e.journalGeneration&&bs(r.journalSeq)&&n.add(s))}return{carried:t,admitted:n}}function gc(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function kd(e,t){const n=new Set;for(const i of t)typeof i=="string"&&i.length>0&&i.length<=128&&n.add(i);if(n.size===0)return e;let r=!1;const s=e.records.map(i=>{const c=i.sourceEntryId??(i.kind==="tool"||i.kind==="supplement"?null:i.id);if(c===null||!n.has(c))return i;const l=gc(i);return l!==i&&(r=!0),l});let o=r?{...e,records:s}:e;return o=Kp(o,n),o}function Kp(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=$k(e),s=e.orderRevision??0,o=e.journalBodyOwed;let i=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)||(i||(i=new Map(o??[])),i.set(d,s),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return i?{...e,journalBodyOwed:i,...l?{journalSourceVoid:l}:{}}:e}function Eo(e,t,n){const r=n&&e.journalSourceUnavailable===!0?{...e,journalSourceUnavailable:void 0}:e;if(t.length===0)return r;const s=r.journalBodyOwed;let o=null;const i=r.journalSourceVoid;let c=null;for(const l of t)s?.has(l)&&(o||(o=new Map(s)),o.delete(l)),i?.has(l)&&(c||(c=new Set(i)),c.delete(l));return!o&&!c?r:{...r,...o?{journalBodyOwed:o}:{},...c?{journalSourceVoid:c}:{}}}function Ts(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function Vp(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function Dk(e,t,n){let r=Sr(e,t,t.entries.map(o=>({id:o.id,journal_seq:o.journal_seq,role:o.payload?.role,tool_call_id:o.payload?.tool_call_id})),!0,n);for(const o of t.entries)r=ec(r,{...o.payload,id:o.id});const s=Ts(r,!1);return mc(s.journalPeerSource===void 0&&!s.journalBodyOwed&&!s.journalSourceVoid&&s.journalSourceUnavailable===void 0?s:{...s,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function Sd(e,t,n){let r=Sr(e,t,(t.entries??[]).map(o=>({id:o.id,journal_seq:o.journal_seq,role:o.payload?.role,tool_call_id:o.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=Ts(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const o=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];o.length>0&&(r=Kp(r,o));const i=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(i.length>0){r=Eo(r,i,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of i)c.add(l);r={...r,journalSourceVoid:c}}}return r=Vp(r,t),mc(r)}function Nk(e,t,n,r){let s=Sr(e,t,[],!1,n,{peer:!0});s=Ts(s,!0);const o=s.journalBodyOwed,i=g=>r!==void 0&&(o?.get(g)??Number.NEGATIVE_INFINITY)>r,c=t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===s.journalGeneration,l=c?[...t.entries??[],...t.dependency_entries??[]]:[],d=[];let u=s.records,f=s.index;if(l.length>0){const g=new Map;for(const y of l){if(typeof y.id!="string"||y.id===""||i(y.id))continue;const b=`tool:${String(y.payload?.tool_call_id??"")}`,_=f.get(y.id)??f.get(b),p=_===void 0?void 0:u[_];if(!p)continue;let R=Gp(y,p);R&&(R={...R,sourceEntryId:y.id,...p.sourcePrecedes?{sourcePrecedes:p.sourcePrecedes}:{}},bs(y.journal_seq)?(R=zp(R,y.id,t.journal_generation,y.journal_seq),d.push(y.id)):R=gc(R),g.set(p.id,R))}g.size>0&&(u=u.map(y=>g.get(y.id)??y),f=St(u))}let h=u===s.records?s:{...s,records:u,index:f};if(c){h=Eo(h,d,!1);const g=(t.source_missing_ids??[]).filter(y=>typeof y=="string"&&y.length>0&&y.length<=128&&!i(y));if(g.length>0){h=Eo(h,g,!1);const y=new Set(h.journalSourceVoid??[]);for(const b of g)y.add(b);h={...h,journalSourceVoid:y}}}return h=Vp(h,t),mc(h)}function Ks(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function Jr(e,t,n={}){let r=e;const s=r,o=[],i=E=>Ts(Eo(E,o,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Sr(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 i(r);const c=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=ec(r,{...E.payload,id:E.id});const l=n.keepPaging===!0&&r.viewEpoch>0,d=n.pagedBefore!==void 0&&r.index.has(n.pagedBefore)?n.pagedBefore:r.records[0]?.id,u=[];for(const E of t.entries){if(l&&!tS(E,r.clearedAt))continue;const z=r.records[r.index.get(E.id)??-1]??r.records[r.index.get(`tool:${String(E.payload?.tool_call_id??"")}`)??-1]??jk(r,E);let F=Gp(E,z);if(F&&r.journalMode&&(F={...F,sourceEntryId:E.id}),F&&r.journalMode){const X=z?.sourcePrecedes??(n.pagedBefore!==void 0&&!z?d:void 0);X!==void 0&&F.sourcePrecedes!==X&&(F={...F,sourcePrecedes:X})}F&&c&&bs(E.journal_seq)?(F=zp(F,E.id,t.journal_generation,E.journal_seq),o.push(E.id)):F&&n.peerSource===!0&&(F=gc(F)),!(F&&z&&Ck(z,n.readWitness))&&F&&u.push(F)}let f=r.argsByCall,h=!1;for(const E of t.entries){const z=E.payload?.tool_calls;if(!Array.isArray(z))continue;const F=Math.round((E.ts??0)*1e3);for(const X of z)!X||typeof X.id!="string"||f.has(X.id)||(h||(f=new Map(f),h=!0),f.set(X.id,{...X,anchoredAt:F,anchorId:E.id}))}for(let E=0;E<u.length;E++){const z=u[E];if(z.kind!=="tool")continue;const F=f.get(z.toolCallId);if(!F)continue;const X=F.arguments??null;u[E]={...z,args:X,intent:typeof X?.i=="string"?X.i:null}}const g=h?r.records.map(E=>{if(E.kind!=="tool"||E.args)return E;const F=f.get(E.toolCallId)?.arguments??null;return F?{...E,args:F,intent:E.intent??(typeof F.i=="string"?F.i:null)}:E}):r.records,y=new Set(t.entries.map(E=>E.id)),b=n.peerSource===!0&&n.replace===!0?r.records.filter(E=>E.kind==="user"&&(E.provisional===!0||E.local===!0)&&!y.has(E.id)):[],_=n.replace?b.length>0?{...$t,records:b,index:St(b)}:$t:{...r,records:g},p=new Map(_.records.map(E=>[E.id,E]));let R=r!==s||n.replace||!n.replace&&g!==r.records;for(const E of u){const z=p.get(E.id);if(!z){R=!0,p.set(E.id,E);continue}if(z.kind==="tool"&&E.kind==="tool"){const F={...E,args:E.args??z.args,intent:E.intent??z.intent,images:Op(E.images,z.images,"current")};pa(z,F)||(R=!0,p.set(E.id,F));continue}pa(z,E)||(R=!0,p.set(E.id,E))}const k=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"),O=t.entries[0],L=O?Math.round((O.ts??0)*1e3):0,P=r.journalMode?dn:ek(_.records,L,n.statedByOwner!==!1);let T=_.oldestId,m=_.oldestTs,w=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(O&&(T=O.id,m=L),w=t.has_more):n.pagedBefore!==void 0?O?(T=O.id,m=L,w=t.has_more):w=!1:O&&(r.journalMode?(r.journalPositions?.get(O.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):L>0&&L<r.oldestTs)&&(T=O.id,m=L,w=t.has_more));const S=T!==r.oldestId||m!==r.oldestTs;if(!R&&!S&&r.hasMore===w&&!k&&P.size===0)return i(r);const x=P.size===0?[...p.values()]:[...p.values()].map(E=>P.has(E.id)?tk(E):E),N=$p(_s(x,n.statedByOwner===!1?dn:new Set(u.map(E=>E.id)),r));return n.keepPaging?i({...r,records:N,index:St(N),argsByCall:f}):i({...r,records:N,index:St(N),oldestId:T,oldestTs:m,hasMore:w,argsByCall:f,compacting:k?!1:r.compacting,compactingSince:k?0:r.compactingSince})}const Lk=/^(?:local|notice|retry|subagent|compaction):/;function _c(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!Lk.test(e.id)}}function Uk(e,t,n=dn){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(s=>!(s.ts<t.ts&&_c(s)&&!n.has(s.id)));return r.length===e.records.length?e:{...e,records:r,index:St(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const qt={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function ki(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function ha(e,t,n=Date.now(),r={}){let s=e;const o=t.message;if(t.type==="journal_order_ready"){const l=typeof t.journal_generation=="string"?t.journal_generation:void 0;if(s={...s,orderNeedsReconcile:!0,orderWantedGeneration:t.reconcile===!0?void 0:l,orderDemand:t.reconcile===!0?{}:{generation:l}},t.reconcile===!0)return s;const d=Sr(s,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=_s(d.records,dn,d);return d===s&&u===s.records?s:{...d,records:u,index:St(u)}}o&&(s=ec(s,o));const i=r.frame,c=r.queuedAskEngine;switch(t.type){case"agent_start":{const l=Number(t.generation??s.generation+1);return l===s.generation?s:{...s,generation:l,compacting:!1,compactingSince:0}}case"compaction_start":return s.compacting?s:{...s,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??s.generation)<s.generation)return s;let d=s;for(const u of s.records)if(u.kind==="assistant"&&u.streaming&&(d=je(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=je(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=ki(o);if(o===void 0||l===null)return qt.idlessFrameRefused+=1,s;const d=s.records[s.index.get(l)??-1];if(o.role==="user"){const u=Up(o.provider_payload);if(u){const b=zt(o),_=ia({...u,text:b});if(_.body.trim()){const p=d?.kind==="user"&&d.provisional===!0;return je(s,{kind:"custom",id:l,ts:p?Ao(s,n):n,customType:"hub_message",text:_.envelope,attribution:"user",...no("hub_message",_.envelope||_.body,{...u}),receipt:_,images:Fn(o,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(Bp(o.provider_payload))return s;const f=zt(o);if(mp(f))return s;const h=d?.kind==="user"&&d.provisional===!0,g=Cp(o,l,d?.kind==="user"?d.documents:void 0),y=Fo(f);return je(s,{kind:"user",id:l,ts:h?Ao(s,n):n,text:f,images:Fn(o,l,d?.kind==="user"?d.images:void 0),...g.length?{documents:g}:{},...h?{provisional:!0}:{},...y?{skill:y}:{}})}return o.role!=="assistant"||d?s:je(s,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...i?{frame:i}:{},stopReason:null,error:!1})}case"message_update":{const l=ki(o);if(o===void 0||l===null)return qt.idlessFrameRefused+=1,s;const d=s.index.get(l),u=String(t.delta??""),f=zt(o);if(d===void 0)return!f&&!u?s:je(s,{kind:"assistant",id:l,ts:n,text:f?f+u:u,streaming:!0,truncated:f===""?"prefix":void 0,...i?{frame:i}:{},stopReason:null,error:!1});const h=s.records[d];if(h.kind!=="assistant")return s;if(!h.streaming)return qt.settledAssistantUpdate+=1,s;if(r.seed!==!0&&i&&h.frame&&i.epoch===h.frame.epoch&&i.seq<=h.frame.seq)return qt.staleUpdateFrameDropped+=1,s;const g=qw(h.frame,i);if(r.seed===!0&&!f)return!h.text&&!u?s:(qt.seededDeltaWithheld+=h.text?1:0,je(s,{...h,text:h.text||u,...g?{frame:g}:{},truncated:h.text?"interrupted":"prefix"}));let y;if(f){if(y=f+u,y.length<=h.text.length)return s}else{if(!u)return s;y=h.text+u}return je(s,{...h,text:y,...g?{frame:g}:{},truncated:f?void 0:h.truncated})}case"message_end":{const l=ki(o);if(o===void 0)return qt.idlessFrameRefused+=1,s;if(l===null){if(o.role!=="assistant")return qt.idlessFrameRefused+=1,s;let y;for(const p of s.records)if(!(p.kind!=="assistant"||!p.streaming)){if(y!==void 0)return qt.idlessFrameRefused+=1,s;y=p}if(y===void 0)return qt.idlessFrameRefused+=1,s;const b=Array.isArray(o.tool_calls)?o.tool_calls:[],_={...y,streaming:!1,settledAt:y.settledAt??n,callsTools:b.length>0,...y.text||b.length===0?{complete:!0}:{}};return je(s,_)}if(o.role!=="assistant")return s;const d=s.index.get(l),u=zt(o),f=d===void 0?void 0:s.records[d],h=Array.isArray(o.tool_calls)?o.tool_calls:[],g={kind:"assistant",id:l,ts:d===void 0?n:s.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:o.stop_reason??null,error:!!o.is_error,...i?{frame:i}:{}};return je(s,g)}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,g="journal_generation"in t||"journal_ordinals"in t||"entry_times"in t,y=s.journalPeerSource===!0||g,b=y&&u!==void 0&&u===s.journalGeneration,_=d.map(k=>String(k.id??"")).filter(k=>k.length>0&&k.length<=128),p={entries:d.map(k=>{const O=String(k.id??""),L=f?.[O],P=h?.[O];return{id:O,ts:b&&typeof P=="number"&&Number.isFinite(P)?P:n/1e3,type:"message",payload:{kind:k.custom_type?"custom":"message",...k},...b&&bs(L)?{journal_seq:L}:{}}}),has_more:s.hasMore,...b?{journal_generation:u}:{}};let R=Jr(s,p,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:y});if(y&&_.length>0)if(b){const k=_.filter(O=>!bs(f?.[O]));k.length>0&&(R=kd(R,k))}else R=kd(R,_),u!==void 0&&(R=Sr(R,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),R=Ts(R,!0));return R}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return s;const d=String(t.supersedes_tool_call_id??""),u=`tool:${l}`,f=s.records[s.index.get(u)??-1],h=d?s.records[s.index.get(`tool:${d}`)??-1]:void 0,g=f?.kind==="tool"?f:h?.kind==="tool"?h:void 0;if(g&&g.phase!=="composing"&&g.phase!=="queued")return d&&f?.kind==="tool"?wi(s,d):s;const b=String(t.not_run_reason??"").trim()||null,_=String(t.not_run_kind??"").trim()||null;if(wd(t.tool_name,c)&&!b&&!g)return d?wi(s,d):s;const p=Number(t.argument_bytes??0),R={kind:"tool",id:u,ts:g?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:b?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:p>0?p:g?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:Qr,added:0,removed:0,diff:null,stopped:!1,notRunReason:b,notRunKind:b?_:null,neverSent:b!==null};return d&&h?.kind==="tool"&&f?.kind!=="tool"?rk(s,d,R):je(d&&f?.kind==="tool"?wi(s,d):s,R)}case"tool_execution_start":{const l=String(t.tool_call_id??"");if(!l)return s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1];if(u&&u.kind==="tool"&&u.phase==="done"&&!u.notRunReason)return s;const f=bd(s,l,t,u),h=f&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:f,anchoredAt:br(t)??n}):s.argsByCall,g=h===s.argsByCall?s:{...s,argsByCall:h};return wd(t.tool_name,c)&&!u?g:je(g,{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:br(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:Qr,added:0,removed:0,diff:u?.kind==="tool"?u.diff:null,details:u?.kind==="tool"?u.details??null:null,stopped:!1})}case"tool_execution_update":{const l=String(t.tool_call_id??"");if(!l)return s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1];if(!u||u.kind!=="tool")return s;const f=t.partial_result??{},h=la(f.details,u.details);return h===(u.details??null)?s:je(s,{...u,details:h})}case"tool_execution_end":{const l=String(t.tool_call_id??"");if(!l)return s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1],f=t.result??{};if(Wp(f.details))return Qp(s,d);const h=bd(s,l,t,u),g=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:Qr,added:0,removed:0,diff:null,stopped:!1},y=h&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:h,anchoredAt:br(t)??n}):s.argsByCall,b=y===s.argsByCall?s:{...s,argsByCall:y},_=r.userStoppedAt??null,p=!!(t.is_error??f.is_error),R=Ip(f.details?.__fault),k=_!==null&&(typeof g.startedAt=="number"?g.startedAt<=_:p);return je(b,{...g,args:h,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:zt(f)||null,isError:k||R?!1:p,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof g.startedAt=="number"?g.startedAt+t.duration_s*1e3:null,startedAt:null,images:Jw(Fn(f,d,g.images),g.images),...hp(f.details,g),diff:pp(fp(f.details),g.diff),stopped:g.stopped||k||R,delivery:ip(f.details,g.delivery,g.toolName),bridge:sp(g.toolName,f.details,g.bridge),bridgeLabel:op(g.toolName,f.details,g.bridgeLabel),details:la(f.details,g.details)})}case"supplement_progress":{const l=Gw(t);if(!l)return s;const d=dc(l.anchor),u=s.records[s.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,h=Rp(f,l,n);return h?je(s,h):s}case"notice":{const l=String(t.text??"");if(!l)return s;const d=`notice:${s.generation}:${l}`;return s.index.has(d)?s:je(s,{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:Mp(String(t.detail??"")),h=f?f.text:l&&d?ok(l,d):jp,g=`compaction:${s.generation}:${l}:${d}`,y=s.compacting?{...s,compacting:!1,compactingSince:0}:s;return y.index.has(g)?y:f?je(y,{kind:"notice",id:g,ts:n,text:h,level:f.level}):ak(je(y,{kind:"compaction",id:g,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:${s.generation}:${String(t.attempt??"")}`;return s.index.has(d)?s:je(s,{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=s.records[s.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?s:je(s,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return s}}function br(e){return nv(e.started_at_epoch)}function bc(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function Fk(e){const t=bc(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function Bk(e,t){const n=br(e);if(n!==null)return n;const r=bc(e);if(!r)return null;const s=t.argsByCall.get(r)?.anchoredAt;return typeof s=="number"&&Number.isFinite(s)&&s>0?s:null}function Hk(e,t){if(br(e)!==null)return!1;const n=bc(e);if(!n)return!1;const r=t.argsByCall.get(n)?.anchorId;if(typeof r!="string")return!1;const s=t.index.get(r);return s!==void 0&&s<=Pp(t.records)}function vc(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 Ho(e){return e.type==="tool_execution_end"}function Wk(e,t,n=Date.now(),r=null){let s=e;t.streaming&&t.generation>s.generation&&(s={...s,generation:t.generation}),s.compacting&&(s={...s,compacting:!1,compactingSince:0});const o=t.streaming===!0,i=Hp(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let h=n;const g=Fk(f);if(g!==null&&!s.index.has(g)){const y=Bk(f,s);if(y!==null)h=y,c=!0,Hk(f,s)&&l.add(g);else if(Ho(f)||vc(f)||!o)continue}s=ha(s,f,h,{seed:!0,queuedAskEngine:i,...r?{frame:r}:{}})}if(!c)return s;const d=_s(s.records,l,s);return{...s,records:d,index:St(d)}}function Ed(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!Ho(r)&&!vc(r))continue;const s=String(r.tool_call_id??"");if(!s)continue;const o=br(r);o!==null&&t.set(s,o)}return t}function Gk(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n;if(r.type!=="tool_call_compose")continue;const s=r.not_run_reason;if(typeof s=="string"&&s.trim().length>0)continue;const o=String(r.tool_call_id??"");o&&t.add(o)}return t}const zk=5e3;function Kk(e,t){const n=new Set(t),r=new Map;if(n.size===0)return r;for(const s of e){if(s.payload?.role!=="tool")continue;const o=s.payload.tool_call_id;if(typeof o!="string"||!n.has(o))continue;const i=s.ts;typeof i!="number"||!Number.isFinite(i)||r.set(o,Math.round(i*1e3))}return r}function Vk(e,t,n,r=new Map,s=new Set){const o=e[0]?.ts;if(typeof o!="number"||!Number.isFinite(o))return!1;let i=null;for(const l of t){const d=n.get(l);if(d===void 0){if(s.has(l))continue;return!1}(i===null||d<i)&&(i=d)}for(const l of r.values())(i===null||l<i)&&(i=l);return i===null?!1:Math.round(o*1e3)<=i-zk}function Ad(e,t){const n=[];for(const r of e??[]){if(!r)continue;const s=r;if(!Ho(s)&&!vc(s))continue;const o=String(s.tool_call_id??"");!o||n.includes(o)||t.has(o)||n.push(o)}return n}function Rd(e,t,n,r){const s=[],o=new Set;for(const i of t)o.has(i)||(o.add(i),!n.has(i)&&((e.get(i)??0)>=r||s.push(i)));return s}const Zk=3.25,ma=100,yc=500;function Id(e){return e<=0?ma:Math.min(yc,ma+Math.ceil(Zk*e))}function Si(e,t){const n=[];if(t.size===0)return n;for(const r of e){const s=r.payload?.tool_calls;if(Array.isArray(s))for(const o of s)o&&typeof o.id=="string"&&t.has(o.id)&&n.push(o.id)}return n}function Yk(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function Qk(e,t){const n=new Set(t);for(const o of e){const i=o.payload?.tool_calls;if(Array.isArray(i))for(const c of i)c&&typeof c.id=="string"&&n.add(c.id)}const r=[],s=new Set;for(const o of e){if(o.payload?.role!=="tool")continue;const i=o.payload.tool_call_id;typeof i!="string"||n.has(i)||s.has(i)||(s.add(i),r.push(i))}return r}function Xk(e,t){return e&&t===0}function Jk(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,s=r.not_run_reason,o=r.type==="tool_call_compose"&&typeof s=="string"&&s.trim().length>0;if(r.type!=="tool_execution_start"&&!Ho(r)&&!o)continue;const i=String(r.tool_call_id??"");i&&t.add(i)}return t}function Zp(e,t,n){const r=new Set(e),s=[];for(const o of t)!r.has(o)&&!n.has(o)&&s.push(o);for(const o of e){if(n.has(o))return s;t.has(o)&&s.push(o)}return s}function qk(e,t,n){return Zp(e,t,n).length}function Td(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=je(t,{...n,truncated:"interrupted"}));return t}function eS(e,t=Date.now()){return e.records.length===0?e:{...$t,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function tS(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 xd(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function nS(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return hc(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function Ao(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function Yp(e,t,n,r,s=Date.now(),o=fa){if(e.index.has(t))return e;const i=Fo(n);return je(e,{kind:"user",id:t,ts:Ao(e,s),text:n,images:r,...o.length?{documents:o}:{},...i?{skill:i}:{},local:!0,provisional:!0})}function Qp(e,t){return hc(e,n=>n.id===t)}let Cd=0;function rS(e,t,n,r=Date.now()){return Cd+=1,je(e,{kind:"notice",id:`local:${r}:${Cd}`,ts:Ao(e,r),text:t,level:n})}function A1(e,t,n,r){const s=t?.anchor_id,o=t?.kind;return!s||o!=="error"&&o!=="interrupted"&&o!=="closed"&&o!=="retired"||n||e.index.has(s)||!t?.unseen&&!r?.has(s)?e:(r?.add(s),je(e,{kind:"notice",id:s,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:o==="closed"?Dp:o==="retired"?Np:o==="error"?"Stopped with an error":"Interrupted",level:o==="closed"?"info":o==="retired"?"warning":o==="error"?"error":"warning"}))}const sS="compacting context…";function R1(e){return typeof e=="string"&&e.trim()===sS}const oS=[1500,5e3];async function I1(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of oS){await t(n);try{if(await e())return}catch{}}}function iS(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 Od=new Set(["openrouter","radient","radient-key"]),aS=new Set(["auto","openrouter/auto"]),cS="Auto";function Xp(e){return e.slice(e.lastIndexOf("/")+1)||e}function lS(e,t){return e===t||e===Xp(t)}function Ei(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 T1(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():"",s=Od.has(t)||!r||lS(r,e.model_id)||r.toLowerCase()==="unknown";return{name:Od.has(t)&&aS.has(e.model_id)?cS:s?Xp(n):r,selector:n}}function x1(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function C1(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function O1(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function P1(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 M1(e){const t=e?.effort_displacement,n=t?.note;if(typeof n!="string"||!n.trim())return null;const r=new Map;for(const i of[e?.effective_model,e?.selected_model]){const c=typeof i?.display_name=="string"?i.display_name.trim():"";if(!i||!c||!i.provider||!i.model_id)continue;const l=`${i.provider}/${i.model_id}`;l!==t?.serving&&l!==t?.selected||r.set(l,c)}if(!r.size)return n.trim();const s=[...r.keys()].sort((i,c)=>c.length-i.length).map(i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),o=new RegExp(`(^|[\\s(])(${s.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(o,(i,c,l)=>`${c}${r.get(l)}`)}function j1(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function $1(e){const t=e.trim();return t&&({auto:"Auto",none:"None",minimal:"Minimal",low:v("ui.chat.session_status.effort_level.low"),medium:v("ui.chat.session_status.effort_level.medium"),high:v("ui.chat.session_status.effort_level.high"),xhigh:"xHigh",max:"Max"}[t.toLowerCase()]??t)}function Jp(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 D1(e,t){const n=(e??t)?.effective_model;return Jp(n)?null:n?.model_id??null}function N1(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(o=>typeof o=="string"):null,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",s=Jp(e);return t?{label:t,adjustable:n===null||n.length>0,knownLadder:!!(n&&n.length>0),levelKnown:!0,detail:n&&n.length>0?`Reasoning effort. This model offers ${n.join(", ")}.`:"Reasoning effort for this session."}:n&&n.length>0?{label:"auto",adjustable:!0,knownLadder:!0,levelKnown:!0,detail:`No level is set, so this model runs at its own default${r?` (${r})`:""}. It offers ${n.join(", ")}.`}:s?{label:"unknown",adjustable:!0,knownLadder:!1,levelKnown:!1,detail:"This session has not reported its reasoning effort yet. It appears after the next turn, or run /effort <level> to set one now."}:n&&e.reasoning?{label:"reasoning",adjustable:!1,knownLadder:!0,levelKnown:!0,detail:"This model reasons, but exposes no effort levels to choose between."}:n===null&&r?{label:r,adjustable:!1,knownLadder:!1,levelKnown:!0,detail:"The level this model runs at by default. This backend does not report which other levels it accepts."}:null}function L1(e,t){if(!e)return null;if(!t||t.length===0||e.knownLadder)return e;const n=t.map(r=>typeof r=="object"&&r!==null&&"value"in r?String(r.value):"").filter(Boolean);return n.length===0?e:{...e,adjustable:!0,detail:`Reasoning effort. This model offers ${n.join(", ")}.`}}function dS(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const i=Nr(n.provider);if(!i)return null;const c=Nr(e?.selected_model?.provider);if(c&&c!==i)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:i,label:Nr(n.label)||i,effectiveState:d,owner:Nr(n.owner_label)||Nr(n.owner_device)||"the owner device",observedAt:Ai(n.observed_at),lastGrantAt:Ai(n.last_grant_at),lastGrantExpiresAt:Ai(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 s=e?.effective_model?.provider;if(s&&s!==r)return null;const o=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:o,state:n.state}:{provider:r,label:o}}function U1(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function F1(e){return e&&e.draft!==!0?dS(e.frontend,e.servingLocality):null}function Nr(e){return typeof e=="string"?e.trim():""}function Ai(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function Ri(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function B1(e){const{label:t,effectiveState:n}=e,r=e.owner||"the owner device",s={local:[`${t} access available`,"This session uses its own provider access."],pending:[`Checking ${t} access`,"Access has not converged yet. The next request checks the owner automatically; no additional sign-in is needed here."],eligible_borrow_unverified:[`Checking access from ${r}`,`This session may borrow ${t} access, but it has not resolved it yet. The next request verifies ${r} automatically.`],effective_borrow:[`${t} access from ${r}`,"The runtime resolved borrowed access for this session. Every new request checks the owner again."],expired:[`Fresh ${t} access needed`,`The last borrowed grant expired, but borrowing permission is still present. The next request asks ${r} for fresh access automatically.`],withdrawn:[`${t} access needs attention`,"The owner cannot currently provide borrowed access, or borrowing permission is unavailable. Restore owner access or permission before retrying, or choose another model."],owner_unavailable:[`${r} cannot provide access`,`This session could not resolve ${t} access from ${r}. Previous access cannot be reused. Retry after owner access is restored, or choose another model.`],device_bound:[`${t} needs a device sign-in`,"This login cannot be borrowed. Sign in on the device running this session, or choose another model."],absent:[`No ${t} access`,e.connectHere===!0?"The serving device has no effective provider access for this session. Connect an account or choose another model.":"The device running this session has no effective provider access. Sign in or restore access on that device, or choose another model."]},o=e.state==="temporarily_unavailable",[i,c]=n?s[n]:[o?v("ui.chat.session_status.temporarily_unavailable",{label:t}):v("ui.chat.session_status.not_signed_in",{label:t}),o?v("ui.chat.session_status.temporarily_unavailable_description"):v("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];return n&&e.observedAt!==void 0&&l.push(`Last checked: ${Ri(e.observedAt)}.`),n&&e.lastGrantAt!==void 0&&l.push(`Last resolved: ${Ri(e.lastGrantAt)}.`),n&&e.lastGrantExpiresAt!==void 0&&l.push(`Recorded grant expiry: ${Ri(e.lastGrantExpiresAt)}.`),n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push("History only; not permission to reuse access."),{title:i,description:c,history:l.join(" "),tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!o,canSwitchModel:n!=="effective_borrow"}}function H1(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function W1(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function G1(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function uS(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function fS(e,t){return!!e.streams[t]}function qp(e,t){return e.attached[t]?.turns.at(-1)}function z1(e,t){const n=qp(e,t);return n?e.streams[n.asideId]:void 0}function K1(e,t){const n=e.attached[t]?.turns??[];for(let r=n.length-1;r>=0;r-=1){const s=n[r];if(s&&e.streams[s.asideId]?.settled)return s.asideId}}function pS(){return{text:"",streaming:!0,settled:!1,error:null}}function hS(e){return{text:e,streaming:!1,settled:!0,error:null}}function mS(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const gS=Rs(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(s=>({streams:{...s.streams,[n]:pS()},attached:{...s.attached,[t]:{turns:[...s.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const s=uS(r.streams[t],n);return s?{streams:{...r.streams,[t]:s}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:hS(n)}}:r),failAside:(t,n)=>e(r=>fS(r,t)?{streams:{...r.streams,[t]:mS(r.streams[t],n)}}:r),setAsideNotice:(t,n)=>e(r=>{const s=r.attached[t];return s?{attached:{...r.attached,[t]:{...s,notice:n}}}:r}),queueAdoption:(t,n,r)=>e(s=>{const o=s.attached[t];return o?{attached:{...s.attached,[t]:{...o,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:s}),unqueueAdoption:(t,n,r)=>e(s=>{const o=s.attached[t];if(o?.queued?.asideId!==n)return s;const{queued:i,...c}=o;return{attached:{...s.attached,[t]:{...c,notice:r}}}}),detachAside:t=>e(n=>{const r=n.attached[t],s={...n.attached};if(delete s[t],!r)return{attached:s};const o={...n.streams};for(const i of r.turns)delete o[i.asideId];return{streams:o,attached:s}})}));function V1(e,t){return qp(e,t)?.asideId}const _S=4*1024*1024,Pd=1024*1024,Kt=new Map;function Md(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function bS(e){const t=e.slice(-200),n=Md(t);if(n<=Pd)return{records:t,bytes:n};let r=0,s=t.length,o=0;for(;s-r>1;){const i=Math.floor((r+s)/2),c=Md(t.slice(i));c>Pd?r=i:(s=i,o=c)}return{records:t.slice(s),bytes:o}}function vS(e,t){const{records:n,bytes:r}=bS(nS(t.transcript).records);if(n.length===0){Kt.delete(e);return}const s={...t.transcript,records:n,index:new Map(n.map((i,c)=>[i.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},o={transcript:s,savedAt:Date.now(),bytes:r,owedLabels:jd(n,t.owedLabels),markLabels:jd(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(i=>s.index.has(i)))};Kt.delete(e),Kt.set(e,o),wS()}function jd(e,t){if(!t||t.size===0)return $d;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:$d}const $d=new Set;function eh(e){const t=Kt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function yS(e){Kt.delete(e)}function wS(){let e=0;for(const t of Kt.values())e+=t.bytes;for(;e>_S&&Kt.size>0;){const t=Kt.keys().next().value;if(t===void 0)break;const n=Kt.get(t);Kt.delete(t),e-=n?.bytes??0}}const kS=8,SS=128,th=new Set,ES="",tn=new Map,wc=e=>e??ES;function Z1(e){return tn.get(wc(e))??th}function Y1(e,t,n){const r=wc(e),s=tn.get(r)??new Set,o=new Set(s);if(n)for(o.delete(t),o.add(t);o.size>SS;){const i=o.values().next().value;if(i===void 0)break;o.delete(i)}else o.delete(t);for(tn.delete(r),o.size>0&&tn.set(r,o);tn.size>kS;){const i=tn.keys().next().value;if(i===void 0)break;tn.delete(i)}return tn.get(r)??th}function AS(e){tn.delete(wc(e))}const RS=128,Ro=4096,Ii=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),Dd=e=>e.startsWith("qg:")&&e.length>3;function Q1(e,t,n=null,r=[]){const s=new Map,o=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(s.has(u))return Ii("duplicate-prior-id");if(s.size===Ro)return Ii("prior-id-limit");s.set(u,{ordinal:c,order:d})}l.eligible!==!1&&Dd(l.key)&&t.has(l.key)&&o.size<RS&&o.set(c,l.key)}for(const c of r)if(!s.has(c)){if(s.size===Ro)return Ii("prior-id-limit");s.set(c,{ordinal:-1,order:-1})}const i=n===null?void 0:s.get(n);if(i!==void 0&&i.ordinal>=0){const c=e[i.ordinal];c.eligible!==!1&&Dd(c.key)&&o.set(i.ordinal,c.key)}return{complete:!0,owners:s,keys:o,reason:null}}function X1(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>Ro)return r("prior-id-limit");const s=new Set,o=n.currentIdsUnique===!0?null:new Set,i=new Map,c=new Map,l=(f,h,g)=>{const y=i.get(f);y===void 0?i.set(f,{current:h,many:!1,lastOrder:g,reordered:!1,outside:!1}):(y.current!==h&&(y.many=!0),g<=y.lastOrder&&(y.reordered=!0),y.lastOrder=g)};for(let f=0;f<t.length;f+=1){const h=t[f];let g=null,y=!1;for(const _ of h.segmentIds){if(o!==null){if(o.has(_))return r("duplicate-current-id");if(o.size===Ro)return r("current-uniqueness-unproved");o.add(_)}const p=e.owners.get(_);if(p!==void 0){if(s.has(_))return r("duplicate-current-id");s.add(_),l(p.ordinal,f,p.order),g===null?g=p.ordinal:g!==p.ordinal&&(y=!0)}}if(h.eligible===!1||y||g===null||g<0)continue;const b=e.keys.get(g);b!==void 0&&c.set(f,{owner:g,key:b})}for(const f of n.outsideCurrentIds??[]){const h=e.owners.get(f);if(h===void 0||s.has(f))continue;const g=i.get(h.ordinal);g!==void 0&&(g.outside=!0)}for(const[f,h]of c){const g=i.get(h.owner),y=h.key.slice(3);(g===void 0||g.many||g.reordered||g.outside||!s.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 g=c.get(h);return g===void 0?f:{...f,key:g.key}}),reason:null}}const IS=8,TS="",Un=new Map,kc=e=>e??TS;function J1(e){return Un.get(kc(e))??null}function q1(e,t){const n=kc(e);for(Un.delete(n),Un.set(n,t);Un.size>IS;){const r=Un.keys().next().value;if(r===void 0)break;Un.delete(r)}}function xS(e){Un.delete(kc(e))}function CS(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const s=n.getTranscript().orderRevision??0,o=()=>(n.getTranscript().orderRevision??0)===s;try{let i=r,c=await n.readPage(i);if(!n.isCurrent()||!o())return{kind:"stale"};if(c.cursor_missing){const u=Mk(n.getTranscript()),f=u!==null&&u!==i?u:Ok(c,i);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(i=f,c=await n.readPage(i),!n.isCurrent()||!o())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)!==s?u:Jr(u,c,{...u.oldestId===r?{pagedBefore:i}:{},...n.peerSource?.()===!0?{peerSource:!0}:{}})));return(d.orderRevision??0)!==s||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 s=r.getTranscript();if(!s.hasMore||!s.oldestId)return Promise.resolve({kind:"nothing-to-load"});const o={key:n,promise:t(r,s.oldestId)};e=o;const i=()=>{e===o&&(e=null)};return o.promise.then(i,i),o.promise}}}const OS={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"},PS={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function Sc(e){return{kind:e,statement:v(OS[e]),action:PS[e]}}function Nd(e){return Sc(ov(e))}const MS=()=>Sc("historyUnreadable"),jS=new Set(["subagent_start","subagent_progress","subagent_end"]),$S=(e,t)=>({...e,[t]:(e[t]??0)+1}),DS=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=nh(n);r&&(t[r]=(t[r]??0)+1)}return t},nh=e=>{if(!e||typeof e!="object")return null;const t=e;return jS.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},NS=(e,t)=>{const n=nh(t);return n?$S(e,n):e};function Ld(e,t,n){if(!n||!e)return{};const r=e.context_tokens;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return{};const s=t.context_tokens;return typeof s=="number"&&Number.isFinite(s)&&s>=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 LS(e){for(const t of e)t.type==="aside_delta"&&gS.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function US(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const $n=new Set,Kr=new Set;function FS(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 BS=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),HS=15e3,ga=[500,1e3,2e3,4e3,8e3,8e3],WS=ga.length,GS=2e4,zS=1e4,KS=1e4;function Ud(e){const t=Math.max(1,Math.min(e,ga.length));return ga[t-1]??8e3}const VS=3,ZS=250,YS=32*1024,Fd=512,Bd=new Set(["turn_end","agent_end"]),Hd=2,QS=500,Wd=yc,XS=6,Ti=yf("sessions.history"),JS=2e3,Gd={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},Wn=new Map,ro=new Map,qS=8,eE=2048,zd=1024,tE=1024,nE="",Pn=new Map;function Kd(e){const t=e??nE,n=Pn.get(t);if(n)return Pn.delete(t),Pn.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(Pn.set(t,r);Pn.size>qS;){const s=Pn.keys().next().value;if(s===void 0||s===t)break;Pn.delete(s)}return r}function xi(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function Ci(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function rE(e,t){return ro.set(e,t),()=>{ro.get(e)===t&&ro.delete(e)}}function eO(e){const t=ro.get(e);return t?(t(),!0):!1}const Ye=new Map,sE=4,oE=16;function rh(e,t){e(n=>Yp(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function iE(e,t,n){const r=e.index.get(t),s=r===void 0?void 0:e.records[r];if(r===void 0||!s||s.kind!=="user"||!s.local||s.text===n)return e;const o=e.records.slice(),{skill:i,...c}=s,l=Fo(n);return o[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:o}}function _a(e,t){let n=Ye.get(e);if(!n){if(Ye.size>=oE){const o=Ye.keys().next();o.done||Ye.delete(o.value)}n=new Map,Ye.set(e,n)}const r={identity:e,id:t.id,text:t.text,images:t.images,documents:t.documents??[],onPainted:t.onPainted,settled:t.settled,submittedAt:t.submittedAt};for(n.set(r.id,r);n.size>sE;){const o=n.keys().next();if(o.done)break;n.delete(o.value)}const s=Wn.get(e);s&&rh(s,r)}function tO(e){if(!e)return null;const t=Ye.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function ba(e,t){const n=Ye.get(e);n&&(n.delete(t),n.size===0&&Ye.delete(e))}function va(e,t){const n=Ye.get(e)?.get(t);n&&(n.settled=!0)}function Vd(e,t){return e?Ye.get(e)?.has(t)===!0:!1}function nO(e){return e?(Ye.get(e)?.size??0)>0:!1}function aE(e,t,n){const r=Ye.get(e)?.get(t);if(!r)return;r.text=n;const s=Wn.get(e);s&&s(o=>iE(o,t,n))}function cE(e,t){if(e===t)return;const n=Ye.get(e);if(!n)return;Ye.delete(e);const r=Ye.get(t)??new Map;for(const[s,o]of n)o.identity=t,r.set(s,o);Ye.set(t,r)}function Vs(e){Ye.delete(e)}function lE(e,t){const n=Ye.get(e);if(n)for(const r of[...n.keys()]){const s=t.index.get(r),o=s===void 0?void 0:t.records[s];o?.kind==="user"&&o.local!==!0&&ba(e,r)}}function dE(e,t){Wn.set(e,t);const n=Ye.get(e);if(n)for(const r of n.values())rh(t,r);return()=>{Wn.get(e)===t&&Wn.delete(e)}}function uE(e,t){const n=Ye.get(e);if(!n)return t;let r=t;for(const s of n.values())r=Yp(r,s.id,s.text,s.images,void 0,s.documents);return r}function fE(e,t,n){return e===t?!0:!n}function pE(e,t){const n=Wn.get(e);if(!n)return ba(e,t),"queued";let r="queued";return n(s=>{const o=s.records[s.index.get(t)??-1];return!o||o.kind!=="user"?s:o.local?(r="retracted",Qp(s,t)):(r="owner",s)}),ba(e,t),r}function sh(e,t){const n=Wn.get(e);if(!n)return"unseen";let r="unseen";return n(s=>{const o=s.records[s.index.get(t)??-1];return!o||o.kind!=="user"||(r=o.local?"local":"owner"),s}),r}function hE(e){const t=eh(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:$t,stale:!1,owedLabels:$n,markLabels:Kr}}function mE(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function Oi(e,t){if(e.size!==0)for(const n of t)e.delete(jt(n))}function Zs(e,t){for(const n of t)e.add(jt(n))}const Zd=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function rO(e,t,n=!0,r=e,s={}){const o=s.openFrame===!0,i=s.journalOrder===!0,c=I.useRef(i);c.current=i;const l=I.useRef(o);l.current=o;const d=s.peerJournalSource===!0,u=I.useRef(d);u.current=d;const f=I.useRef(null),h=I.useRef(0),g=I.useRef(0),y=I.useRef(0),b=I.useRef(null),_=I.useRef(null),p=I.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const $=yt.getState();return cA($.sessions,$.placementFacts,e)},[e]),R=I.useCallback(()=>{const $=f.current;return p()&&$!==null&&$.sessionId===e&&$.peer},[p,e]),k=I.useCallback(()=>{const $=f.current;return $!==null&&$.sessionId===e&&$.peer},[e]),[O,L]=I.useState(()=>{const $=t&&e?hE(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?uE(r,$?.transcript??$t):$t,stale:$?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:$?.owedLabels??$n,labelMarked:$?.markLabels??Kr,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),P=I.useRef(O),T=I.useCallback($=>{const J=$(P.current);return J===P.current||(P.current=J,L(J)),J},[]);I.useEffect(()=>vm(()=>{T($=>{const{failure:J}=$;if(!J?.kind)return $;const de=Sc(J.kind);return de.statement===J.statement&&de.action===J.action?$:{...$,failure:de}})}),[T]);const m=I.useRef(e),w=I.useRef([]),S=I.useRef($t.index),x=I.useRef(new Set),N=I.useRef(new Set),E=I.useRef(Kd(e)),z=I.useRef(new Set),F=I.useRef(null),X=I.useRef({}),$e=I.useRef(null),We=I.useRef(null),K=I.useRef(null),he=I.useRef(0),re=I.useRef(0),Pe=I.useRef(0);I.useEffect(()=>{if(!e||!t)return;const $=++re.current,J=new WeakMap;let de=null;const Le=(te,ne)=>{const be=J.get(te);if(be===void 0||At(ne)===be.revision)return!1;const se=te.payload.history.journal_generation;return!(typeof se=="string"&&se.length>0&&se===ne.journalGeneration)};let ee=null,ut=!1,ze=0,ye=0,Xe=0,H=0,Re=0,xe=0,Te=0,Ke=!1;const Fe=()=>{xe&&(window.clearTimeout(xe),xe=0)},Ps=te=>{for(const ne of te)E.current.attempts.set(ne,(E.current.attempts.get(ne)??0)+1)},Jo=te=>{T(ne=>{const be=new Set;for(const Ce of ne.labelPending)ne.labelPending.has(Ce)&&(Ci(E.current,ne.transcript.argsByCall,Ce,xi(ne))||be.add(Ce));let se=null;for(const Ce of ne.labelMarked)Ci(E.current,ne.transcript.argsByCall,Ce,xi(ne))||(se=se??new Set(ne.labelMarked),se.delete(Ce));if(be.size===0&&!se)return ne;const ke=new Set(ne.labelPending);for(const Ce of be)ke.delete(Ce);return{...ne,labelPending:ke.size?ke:$n,labelMarked:se&&se.size===0?Kr:se??ne.labelMarked}})},lm=te=>{T(ne=>{let be=null,se=null;for(const ke of te)ne.labelPending.has(ke)&&(be=be??new Set(ne.labelPending),be.delete(ke),se=se??new Set(ne.labelMarked),se.add(ke));return!be||!se?ne:{...ne,labelPending:be.size?be:$n,labelMarked:se}})},Ms=async(te,ne,be=Gd,se=1,ke,Ce=ne,ve=null)=>{he.current+=1,re.current===te&&T(Qe=>Qe.historyReadPending?Qe:{...Qe,historyReadPending:!0});for(const Qe of be.targets)E.current.inFlight.add(Qe),z.current.add(Qe);let st=!1;try{st=await dm(te,ne,Ce,ve,be,se,ke)}finally{if(he.current=Math.max(0,he.current-1),he.current===0&&T(Qe=>Qe.historyReadPending?{...Qe,historyReadPending:!1}:Qe),!st){for(const Qe of be.targets)E.current.inFlight.delete(Qe);E.current.refused&&lm(be.targets),Jo()}}},dm=async(te,ne,be,se,ke,Ce,ve)=>{const st={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:be.size===0},Qe=P.current.transcript.viewEpoch,Je=await um(te,ne,be,se,ke,Ce,st,ve);if(Je||re.current!==te||st.reachedHeld||P.current.transcript.viewEpoch!==Qe)return Je;const gt=ne!==be&&[...ne].some(bt=>be.has(bt));if(gt&&st.joined)return Je;let _t;if(st.oldest){if(!st.hasMore)return Je;_t={id:st.oldest.id,ts:Math.round((st.oldest.ts??0)*1e3)}}else{if(gt||!se)return Je;_t=se}if(!_t)return Je;const fn=T(bt=>{const Pt=Uk(bt.transcript,_t,st.keys);return Pt===bt.transcript?bt:{...bt,transcript:Pt}});return S.current=fn.transcript.index,Je},um=async(te,ne,be,se,ke,Ce,ve,st)=>{const Qe=P.current.transcript.viewEpoch,Je=()=>P.current.transcript.viewEpoch!==Qe,gt=new Set;let _t,fn=0,bt=0,Pt=!1,pn=be.size===0,er=!1;const js=P.current.cold,hn=F.current,Cn=hn?{epoch:hn.epoch,seq:hn.seq}:null,Jt=new Set(ke.found),tr=()=>qk(ke.order,ke.targets,Jt),j=()=>Zp(ke.order,ke.targets,Jt),C=()=>{const Y=new Map;for(const vt of Ee){if(Jt.has(vt))continue;const Mt=ft.get(vt);Mt!==void 0&&Y.set(vt,Mt)}return Y},we=new Set(ke.every);for(const Y of Jt)we.add(Y);const Ee=new Set,ft=new Map;let Z=1;const mn=ke.targets.size>0;let fe=Math.max(Id(tr()),mn?E.current.depth:0),Ve=0;for(;fn<Wd&&bt<XS;){bt+=1;let Y;const vt=sa(P.current.transcript),Mt=vt.revision;try{Y=await Ze({op:"sessions.history",sessionId:e,..._t?{beforeId:_t}:{},limit:Math.min(fe,Wd-fn),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Gt(P.current.transcript).slice(0,512),...R()?{peerJournalSource:!0}:{}}:{}})}catch{if(Je())return!1;if(P.current.transcript.records.length>0){if(Ve++>0)return E.current.refused=!0,!1;continue}return Ce<VS?(Re=window.setTimeout(()=>{if(Re=0,re.current!==te||Je()){Jo();return}Ms(te,ne,ke,Ce+1,st,be,se)},Ud(Ce)),!0):(T(Ae=>({...Ae,status:"unavailable",failure:MS(),heldFrontend:null,...Ae.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{Jo()}if(re.current!==te||Je())return!1;if(At(P.current.transcript)!==Mt){if(!P.current.hydrated)continue;return!1}E.current.refused=!1;const On=Y.entries[0];fn+=Y.entries.length,st?.(Y.entries.length),Oi(x.current,Y.entries),Zs(N.current,Y.entries),T(Ae=>{if(At(Ae.transcript)!==Mt)return Ae;const Ht=Jr(Ae.transcript,Y,{authoritative:!0,orderRead:vt,peerSource:k(),readWitness:Cn}),nr=Si(Y.entries,we),ei=new Set(Ae.labelPending);for(const mm of nr)ei.delete(mm);return{...Ae,hydrated:Ae.hydrated||Y.entries.length>0||!js,labelPending:ei.size?ei:$n,labelMarked:FS(Ae.labelMarked,nr),transcript:Ht}}),e&&_t===void 0&&yt.getState().resolveHeldFromServer(e,Y.entries,!Y.cursor_missing);const hm=tr();for(const Ae of Si(Y.entries,we))Jt.add(Ae),we.add(Ae);if(Yk(Y.entries)&&(er=!0),mn){const Ae=Qk(Y.entries,we);for(const Ht of Ae)Ee.add(Ht),we.add(Ht);for(const[Ht,nr]of Kk(Y.entries,Ae))ft.set(Ht,nr);for(const Ht of[...Ee])Jt.has(Ht)&&Ee.delete(Ht);Ee.size>0&&Z--<=0&&Ee.clear()}Pt=Pt||ne.size===0||Y.entries.some(Ae=>ne.has(jt(Ae))||gt.has(Ae.id)),pn=pn||Y.entries.some(Ae=>be.has(jt(Ae)));for(const Ae of Y.entries)gt.add(Ae.id);for(const Ae of Y.entries)ve.keys.add(jt(Ae));On&&(ve.oldest=On),ve.hasMore=Y.has_more,ve.joined=Pt,ve.reachedHeld=pn;const qo=tr()+Ee.size;mn&&tr()<hm&&(E.current.depth=Math.min(yc,Math.max(E.current.depth,fn)));let sl=!1;if(mn){const Ae=j();sl=Vk(Y.entries,Ae,ke.starts,C(),new Set(Ae.filter(nr=>ke.waiting.has(nr))))||er}if(Xk(Pt&&pn,sl?0:qo)||!On||!Y.has_more)return!1;_t=On.id,fe=qo>0?Id(qo):ma}return!1},el=()=>{if(ze&&cancelAnimationFrame(ze),ye&&clearTimeout(ye),ze=0,ye=0,re.current!==$)return;const te=w.current;if(w.current=[],te.length===0)return;const ne=new Set,be=new Map;for(const j of x.current)P.current.transcript.index.has(j)||x.current.delete(j);for(const j of N.current)P.current.transcript.index.has(j)||N.current.delete(j);for(const j of P.current.transcript.records)_c(j)&&!x.current.has(j.id)&&(ne.add(j.id),be.set(j.id,N.current.has(j.id)?j.ts:null));let se=null;for(const j of te){if(j.type!=="snapshot")continue;const C=j.payload.history,we=C.entries[0];if(!we||!C.has_more)continue;const Ee=Math.round((we.ts??0)*1e3);Ee>0&&(!se||Ee<se.ts)&&(se={id:we.id,ts:Ee})}LS(te);const ke=j=>{const C=j.payload.history.entries,we=C.at(-1);if(!we)return!1;if(mE(j.payload)){if(ne.size===0)return!0;const Ee=new Set;for(const ft of C)Ee.add(jt(ft));return C.some(ft=>ne.has(jt(ft)))?!0:Nv(j.payload.history,be,Ee)}return we.id===j.payload.frontend.snapshot.history_cursor?!1:ne.has(jt(we))},Ce=j=>j!=null&&S.current.has(j);let ve=!1;const st=te.some(j=>j.type==="attention"?!Ce(j.payload.anchor_id):j.type==="snapshot"&&!ke(j)),Qe=P.current.cold&&!P.current.hydrated&&te.some(j=>j.type==="snapshot"||j.type==="frontend.replace"||j.type==="frontend.update"?j.payload.cold===!1:!1),Je=new Set(P.current.transcript.argsByCall.keys()),gt=[],_t=new Set;for(const j of te){if(j.type!=="snapshot")continue;const C=Le(j,P.current.transcript);C||Zs(N.current,j.payload.history.entries);for(const we of j.payload.history.entries){C||_t.add(jt(we));const Ee=we.payload?.tool_calls;if(Array.isArray(Ee))for(const ft of Ee)ft&&typeof ft.id=="string"&&Je.add(ft.id)}for(const we of j.payload.frontend.snapshot.live_events??[]){const Ee=we.message;!C&&typeof Ee?.id=="string"&&_t.add(Ee.id)}gt.push(...j.payload.frontend.snapshot.live_events??[])}const fn=te.some(j=>j.type==="event"&&Bd.has(String(j.payload.type??""))),bt=Rd(E.current.attempts,Ad(gt,Je),Je,Hd),Pt=fn?Rd(E.current.attempts,[...E.current.attempts.keys(),...E.current.settled],Je,Hd):[],pn=[];for(const j of te){if(j.type!=="event")continue;const C=j.payload;String(C.type??"")==="tool_execution_end"&&String(C.tool_call_id??"")&&pn.push(C)}const er=[];for(const j of pn){const C=String(j.tool_call_id??"");Je.has(C)||E.current.settled.has(C)||er.push(C)}for(const j of er)E.current.settled.add(j);for(;E.current.settled.size>Fd;){const j=E.current.settled.values().next().value;if(j===void 0)break;E.current.settled.delete(j)}for(const[j,C]of Ed(pn))E.current.starts.set(j,C);for(;E.current.starts.size>zd;){const j=E.current.starts.keys().next().value;if(j===void 0)break;E.current.starts.delete(j)}const js=E.current.settleRows<QS?er:[],hn=[...new Set([...bt,...Pt,...js])],Cn=hn.filter(j=>!E.current.painted.has(j));if(gt.length>0){E.current.order=Ad(gt,new Set);for(const[j,C]of Ed(gt))E.current.starts.set(j,C);for(;E.current.starts.size>zd;){const j=E.current.starts.keys().next().value;if(j===void 0)break;E.current.starts.delete(j)}for(const j of Gk(gt))E.current.waiting.add(j);for(const j of Jk(gt))E.current.waiting.delete(j);for(;E.current.waiting.size>tE;){const j=E.current.waiting.values().next().value;if(j===void 0)break;E.current.waiting.delete(j)}}for(const j of[...E.current.attempts.keys()])Je.has(j)&&E.current.attempts.delete(j);for(Ps([...bt,...Pt]);E.current.attempts.size>Fd;){const j=E.current.attempts.keys().next().value;if(j===void 0)break;E.current.attempts.delete(j)}if(performance.mark("lop:transcript:flush:start"),T(j=>{let C={...j},we=C.frontend!==null;ve=!1;let Ee=null;const ft=Date.now();for(const Z of te){if(Z.type==="heartbeat")continue;if(Z.type==="gap"){de=null,C={...C,frontend:null,heldFrontend:C.frontend??C.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:Td(C.transcript)},we=!1;continue}if(Z.type==="open")de=null;else if("seq"in Z){const fe={epoch:Z.epoch,seq:Z.seq},Ve=Zd(Z);if(!Ve&&!rv(de,fe,{allowEqual:Z.type==="snapshot"}))continue;Ve||(de=fe)}const mn=F.current;if((Z.type==="open"||"seq"in Z)&&!Zd(Z)&&(F.current={epoch:Z.epoch,seq:Z.seq},C={...C,receipt:F.current}),Z.type==="open"){if(C={...C,subscriptionId:Z.payload.subscription_id},Z.payload.gap){const fe=C.frontend??C.heldFrontend;C={...C,frontend:null,heldFrontend:fe,history:null,transcript:Td(C.transcript)},fe&&C.status==="live"&&(C={...C,status:"reconnecting"}),we=!1}continue}if(!we){if(Z.type==="event"&&(Ee=ha(Ee??C.transcript,Z.payload,ft,{frame:{epoch:Z.epoch,seq:Z.seq}})),Z.type==="snapshot"){const fe=J.get(Z),Ve=Le(Z,C.transcript);Ve&&(ve=!0);const Y=Z.payload,vt=!Y.history.cursor_missing&&!Ve;let Mt=Ee??C.transcript;vt&&(performance.mark("lop:open:history:start"),Mt=Jr(Mt,Y.history,{authoritative:!0,orderRead:fe,peerSource:k(),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"),Oi(x.current,Y.history.entries),Zs(N.current,Y.history.entries)),e&&yt.getState().resolveHeldFromServer(e,Y.history.entries,vt),performance.mark("lop:open:seed:start"),Mt=Wk(Mt,Y.frontend.snapshot,ft,{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 On=Ld(C.frontend??C.heldFrontend,Y.frontend.snapshot,Y.cold===!0||Y.attaching===!0);C={...C,contextCarried:Object.keys(On).length>0,subagentPulses:DS(Y.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...Y.frontend.snapshot,...On,attention:fr(C.frontend?.attention,Y.frontend.snapshot.attention,e)},history:Ve?C.history:Y.history,cold:Y.cold,ownerEpoch:Y.frontend.epoch,failure:null,hydrated:C.hydrated||vt&&Y.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:Mt},we=!0,Ee=null}continue}if(Z.type==="attention"){C.frontend&&(C={...C,frontend:{...C.frontend,attention:fr(C.frontend.attention,Z.payload,e)}});continue}if(Z.type==="frontend.update"){const fe=Z.payload,Ve=fe.changes??{};if((fe.degraded===!0||fe.paused===!0)&&(C={...C,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!C.frontend)continue;const Y=fe.epoch!==C.ownerEpoch&&Ve.epoch===fe.epoch,vt=fe.changes!==void 0&&Ve.epoch===fe.epoch;(Y||fe.epoch===C.ownerEpoch&&(C.frontend.sequence<fe.sequence||C.frontend.sequence===fe.sequence&&vt))&&(C={...C,contextCarried:!1,ownerEpoch:Y?fe.epoch:C.ownerEpoch,frontend:{...C.frontend,...Ve,...Ve.jobs==null&&fe.job_deltas?{jobs:Cv(C.frontend.jobs??[],fe.job_deltas)}:{},attention:fr(C.frontend.attention,Ve.attention,e),sequence:fe.sequence},...typeof fe.cold=="boolean"?{cold:fe.cold}:{}},vt&&C.liveUpdatesNotice==="update"&&C.liveUpdatesPaused&&(C={...C,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(Z.type==="frontend.replace"){if(C.frontend&&sv(mn,e,Z)){const fe=Z.payload.frontend,Ve=Ld(C.frontend,fe.snapshot,Z.payload.cold===!0);C={...C,contextCarried:Object.keys(Ve).length>0,frontend:{...fe.snapshot,...Ve,attention:fr(C.frontend.attention,fe.snapshot.attention,e)},ownerEpoch:fe.epoch,cold:Z.payload.cold,...C.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(Z.type==="event"){const fe=String(Z.payload.type??"");if(Z.payload.action==="reload"){C={...C,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}BS.has(fe)&&(C={...C,terminal:fe}),Bd.has(fe)&&(C={...C,turnsCompleted:C.turnsCompleted+1});const Ve=ha(C.transcript,Z.payload,ft,{frame:{epoch:Z.epoch,seq:Z.seq},userStoppedAt:e?yt.getState().stoppedTurns[e]??null:null,queuedAskEngine:Hp(C.frontend)});Ve!==C.transcript&&(C={...C,transcript:Ve});const Y=NS(C.subagentPulses,Z.payload);Y!==C.subagentPulses&&(C={...C,subagentPulses:Y})}}if(!we&&Ee){for(const Z of Ee.index.keys())C.transcript.index.has(Z)||x.current.add(Z);C={...C,transcript:Ee}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),S.current=C.transcript.index,!US(te))return j;if(Cn.length>0){const Z=new Set(C.labelPending);for(const mn of Cn)Z.add(mn);C={...C,labelPending:Z}}return C.frontend!==null&&C.frontend!==C.heldFrontend&&(C={...C,heldFrontend:C.frontend}),C}),Cn.length>0){for(const j of Cn)E.current.painted.add(j);for(;E.current.painted.size>eE;){const j=E.current.painted.values().next().value;if(j===void 0)break;E.current.painted.delete(j)}}const Jt=st||ve,tr=js.length>0&&bt.length===0&&Pt.length===0&&!Jt&&!Qe;if(Jt||hn.length>0||Qe){const j=new Set(hn),C=E.current.order;Ms($,_t,hn.length>0?{targets:j,order:C,starts:E.current.starts,waiting:E.current.waiting,every:new Set([...C,...j]),found:new Set(Si(te.flatMap(we=>we.type==="snapshot"?we.payload.history.entries:[]),new Set(C))),pending:Cn}:Gd,1,tr?we=>{E.current.settleRows+=we}:void 0,ne,se)}},xr=()=>{const te=ee;if(ee=null,f.current=null,h.current+=1,g.current&&(window.clearTimeout(g.current),g.current=0),y.current+=1,!!te){ut=!0;try{te()}finally{ut=!1}}},Cr=()=>{const te=sa(P.current.transcript),ne=++Pe.current;Fe(),xe=window.setTimeout(()=>{xe=0,re.current===$&&(xr(),T(se=>({...se,subscriptionId:null,status:"unavailable",failure:Nd(Yr.ended),...se.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ke&&(Ke=!0,Te=window.setTimeout(()=>{Te=0,re.current===$&&nl()},zS)))},GS);const be=p();ee=vv({sessionId:e,epoch:X.current.epoch,afterSeq:X.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:i,orderIds:Gt(P.current.transcript).slice(0,512),...be?{peerJournalSource:!0}:{}}:{}},se=>{if(re.current===$&&Pe.current===ne){if(se.kind==="error"||se.kind==="end"){if(ut)return;if(Fe(),xr(),se.kind==="error"&&se.status===404){if(!n){e&&yt.getState().retireDraftWarm(e),T(ve=>({...ve,subscriptionId:null}));return}e&&(yS(e),AS(e),xS(e),yt.getState().retireDraftsForSession(e)),T(ve=>({...ve,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...ve.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const ke=se.kind==="error"?se.detail??v("ui.common.errors.event_stream_failed"):v("ui.common.errors.event_stream_closed");if(T(ve=>({...ve,subscriptionId:null})),Xe>=WS){T(ve=>({...ve,status:"unavailable",failure:Nd(ke),...ve.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}Xe+=1;const Ce=F.current;Ce&&(X.current={epoch:Ce.epoch,afterSeq:Ce.seq}),T(ve=>ve.status==="unavailable"&&Xe>1?ve:{...ve,status:"reconnecting",failure:null}),H=window.setTimeout(()=>{H=0,re.current===$&&Cr()},Ud(Xe));return}if(se.data!==void 0)try{const ke=se.data,Ce=ke.length>=YS;Ce&&performance.mark("lop:open:parse:start");const ve=JSON.parse(ke);ve.type==="snapshot"&&J.set(ve,te),Ce&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),ve.type==="snapshot"&&(Xe=0,Fe(),Ke=!1),w.current.push(ve),ze||(ze=requestAnimationFrame(el)),ye||(ye=window.setTimeout(el,ZS))}catch{}}}),f.current={sessionId:e,peer:be},h.current+=1},tl=()=>{H!==0&&(window.clearTimeout(H),H=0),X.current={},F.current=null,xr(),Cr()},nl=()=>{Xe=0,Te&&(window.clearTimeout(Te),Te=0),H&&(window.clearTimeout(H),H=0),Re&&(window.clearTimeout(Re),Re=0),T(te=>({...te,failure:null,status:te.status==="unavailable"?"connecting":te.status,transcript:Ks(te.transcript,!1)})),P.current.hydrated||Ms($,new Set(P.current.transcript.index.keys())),!ee&&Cr()};Cr(),$e.current=nl,We.current=()=>{P.current.liveUpdatesReloading||(T(te=>({...te,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Xe=0,H&&(window.clearTimeout(H),H=0),Te&&(window.clearTimeout(Te),Te=0),tl())},K.current=()=>{!P.current.hydrated&&he.current===0&&Ms($,new Set(P.current.transcript.index.keys()))};const fm=rE(e,tl),rl=()=>{if(!t||!e||b.current===e)return;const te=f.current;te===null||te.sessionId!==e||te.peer||p()&&(b.current=e,xr(),Cr())};_.current=rl;const pm=yt.subscribe(()=>{rl()});return()=>{re.current+=1,$e.current=null,K.current=null,We.current=null,_.current=null,pm(),g.current&&(window.clearTimeout(g.current),g.current=0),fm(),xr(),ze&&cancelAnimationFrame(ze),ye&&clearTimeout(ye),H&&clearTimeout(H),Re&&clearTimeout(Re),De.current&&(window.clearTimeout(De.current),De.current=0),Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),Te&&window.clearTimeout(Te),Fe(),w.current=[]}},[T,e,t,n,i,p,R,k]),I.useEffect(()=>{!e||!t||_.current?.()},[e,t,d]),I.useEffect(()=>{X.current={},F.current=null,S.current=$t.index;const $=fE(m.current,e,n);m.current=e;const J=e?eh(e):null;S.current=$?P.current.transcript.index:(J?.transcript??$t).index;const de=new Set($?x.current:[]);for(const ee of J?.replayBorn??[])de.add(ee);const Le=$?P.current.transcript.index:(J?.transcript??$t).index;for(const ee of de)Le.has(ee)||de.delete(ee);x.current=de,$||(N.current=new Set),T(ee=>({...ee,frontend:null,heldFrontend:$?ee.heldFrontend:null,contextCarried:$?ee.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:$?ee.turnsCompleted:0,transcript:$?ee.transcript:J?.transcript??$t,stale:$?ee.stale:J!==null,missing:$?ee.missing:!1,status:"connecting",subagentPulses:{},labelPending:J?.owedLabels??$n,labelMarked:J?.markLabels??Kr,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),E.current=Kd(e)},[e,n]),I.useEffect(()=>{if(e)return()=>{const $=P.current.transcript;$.records.length>0&&vS(e,{transcript:$,owedLabels:new Set([...P.current.labelPending].filter(J=>Ci(E.current,P.current.transcript.argsByCall,J,xi(P.current)))),markLabels:new Set(P.current.labelMarked),replayBorn:new Set(x.current)});for(const J of z.current)E.current.inFlight.delete(J);z.current.clear()}},[e]);const De=I.useRef(0);I.useEffect(()=>{if(O.labelPending.size===0&&O.labelMarked.size===0){De.current&&(window.clearTimeout(De.current),De.current=0);return}if(De.current)return;const $=()=>{De.current=0;const J=P.current.labelPending,de=P.current.labelMarked;if(J.size===0&&de.size===0)return;const Le=E.current;for(const ee of J)if(Le.inFlight.has(ee)){De.current=window.setTimeout($,Ti);return}for(const ee of de)if(Le.inFlight.has(ee)){De.current=window.setTimeout($,Ti);return}T(ee=>ee.labelPending.size===0&&ee.labelMarked.size===0?ee:{...ee,labelPending:$n,labelMarked:Kr})};De.current=window.setTimeout($,Ti)},[T,O.labelPending,O.labelMarked]);const Ge=I.useRef(0);I.useEffect(()=>{if(O.labelPending.size===0){Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),T($=>$.labelHoldLate?{...$,labelHoldLate:!1}:$);return}O.labelHoldLate||Ge.current||(Ge.current=window.setTimeout(()=>{Ge.current=0,T($=>$.labelPending.size===0||$.labelHoldLate?$:{...$,labelHoldLate:!0})},JS))},[T,O.labelPending,O.labelHoldLate]);const qe=I.useRef(e);qe.current=e;const me=I.useRef({id:e,epoch:0});me.current.id!==e&&(me.current={id:e,epoch:me.current.epoch+1});const Ie=I.useRef(null);Ie.current===null&&(Ie.current=CS());const Et=I.useRef(!1),Ne=I.useRef(null),[Ct,_e]=I.useState(0);I.useEffect(()=>{const $=O.transcript,J=Gt($);if(!e||!i||!$.orderNeedsReconcile&&(!$.journalGeneration||J.length===0)||Et.current)return;const de=H=>({fields:JSON.stringify([Ct,e,H.viewEpoch,At(H),H.orderNeedsReconcile,H.orderWantedGeneration,Gt(H)]),demand:H.orderDemand}),Le=de($);if(Ne.current?.fields===Le.fields&&Ne.current.demand===Le.demand)return;Ne.current=Le;const ee=e,ut=$.viewEpoch;Et.current=!0;let ze=null,ye=$;const Xe=H=>{if(!H.peer||qe.current!==ee||P.current.transcript.viewEpoch!==ut||h.current!==H.streamEpoch)return;const Re=H.kind==="authority"?H.frame.payload.history:H.page,xe=Re.journal_order_state;if(xe==="ready"){g.current&&(window.clearTimeout(g.current),g.current=0),T(Ke=>{const Fe=Ks(Ke.transcript,!1);return Fe===Ke.transcript?Ke:{...Ke,transcript:Fe}});return}if(xe==="unavailable"){if(g.current&&(window.clearTimeout(g.current),g.current=0),Re.reconcile===!0)return;T(Ke=>{const Fe=Ks(Ke.transcript,!0);return Fe===Ke.transcript?Ke:{...Ke,transcript:Fe}});return}if(xe!=="building")return;g.current&&(window.clearTimeout(g.current),g.current=0);const Te=++y.current;g.current=window.setTimeout(()=>{g.current=0,y.current===Te&&qe.current===ee&&P.current.transcript.viewEpoch===ut&&h.current===H.streamEpoch&&T(Ke=>{const Fe=Ks(Ke.transcript,!0);return Fe===Ke.transcript?Ke:{...Ke,transcript:Fe}})},KS)};$v({getTranscript:()=>P.current.transcript,isCurrent:()=>qe.current===ee&&P.current.transcript.viewEpoch===ut,sweep:(H,Re)=>{if(!R())return;if(H.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${ee}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const xe=H.journalGeneration;if(typeof xe!="string"||xe.length===0)return{kind:"none",path:`/v1/desktop/sessions/${ee}/history`,query:new URLSearchParams};if(Df(H,Re?.("lookup")).length>0){const Fe=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:xe});return{kind:"lookup",path:`/v1/desktop/sessions/${ee}/history`,query:Fe}}if(tc(H).length>0){const Fe=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:xe});return{kind:"payload",path:`/v1/desktop/sessions/${ee}/history`,query:Fe}}return{kind:"none",path:`/v1/desktop/sessions/${ee}/history`,query:new URLSearchParams}},read:async(H,Re)=>{ye=P.current.transcript,Ne.current=de(ye);const xe=R(),Te=h.current;if(Re==="lookup"||Re==="payload"){const Fe=P.current.transcript.journalGeneration,Ps=await Ze({op:"sessions.history",sessionId:ee,limit:100,journalOrder:!0,orderIds:H,peerJournalSource:!0,sourceRead:Re==="payload"?"payload":"metadata",...typeof Fe=="string"&&Fe.length>0?{expectedJournalGeneration:Fe}:{}});return Re==="payload"?{kind:"payload",page:Ps,peer:xe,streamEpoch:Te}:{kind:"lookup",page:Ps,peer:xe,streamEpoch:Te}}return{kind:"authority",frame:await Ze({op:"sessions.get",sessionId:ee,journalOrder:!0,orderIds:H,...xe?{peerJournalSource:!0}:{}}),peer:xe,streamEpoch:Te}},page:H=>H.kind==="authority"?H.frame.payload.history:H.page,lookupPath:`/v1/desktop/sessions/${ee}`,commit:(H,Re,xe)=>{H.peer&&h.current!==H.streamEpoch||(T(Te=>qe.current!==ee||At(Te.transcript)!==Re||Te.transcript.viewEpoch!==ut?Te:{...Te,transcript:H.kind==="authority"?H.peer?Sd(Te.transcript,H.frame.payload.history,{authoritative:!0,orderRead:xe}):Dk(Te.transcript,H.frame.payload.history,xe):H.kind==="payload"?Nk(Te.transcript,H.page,xe,Re):Sd(Te.transcript,H.page,{authoritative:!1})}),Xe(H))}}).then(H=>{ze=H.kind==="complete"?H.transcript:null}).catch(H=>{console.warn("[canonical] source-order reconcile refused",H)}).finally(()=>{Et.current=!1;const H=P.current.transcript,Re=ze??ye;ze&&qe.current===ee&&H.viewEpoch===ut&&!H.orderNeedsReconcile&&(Ne.current=de(Re)),(qe.current!==ee||H.viewEpoch!==ut||At(H)!==At(Re)||H.orderWantedGeneration!==Re.orderWantedGeneration||H.orderNeedsReconcile!==Re.orderNeedsReconcile||H.orderDemand!==Re.orderDemand||JSON.stringify(Gt(H))!==JSON.stringify(Gt(Re)))&&_e(xe=>xe+1)})},[T,e,i,R,O.transcript,Ct]);const Se=I.useCallback(async()=>{const $=Ie.current;if(!e||!$)return{kind:"nothing-to-load"};const J=e,de=me.current.epoch,Le=()=>me.current.epoch===de,ee=P.current.transcript.viewEpoch,ut=()=>P.current.transcript.viewEpoch===ee,ze=await $.load(`${J}#${de}`,{getTranscript:()=>P.current.transcript,readPage:ye=>Ze({op:"sessions.history",sessionId:J,beforeId:ye,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Gt(P.current.transcript).slice(0,512),...R()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>Le()&&ut(),commit:ye=>T(Xe=>{const H=ye(Xe.transcript);return H===Xe.transcript?Xe:{...Xe,transcript:H}}).transcript,setLoading:ye=>{Le()&&T(Xe=>Xe.loadingOlder===ye?Xe:{...Xe,loadingOlder:ye})},peerSource:k});return Le()&&(ze.kind==="failed"?T(ye=>ye.olderFailed?ye:{...ye,olderFailed:!0}):ze.kind==="applied"&&T(ye=>ye.olderFailed?{...ye,olderFailed:!1}:ye)),ze},[T,e,R,k]),dt=I.useCallback(async()=>(await Se()).kind==="applied",[Se]),mt=I.useRef(!1),Ot=I.useCallback(async($,J)=>{if(!e||mt.current)return!1;const de=e;mt.current=!0;const Le=At(P.current.transcript),ee=F.current,ut=ee?{epoch:ee.epoch,seq:ee.seq}:null;try{const ze=await Ze({op:"sessions.history",sessionId:de,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Gt(P.current.transcript).slice(0,512),...R()?{peerJournalSource:!0}:{}}:{}});return qe.current!==de||At(P.current.transcript)!==Le||P.current.transcript.viewEpoch!==J?!1:(T(ye=>At(ye.transcript)!==Le?ye:{...ye,transcript:Jr(ye.transcript,ze,{keepPaging:!0,peerSource:k(),readWitness:ut})}),Oi(x.current,ze.entries),Zs(N.current,ze.entries),iS(ze.entries,$))}catch{return!1}finally{mt.current=!1}},[T,e,R,k]);I.useEffect(()=>r?dE(r,J=>{T(de=>{const Le=J(de.transcript);return Le===de.transcript?de:{...de,transcript:Le}})}):void 0,[T,r]),I.useEffect(()=>{r&&lE(r,O.transcript)},[r,O.transcript]);const Tr=I.useCallback(()=>{T($=>({...$,transcript:eS($.transcript),olderFailed:!1,heldFrontend:null}))},[T]),qn=I.useCallback(()=>{$e.current?.()},[]),Yc=I.useCallback(()=>{We.current?.()},[]),Qc=I.useCallback(()=>{K.current?.()},[]),Xc=I.useCallback(($,J="info")=>{T(de=>({...de,transcript:rS(de.transcript,$,J)}))},[T]),Jc=I.useCallback($=>{T(J=>({...J,pendingModel:$}))},[T]),qc=I.useCallback(()=>{T($=>$.pendingModel===null?$:{...$,pendingModel:null})},[T]);return I.useEffect(()=>{const $=O.pendingModel;if(!$)return;const J=Ei($);if(!J)return;const de=O.frontend;(Ei(de?.selected_model)===J||Ei(de?.effective_model)===J)&&T(Le=>({...Le,pendingModel:null}))},[T,O.frontend,O.pendingModel]),I.useEffect(()=>{if(!O.pendingModel)return;const $=window.setTimeout(()=>T(J=>({...J,pendingModel:null})),HS);return()=>window.clearTimeout($)},[T,O.pendingModel]),I.useMemo(()=>({...O,awaitingHydration:t&&!!e&&n&&!O.hydrated,loadOlder:dt,loadOlderDetailed:Se,refreshTail:Ot,clearView:Tr,addNote:Xc,paintPendingModel:Jc,clearPendingModel:qc,retry:qn,rehydrate:Qc,reloadFromHistory:Yc}),[O,t,e,n,dt,Se,Ot,Tr,Xc,Jc,qc,qn,Qc,Yc])}function Wo(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
41
+
42
+ `)?e:`${t}
43
+
44
+ ${e}`}const Pi={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function so(e,t,n){const r=[...e.attachments??[]],s=[],o=[],i=new Set;for(const h of t.attachments){const g=r.find(b=>b.path===h&&!i.has(b.id));if(g){i.add(g.id),o.push(g.id);continue}const y={id:n(),path:h};s.push(y),o.push(y.id)}const c=[...e.replies??[]],l=t.replies.filter(h=>!c.some(g=>g.id===h.id)),d=t.text,u=[...s,...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:Wo(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:o,replyIds:t.replies.map(h=>f.find(g=>g.id===h.id)?.id).filter(h=>h!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function gE(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 s=0;s+r<=n.length;s++)if(t.includes(n.slice(s,s+r)))return!0;return!1}function _E(e){return{text:Wo(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function bE(e,t){if(!e||!t)return!1;const n=_E(e),r=e.attachments??[],s=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((o,i)=>o.id===t.chipIds[i])&&s.length===t.replyIds.length&&s.every((o,i)=>o.id===t.replyIds[i])}function vE(e,t=()=>crypto.randomUUID()){const n={};for(const[r,s]of Object.entries(e??{}))n[r]=s.inFlight?so(s,s.inFlight,t):s;return n}function yE(e,t){const n=t.text,r=Wo(e.currentInput??"",e.pendingText??"");let s=r,o="overlap";n===""?o="draft-only":r.startsWith(n)&&(s=r.slice(n.length).replace(/^\n+/,""),o="draft-only");const i=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:s,pendingText:void 0,attachments:(e.attachments??[]).filter(l=>!i.has(l.id)),replies:(e.replies??[]).filter(l=>!c.has(l.id)),unredactedChars:n===""?e.unredactedChars??0:0},box:o}}const it=Rs()(Uo((e,t)=>({inputByConversation:{},addReply:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},o=Array.isArray(s.replies)?s.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...s,replies:[...o,r]}}})},removeReply:(n,r)=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,replies:s.replies.filter(o=>o.id!==r)}}})},clearReplies:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:[]}}})},addAttachment:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},o=Array.isArray(s.attachments)?s.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...s,attachments:[...o,r]}}})},removeAttachment:(n,r)=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,attachments:s.attachments.filter(o=>o.id!==r)}}})},clearAttachments:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[]}}})},setCurrentInput:(n,r,s=0)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...o,lateDelivered:o.lateDelivered==="overlap"&&!gE(o,r)?void 0:o.lateDelivered,currentInput:r,unredactedChars:r?s:0}}})},getUnredactedChars:n=>t().inputByConversation[n]?.unredactedChars||0,getCurrentInput:n=>t().inputByConversation[n]?.currentInput||"",addSubmittedMessage:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},o=s.submittedMessages[s.submittedMessages.length-1],i=r&&r!==o?[...s.submittedMessages.slice(-19),r]:s.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...s,submittedMessages:i}}})},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 s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},o=s.submittedMessages;let i=null;typeof r=="number"&&o.length>0&&(i=Math.max(0,Math.min(r,o.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentHistoryIndex:i}}})},resetCurrentHistoryIndex:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentHistoryIndex:null}}})},clearAll:n=>{const{[n]:r,...s}=t().inputByConversation;e({inputByConversation:s})},restoreRow:(n,r)=>{e({inputByConversation:{...t().inputByConversation,[n]:{...r,textRevision:(r.textRevision??0)+1}}})},beginInFlight:(n,r,s=!0)=>{const o=t().inputByConversation[n]??Pi,i=new Set(r.attachments.map(d=>d.id)),c=new Set(r.replies.map(d=>d.id)),l=o.currentInput===r.text;e({inputByConversation:{...t().inputByConversation,[n]:{...o,currentInput:l?"":o.currentInput,unredactedChars:l?0:o.unredactedChars,textRevision:l?(o.textRevision??0)+1:o.textRevision,attachments:(o.attachments??[]).filter(d=>!i.has(d.id)),replies:(o.replies??[]).filter(d=>!c.has(d.id)),inFlight:s?{text:r.text,attachments:r.attachments.map(d=>d.path),replies:[...r.replies],unredactedChars:l?o.unredactedChars:0,volatileText:r.volatileText}:o.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const r={...t().inputByConversation};let s=!1;for(const o of n){const i=r[o];!i||!i.inFlight&&!i.returned||(r[o]={...i,inFlight:void 0,returned:void 0},s=!0)}s&&e({inputByConversation:r})},returnInFlight:(n,r)=>{const s={...t().inputByConversation},o=s[n],i=o?.inFlight??s[r]?.inFlight;let c=s[r]??Pi;n!==r&&o&&(c=so(c,{text:o.currentInput??"",attachments:(o.attachments??[]).map(l=>l.path),replies:o.replies??[],unredactedChars:o.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:s[r]?.returned},delete s[n]),i&&(c=so(c,i,()=>crypto.randomUUID())),!(!i&&n===r)&&(s[r]=c,e({inputByConversation:s}))},adoptReturnedText:n=>{const r=t().inputByConversation[n];if(r?.pendingText===void 0)return null;const s=Wo(r.currentInput??"",r.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:s,pendingText:void 0,textRevision:(r.textRevision??0)+1}}}),s},returnPayload:(n,r)=>{const s=t().inputByConversation[n]??Pi;s.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:so(s,r,()=>crypto.randomUUID())}})},reconcileDelivered:n=>{const r=t().inputByConversation[n];if(!r)return;const s=f=>(f.currentInput??"")===""&&(f.attachments??[]).length===0&&(f.replies??[]).length===0,o=r.returned!==void 0||r.inFlight!==void 0,i=r.returned?bE(r,r.returned):s(r),c=r.returned?yE(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&&!s(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:o&&r.returned?.text?"overlap":o?"delivered":void 0,lateDeliveredText:o?r.returned?.text:void 0};e({inputByConversation:{...t().inputByConversation,[n]:i||c!==null&&s(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 s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:r,unredactedChars:s.unredactedChars??0,textRevision:(s.textRevision??0)+1}}})}}),{name:"conversation-input-store",partialize:e=>({inputByConversation:Object.fromEntries(Object.entries(e.inputByConversation).map(([t,n])=>{let r=n;return r.inFlight?.volatileText&&(r={...r,inFlight:{...r.inFlight,text:""}}),r.returned?.volatileText&&(r={...r,returned:{...r.returned,text:""}}),r.volatilePendingText&&(r={...r,pendingText:void 0}),r.volatilePendingText&&(r={...r,lateDeliveredText:void 0}),[t,r]}))}),merge:(e,t)=>({...t,inputByConversation:vE(e?.inputByConversation)})}));function oh(e){if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null}function sO(e,t){return t?e.filter(n=>n.session_id===t&&ih(n)).length:0}function ih(e){if(oh(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function wE(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function oO(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 iO={cwd:""};function kE(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,wE(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function SE(e){return(await Ze({op:"sessions.preview",requestId:crypto.randomUUID(),cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}})).frontend}function aO(e,t){const n=e.trim();if(!n)return{checked:!0,rung:null,confirmation:s=>`This conversation will run ${s}.`};if(!t.ladderKnown)return{checked:!1,rung:null,refusal:"Nothing was changed, because that model's effort levels could not be read. Try again."};const r=t.ladder.find(s=>s.trim().toLowerCase()===n.toLowerCase());return r?{checked:!0,rung:r,confirmation:s=>`This conversation will run ${s} at ${r} effort.`}:{checked:!0,rung:null,confirmation:s=>t.level?`This conversation will run ${s}. Its effort is now ${t.level}, because ${n} is not one of that model's levels.`:`This conversation will run ${s}. No effort level is set on it, because ${n} is not one of that model's levels.`}}function cO(e,t){return e!==!0?null:t==="on"?"Fast mode stays on for this model.":t==="off"?"Changing the model turned fast mode off.":"This model does not support fast mode, so it stays off."}const lO="Fast mode is off: this version of the Local Operator service cannot carry it.",dO="fast_unavailable";function Ec(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function uO(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function fO(e){const t=e instanceof Oe?e:null;return t?.code==="fast_mode_unsupported"?"This model cannot run fast mode. Pick a model that can.":t?.status===422?"Fast mode is not available on this version of the Local Operator service. Update Local Operator, then try again.":"Fast mode was not changed. Try again."}function pO(e,t){const n={...e,model:Ec(e.model,t)};return{queryKey:kE(n),queryFn:()=>SE(n),placeholderData:Sm,staleTime:3e4,retry:!1}}function ae(e){return typeof e=="string"?e.trim():""}function ar(e){const t=ae(e);return t||null}function xn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Vr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function ah(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function Gn(e,t){return typeof e=="boolean"?e:t}function ya(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Rr(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 Rr(t)}return[]}function EE(e){if(!wn(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:ah(e.attempts),last_frame_at:xn(e.last_frame_at),next_retry_at:xn(e.next_retry_at),last_error:ae(e.last_error)}}function wn(e){return typeof e=="object"&&e!==null}const AE=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function RE(e,t){const n=ae(e);return AE.includes(n)?n:t?"reachable":"unreachable_legacy"}const IE=["running","not_listening","unknown"];function TE(e){const t=ae(e);return IE.includes(t)?t:void 0}function xE(e){if(Array.isArray(e))return e.filter(wn).map(t=>({endpoint:ae(t.endpoint),connected:t.connected===!0,detail:ae(t.detail),latency_ms:xn(t.latency_ms)})).filter(t=>t.endpoint!=="")}function hO(e){const t=new Set,n=[];for(const i of Rr(e)){const c=ae(i.device_id);if(!c||t.has(c)||typeof i.reachable!="boolean")continue;t.add(c);const l=TE(i.remote_relay),d=xE(i.attempts),u=i.reachable?void 0:EE(i.redial);n.push({device_id:c,name:ae(i.name),reachable:i.reachable,link_state:RE(i.link_state,i.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:ar(i.unreachable_reason??i.reason),last_seen_at:xn(i.last_seen_at),session_count:Vr(i.session_count),rtt_ms:xn(i.rtt_ms)})}const r=wn(e)?e:{},s=ae(r.self_device_id),o=ya(r.degraded);return{peers:n,...s?{self_device_id:s}:{},...o.length?{degraded:o}:{}}}function CE(e){const t=ae(e.device_id);return t?{device_id:t,name:ae(e.name),role:ae(e.role),capabilities:ya(e.capabilities),active:Gn(e.active,!0),suspect:Gn(e.suspect,!1),endpoints:ya(e.endpoints),last_seen_at:xn(e.last_seen_at),reachable:Gn(e.reachable,!0),reason:ae(e.reason??e.unreachable_reason),scope:ae(e.scope)}:null}function OE(e){const t=ae(e.network_id);return t?{network_id:t,name:ae(e.name),epoch:ah(e.epoch),trust:ae(e.trust),members:Rr(e.members).map(CE).filter(n=>n!==null)}:null}function mO(e){const t=wn(e)?e:{},n=ae(t.self_device_id);return{networks:Rr(t.networks).map(OE).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function PE(e){return e.live_state.trim().toLowerCase()==="busy"}function gO(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const s of Rr(r)){const o=ae(s.id);if(!o||n.has(o))continue;const i=s.locality==="remote"?"remote":ae(s.locality)==="local"?"local":null;if(!i)continue;n.add(o);const c=wn(s.status)?{code:ae(s.status.code),label:ae(s.status.label)}:null,l=wn(s.binding)?{agent:ar(s.binding.agent),team:ar(s.binding.team)}:null,d=wn(s.opened_by)?{agent:ar(s.opened_by.agent),label:ar(s.opened_by.label),session:ar(s.opened_by.session)}:null;t.push({id:o,name:ae(s.name),mtime:xn(s.mtime)??0,locality:i,owner_device:ae(s.owner_device),owner_device_name:ae(s.owner_device_name),reachable:Gn(s.reachable,!0),unreachable_reason:ae(s.unreachable_reason),live_state:ae(s.live_state),archived:Gn(s.archived,!1),created_at:xn(s.created_at),pinned:Gn(s.pinned,!1),...typeof s.active=="boolean"?{active:s.active}:{},waiting_on:Vr(s.waiting_on),jobs_running:Vr(s.jobs_running),subagents_running:Vr(s.subagents_running),subagents_queued:Vr(s.subagents_queued),...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function _O(e){const{id:t,name:n,mtime:r,...s}=e;return{...s,session_id:t,title:n,updated_at:r}}function bO(e){if(!wn(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:Gn(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:Rr(e.phases).map(s=>({phase:ae(s.phase),peer:ae(s.peer),progress:typeof s.progress=="number"?s.progress:0}))}:null}const ME=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function vO(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)||v("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||ME.has(n)}}function yO(e){const t=ae(e.name);return t||v("ui.mesh.mesh_types.device_suffix",{suffix:ae(e.device_id).slice(-6)})}function jE(e){const t=ae(e.name);return t?JSON.stringify(t):v("ui.mesh.mesh_types.unnamed_device")}function $E(e,t){const n=ae(e);if(!t)return n;const r=t.map(ae).filter(o=>o.length>0&&o!==n);let s=Math.min(10,n.length);for(;s<n.length&&r.some(o=>o.startsWith(n.slice(0,s)));)s+=1;return s<n.length?`${n.slice(0,s)}…`:n}function wO(e,t,n=!1){const r=n?$E(e.id,t):ae(e.id);return`${jE(e)} ${r}`}function kO(e){const t=ae(e.name);return t||v("ui.mesh.mesh_types.network_suffix",{suffix:ae(e.network_id).slice(-6)})}const DE=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function NE(e){const t=e.trim();return t!==""&&DE.includes(t)}function ch(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"||NE(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const SO=()=>v("ui.mesh.mesh_graph.identity_suspect");function lh(e){switch(e){case"self":return v("ui.mesh.mesh_drop.this_device");case"reached":return v("ui.mesh.mesh_reach.reached");case"relay-down":return v("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return v("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return v("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return v("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return v("ui.mesh.mesh_reach.not_a_member");case"unanswered":return v("ui.mesh.mesh_reach.no_answer");case"not-attempted":return v("ui.mesh.mesh_reach.not_asked");default:return v("ui.mesh.mesh_reach.unknown")}}function EO(e){const t=ch(e),n=lh(t);return e.reason?`${n} — ${e.reason}`:n}const AO={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"},RO={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function IO(e){const t=e.trim();switch(t){case"ok":return v("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return v("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return v("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return v("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return v("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?v("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function TO(e){return e.reachable?"":e.remoteRelay==="not_listening"?v("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?v("ui.mesh.mesh_reach.peer_closed_handshake"):""}function xO(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>PE(r))?"working":"idle",source:"derived"}}function LE(e,t){const n={...e};for(const[r,s]of Object.entries(t))(!n[r]||s.at>=n[r].at)&&(n[r]=s);return n}function UE(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=ch({state:"unreachable",reachable:n.reachable,reason:n.reason??"",sessionCount:n.session_count??null}),s=r==="unanswered",o=s&&n.redial_state==="reconnecting";return e.peer_reach===r&&e.link_down===s&&(e.link_reconnecting??!1)===o&&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:s,link_reconnecting:o,peer_reach:r,last_seen_at:n.last_seen_at,link_down_reason:n.reason}}function CO(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${v("ui.chat.canonical.transcript.reconnecting")} · ${wa(n,t)}`:v("ui.presence.link_down_last_seen",{age:wa(n,t)})}function wa(e,t){if(e===null)return v("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?v("ui.presence.just_now"):n<3600?v("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?v("ui.presence.hours_ago",{count:Math.floor(n/3600)}):v("ui.presence.days_ago",{count:Math.floor(n/86400)})}function OO(e,t){if(e.link_reconnecting===!0)return v("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return v("ui.presence.link_down_compact",{age:wa(n,t)})}function FE(e,t,n,r){if(r<=n)return{facts:e,watermark:n,removed:[]};const s=Object.fromEntries(Object.entries(e).filter(([,o])=>o.at>r));for(const[o,i]of Object.entries(t))(!s[o]||i.at>=s[o].at)&&(s[o]=i);return{facts:s,watermark:r,removed:Object.keys(e).filter(o=>!s[o])}}function PO(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?lh(e.peer_reach):null}function MO(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?v("ui.chat.canonical.untitled"):n==="this chat"?v("ui.chat.canonical.this_chat"):n:t==="this_chat"?v("ui.chat.canonical.this_chat"):v("ui.chat.canonical.untitled")}function ka(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 Ys=(e,t)=>e instanceof Oe?qa(e,t):e instanceof Error?e.message:t,Go="session_unvalidated",BE=()=>v("ui.common.errors.session_unvalidated"),Io="leading_slash_message",dh=()=>v("ui.common.errors.leading_slash_message");function HE(e,t){return e instanceof Oe&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const uh="attachment_read_failed",fh="store_out_of_space",ph="store_unavailable";function Yd(e){return e===fh||e===ph}const WE="answer_not_sent",hh="aside_not_answered",mh="aside_still_answering";function Zr(e){return e===Io||e===uh||e===fh||e===ph||e===WE||e===hh||e===mh||e===Go||e===No}function GE(e){return e instanceof Oe&&e.status===409&&Ac(e)===void 0}function gh(e,t=!1){return VE(e)||GE(e)&&!t?"not_sent":e instanceof Oe&&e.status===404?"gone":"unknown"}function Ac(e){if(e instanceof Oe||e instanceof In)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const pt={get unconfirmed(){return v("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return v("ui.chat.canonical.send_failure.unreachable")},get busy(){return v("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return v("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return v("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return v("ui.chat.canonical.send_failure.retiring")},get notReady(){return v("ui.chat.canonical.send_failure.not_ready")},get generic(){return v("ui.chat.canonical.send_failure.generic")},get gone(){return v("ui.chat.canonical.send_failure.gone")},get sendLock(){return v("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return v("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return v("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return v("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return v("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return v("ui.chat.canonical.send_failure.late_delivery_overlap")}};function jO(e){return e?pt.gateLock:pt.sendLock}const $O=()=>v("ui.common.actions.retry"),DO=()=>v("ui.common.actions.clear");function zE(e,t,n=!1){const r=gh(e,n),s=t??Ac(e),o=qa(e,pt.generic);return r==="gone"?{message:pt.gone,retry:!1,code:s}:r==="not_sent"?s===No?{message:pt.busy,retry:!0,code:s}:s===gf?{message:pt.retiring,retry:!0,code:s}:s===Go?{message:pt.notReady,retry:!Zr(s),code:s}:s===hh?{message:pt.asideNotAnswered,retry:!1,code:s}:s===mh?{message:pt.asideStillAnswering,retry:!1,code:s}:s===Io?{message:dh(),retry:!1,code:s}:{message:o,retry:!1,code:s}:s===Tt.transportFailed?{message:pt.unreachable,retry:!0,code:s}:Lo(s)?{message:Ja(s),retry:!1,code:s}:s===Xa?{message:pt.unconfirmed,retry:!Zr(s),code:s}:s===_b.runtimeUnreachable?{message:pt.unconfirmed,retry:!0,code:s}:s?{message:o,retry:!Zr(s),code:s}:{message:pt.unconfirmed,retry:!Zr(s),code:s}}function Sa(e){return e.trim()}function NO(e,t){if(t.length===0)return Sa(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
45
+ `);return Sa(`${n}
46
+ ${e}`)}function Ea(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function KE(e,t,n,r){if(t.peer!==void 0||n?.locality==="remote"||r?.locality==="remote")return!1;const s=t.submittedAt;if(s===void 0||s<=0)return!1;const o=e[0]?.ts;return o===void 0||o<=0?!1:o*1e3<=s}function LO(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,o])=>Ea(o,t));return(r.find(([,o])=>o.submittedText!==void 0||o.undelivered!==void 0||o.error!==void 0||o.admissionAttempted===!0||o.pending===!0)??r[0])?.[0]??`send:${t}`}function Rc(e,t){return t??e??void 0}function _h(e,t,n){return e?t??void 0:n??void 0}function UO(e,t,n){return Rc(e,_h(e,t,n))}function VE(e){return e instanceof Oe?e.status===413||e.status===422?!0:e.code===No||e.code===gf||e.code===Tt.noCredential||Yd(e.code):e instanceof In&&(e.code===Go||e.code===uh||Yd(e.code))}function xs(e,t){const n=e.startsWith("send:")?e.slice(5):null;return Rc(e.startsWith("draft:")?e:null,t??n)??e}function ZE(e,t){const n=it.getState(),r=xs(e,t),s=r===""||r===e?[e]:[e,r];n.settleInFlight(s),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function FO(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=xs(e,t.sessionId);return it.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),yt.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:pt.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!Zr(t.heldClaimCode),heldClaimCode:void 0}),!0}function BO(e,t){if(!t)return!1;const n=t.undelivered,r=t.submittedText,s=r!==void 0&&t.error!==void 0&&t.errorRetry!==void 0;if(!n&&!s)return!1;const o=xs(e,t.sessionId);if(n){if(Vd(o,n.recordId))return!1;const c=sh(o,n.recordId);return c!=="unseen"?(c==="owner"&&yt.getState().retractUndelivered(e,n.recordId),!1):(_a(o,{id:n.recordId,text:n.text,images:[],documents:ka(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const i=t.admissionRequestId;return Vd(o,i)?!1:(_a(o,{id:i,text:t.submittedRendered??r,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${i}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type})),documents:ka(t.submittedFiles??[],i)}),!0)}function Qd(e,t,n){pE(xs(e,t),n)}function YE(e,t,n){if(e.submittedText!==t)return!1;const r=e.submittedAttachments??[];return r.length!==n.length?!1:r.every((s,o)=>s===n[o])}function QE(e,t){return!!t&&e===t}const XE=3,JE=5e3,qE=2e3;async function eA(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=XE||!(n instanceof Oe)||n.code!==No)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??qE),JE);await new Promise(s=>setTimeout(s,r))}}async function tA(e){await eA(async()=>{await Ze(e)})}async function HO(e,t,n,r,s){const o=yt.getState();if(QE(o.validatingSessionId,n))throw new In(BE(),Go);const i=o.drafts[e];if(i?.pending)return null;const c=Sa(t.text),l=i?.submittedText!==void 0&&YE(i,c,t.attachments),d=i??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?i?.submittedImages??t.images:t.images,f=l?i?.submittedFiles??t.files:t.files,h=l?i?.submittedMode??t.mode:t.mode,g=l&&i?i.submittedInputMode:t.inputMode,y=l&&i?i.submittedInputPath:t.inputPath,b=i?.submittedText===void 0||l?i?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),_=Date.now();o.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:b,submittedRendered:l?i?.submittedRendered:void 0,migratedHeld:i?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:h,submittedInputMode:g,submittedInputPath:y,error:void 0,errorCode:void 0,submittedAt:_});const p=Rc(e.startsWith("draft:")?e:null,n??d.sessionId)??null;p&&_a(p,{id:b,submittedAt:_,text:c,images:u.map((L,P)=>({id:`${b}:${P}`,data:L.data_b64,attachment:null,mimeType:L.mime_type})),documents:ka(f??[],b),onPainted:r});let R=l,k=n??d.sessionId,O=null;try{if(!k){if(O="sessions.create",k=await o.createSession(t.cwd,d.target,d.createRequestId,Ec(d.model??null,o.draftFastCarries),d.warmId,d.peer)??void 0,!k)throw new In(yt.getState().error??v("ui.common.errors.chat_start_simple"));o.updateDraft(e,{sessionId:k}),p&&cE(p,k),o.fetchSessions()}const L=l&&i?.submittedRendered!==void 0?i.submittedRendered:s?await s(k)??c:c;return R=!0,o.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:L}),k&&aE(k,b,L),O="sessions.message",await tA({op:"sessions.message",sessionId:k,requestId:b,text:L,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:h,inputMode:g,inputPath:y}),o.finishDraft(e,k),yt.setState({error:null}),k}catch(L){yt.setState({error:null});const P=l&&i?.admissionAttempted===!0,T=gh(L,P),m=O==="sessions.message"&&HE(L,c),w=m?Io:Ac(L),S=zE(L,w,P);let x=!1;const N=k??p??void 0;if(N&&T==="unknown"&&(x=R&&sh(N,b)==="owner"),o.updateDraft(e,{pending:!1,admissionAttempted:T==="unknown"&&R,errorCode:w,error:S.message,errorRetry:S.retry}),x)return k?(o.finishDraft(e,k),k):null;const E=xs(e,k??d.sessionId),z=p&&p!==E?[p,E]:[E];throw it.getState().settleInFlight(z),p&&p!==E&&it.getState().returnInFlight(p,E),N&&va(N,b),e!==N&&va(e,b),m?new Oe(422,dh(),L,Io):L}}const bh=50,Xd="activity",nA=25,rA=500;function sA(e){return e?bh:rA}function Jd(e,t){return`${e}:${t}`}function oA(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function iA(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function aA(e,t){const n=new Set;for(const[r,s]of Object.entries(t))s.locality==="remote"&&n.add(r);for(const r of e)r.locality==="remote"&&n.add(r.session_id);return n}function cA(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 lA(e){const t=new Set(e.tailIds),n=new Set(e.keepIds??[]),r=new Set(e.page.map(c=>c.session_id)),s=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)),o=e.merge(e.sessions,e.page),i=new Set(o.map(c=>c.session_id));for(const c of s)i.has(c.session_id)||(i.add(c.session_id),o.push(c));return{rows:o,tailIds:e.tailIds.filter(c=>i.has(c))}}function dA(e){const t=[...e.previousIds],n=new Set(t);for(const o of e.page)n.has(o.session_id)||(n.add(o.session_id),t.push(o.session_id));const r=[...e.sessions],s=new Map(r.map((o,i)=>[o.session_id,i]));for(const o of e.page){const i=s.get(o.session_id);if(i===void 0){s.set(o.session_id,r.length),r.push(o);continue}r[i]=e.merge(r[i],o)}return{rows:r,ids:t}}function Dn(e,t){return{...e,...t,...pA(e,t),...hA(t,e),attention:fr(e?.attention,t.attention,t.session_id)}}const WO=oh,uA=e=>e.filter(ih),qd=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const s=e[r],o=fr(s.attention,n,t);if(o===s.attention)return e;const i=e.slice();return i[r]={...s,attention:o},i},fA=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function pA(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 hA(e,t){const n=typeof t?.status_epoch=="string"&&t.status_epoch===e.status_epoch,r=t?.status_revision,s=e.status_revision;return t?.status!==void 0&&n&&typeof r=="number"&&typeof s=="number"&&r>s?{status:t?.status,status_revision:t?.status_revision,status_epoch:t?.status_epoch}:{}}function mA(e,t){const n={};let r=!1;for(const[s,o]of Object.entries(e)){if(o.at<t){r=!0;continue}n[s]=o}return r?n:e}function Mi(e,t){const n={...e.archiveFacts};delete n[t];const r={...e.placementFacts};delete r[t];const s=e.answerSeq+1;return{sessions:e.sessions.filter(o=>o.session_id!==t),archiveFacts:n,placementFacts:r,answerSeq:s,forgotten:{...e.forgotten,[t]:{at:s,title:e.sessions.find(o=>o.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function vh(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 yh(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 wh(e,t,n){const r=it.getState();if(t&&t!==e){r.adoptReturnedText(t);const s=it.getState().inputByConversation[t];s&&s.inFlight===void 0&&((s.currentInput??"")!==""||(s.attachments?.length??0)>0)&&r.returnInFlight(t,e)}n&&r.returnPayload(e,{text:n.text,attachments:n.attachments,replies:[]})}function gA(e,t,n){const r=it.getState(),s=n??(e?r.getCurrentInput(e):"");s&&r.setComposerText(t,s),e&&e!==t&&r.setComposerText(e,"")}function _A(e,t){let n=null;const r=[];for(const[s,o]of Object.entries(e))!o.sessionId||t[o.sessionId]===void 0||(n??={...e},n[s]=vh(o),r.push({key:s,sessionId:o.sessionId,payload:yh(o)}));return{drafts:n??e,restored:r}}function kh(e){return e.map(({id:t,name:n,mtime:r,...s})=>({...s,session_id:t,title:n,updated_at:r}))}function eu(e,t){return kh(e).filter(n=>t[n.session_id]===void 0)}function ji(e){return typeof e=="string"&&e.length>0?e:null}function bA(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),s=n(t.active),o=n(t.unbound);if(r===null||s===null||o===null||!Array.isArray(t.scopes))return null;const i=[];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||i.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:r,active:s,unbound:o,scopes:i}}function vA(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Dn(n.get(r.session_id),r)])).values()]}let $i=0,sr=null;function yA(e,t,n){const r=sr;if(r)return r.invalidated=!0,r.limit=e,r.withCounts=t,r.promise;const s={limit:e,withCounts:t,invalidated:!1,promise:null};return sr=s,s.promise=(async()=>{try{for(;;){s.invalidated=!1;let o;try{o=await n(s.limit,s.withCounts)}catch(i){if(s.invalidated)continue;throw i}if(!s.invalidated)return sr===s&&(sr=null),o}}finally{sr===s&&(sr=null)}})(),s.promise}function Sh(){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 wA(){const e=Sh();return e.kind==="session"?e.sessionId:null}function kA(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 SA(e,t){const n={...t,...e},{drafts:r,restored:s}=_A(n.drafts,n.forgotten),o=r===n.drafts?n:{...n,drafts:r};for(const l of s)wh(l.key,l.sessionId,l.payload);const i=Sh();if(i.kind==="session")return{...o,activeSessionId:i.sessionId};if(i.kind==="catalogue")return{...o,activeSessionId:null};const c=kA(o);return c?{...o,...c}:o}const yt=Rs()(Uo((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:wA(),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 s=Object.entries(r.drafts);return s.some(([,o])=>!o.sessionId)?{cwd:n,drafts:Object.fromEntries(s.map(([o,i])=>i.sessionId?[o,i]:[o,{...i,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=sA(t().cataloguePageable),r=!1)=>{const s=++$i,o=t().answerSeq+1;e({answerSeq:o}),e({loading:!0,error:null});try{const i=await yA(n,r,(l,d)=>Ze({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:Xd}:{}}));if(s!==$i)return;const c=kh(i.sessions);e(l=>{const d={...l.pinFacts};for(const[m,w]of Object.entries(d))w.at>=o||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<o&&u.has(m)&&(delete h[m],f=!0);const g=f?h:l.forgotten,y=c.filter(m=>g[m.session_id]===void 0);let b=null;for(const m of y){const w=l.placementFacts[m.session_id];if(w===void 0||w.at>=o)continue;const S=m.locality==="remote"?"remote":m.locality==="local"?"local":null;S!==null&&(b??={...l.placementFacts},b[m.session_id]={locality:S,owner_device:typeof m.owner_device=="string"?m.owner_device:"",at:l.answerSeq+1})}const _=ji(i.next_cursor),p=_===null&&i.truncated!==!0,R=y.map(m=>m.session_id),k=l.sessions.filter(m=>g[m.session_id]===void 0&&(l.pinFacts[m.session_id]?.at??-1)>=o),O=lA({sessions:l.sessions,scopeIds:oA(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...iA(l.placementFacts)],tailIds:p?[]:l.head.tailIds,page:y,merge:vA});let L=O.rows;for(const m of k){const w=l.pinFacts[m.session_id],S=L.findIndex(x=>x.session_id===m.session_id);S===-1?L=[...L,{...m,pinned:w.pinned}]:L[S]={...L[S],pinned:w.pinned}}const P=mA(l.archiveFacts,o),T=bA(i.counts);return{sessions:L,pinFacts:d,archiveFacts:P,...b===null?{}:{placementFacts:b,answerSeq:l.answerSeq+1},forgotten:g,loading:!1,truncated:i.truncated===!0,head:{pageIds:R,tailIds:O.tailIds,nextCursor:_,tailCursor:p?null:l.head.tailStarted?l.head.tailCursor:_,tailStarted:l.head.tailStarted,complete:p,loading:!1,error:null,at:o},...T===null?{}:{counts:T},statusUnavailable:Array.isArray(i.degraded)?i.degraded.filter(m=>typeof m=="string"):[]}})}catch(i){s===$i&&e({loading:!1,error:Ys(i,v("ui.common.errors.chats_refresh"))})}},fetchCatalogueTail:async()=>{const n=t().head,r=n.tailCursor;if(!(r===null||n.loading)){e(s=>({head:{...s.head,loading:!0,error:null,tailStarted:!0,tailCursor:r}}));try{const s=await Ze({op:"sessions.list",limit:bh,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:Xd}:{}}),o=eu(s.sessions,t().forgotten);e(i=>{const c=new Map(i.sessions.map((f,h)=>[f.session_id,h])),l=[...i.sessions],d=[];for(const f of o){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]=Dn(l[h],f)}const u=ji(s.next_cursor);return{sessions:l,head:{...i.head,tailIds:[...i.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(s){e(o=>({head:{...o.head,loading:!1,error:Ys(s,v("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,s=null,o=nA)=>{const i=Jd(n,r);if(t().scopes[i]?.loading)return;const c=t().answerSeq+1;e({answerSeq:c}),e(l=>({scopes:{...l.scopes,[i]:{ids:l.scopes[i]?.ids??[],nextCursor:l.scopes[i]?.nextCursor??null,loading:!0,error:null,at:c}}}));try{const l=await Ze({op:"sessions.list",limit:o,include_archived:!1,scope_kind:n,scope_name:r,...s===null?{}:{cursor:s}}),d=eu(l.sessions,t().forgotten);e(u=>{const f=u.scopes[i];if(f===void 0||f.at!==c)return{};const h=s!==null&&l.cursor_missing!==!0,g=dA({sessions:u.sessions,previousIds:h?f.ids:[],page:d,merge:Dn}),y=ji(l.next_cursor);return{sessions:g.rows,scopes:{...u.scopes,[i]:{ids:g.ids,nextCursor:y,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[i];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[i]:{...u,loading:!1,error:Ys(l,v("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const s=Jd(n,r);e(o=>{const i=o.scopes[s];if(i===void 0)return{};const c={...o.scopes};delete c[s];const l=o.activeSessionId,d=new Set(i.ids),u=new Set(o.head.pageIds),f=o.sessions.filter(h=>!d.has(h.session_id)||u.has(h.session_id)||l!==null&&h.session_id===l);return{scopes:c,sessions:f}})},setCataloguePageable:n=>{t().cataloguePageable!==n&&e({cataloguePageable:n})},setCatalogueActivityHead:n=>{t().catalogueActivityHead!==n&&e({catalogueActivityHead:n})},setDraftFastCarries:n=>{t().draftFastCarries!==n&&e({draftFastCarries:n})},setDraftWarmable:n=>{if(t().draftWarmable===n||(e({draftWarmable:n}),!n))return;const r=t().activeDraftKey,s=r?t().drafts[r]:void 0;if(!r||!s||s.sessionId||s.warmId)return;it.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 s={...n.drafts};for(const[i,c]of Object.entries(r.drafts))i in s||(s[i]=c);const o=it.getState();for(const[i,c]of Object.entries(r.composer)){const l=o.inputByConversation[i];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||o.restoreRow(i,c)}return{drafts:s,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,r,s)=>{const o=t().answerSeq+1,i=t().archiveFacts[n]??null,c=s??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:o,archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:o,answered:!1}}}));try{return await Ze({op:"sessions.archive",sessionId:n,archived:r}),e(l=>{const u=l.archiveFacts[n]?.at!==o;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:o,answered:!0}},archiveUndo:u?l.archiveUndo:r?{sessionId:n,title:c??void 0,archived:!0,at:o}:null,archiveFailure:l.archiveFailure?.sessionId===n?null:l.archiveFailure}}),!0}catch(l){return e(d=>{const u=d.archiveFacts[n]?.at!==o,f={...d.archiveFacts};return u||(i?.answered===!0?f[n]=i:(delete f[n],i!==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 Oe&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await Ze({op:"sessions.delete",sessionId:n,confirmed:!0}),e(r=>Mi(r,n)),t().retireDraftsForSession(n),{ok:!0}}catch(r){const s=r instanceof Oe?r.status:null,o=r instanceof Oe?r.code??null:null;return s===404?(e(i=>Mi(i,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:o==="session_delete_refused",detail:r instanceof Oe&&r.message?r.message:v("ui.common.errors.conversation_delete")}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,s=crypto.randomUUID(),o,i,c)=>{try{const l=await Ze({op:"sessions.create",requestId:s,cwd:n,...r?{target:r}:{},...o?{model:o}:{},...i?{draftId:i}:{},...c?{peer:c}:{}});return t().upsertSession({session_id:l.session_id,cwd:n,binding:l.binding}),c&&t().settlePlacement(l.session_id,{locality:"remote",owner_device:c}),l.session_id}catch(l){throw e({error:Ys(l,v("ui.common.errors.chat_start"))}),l}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,r=Date.now())=>e(s=>({stoppedTurns:{...s.stoppedTurns,[n]:r}})),clearTurnStopped:n=>e(r=>{if(!(n in r.stoppedTurns))return r;const{[n]:s,...o}=r.stoppedTurns;return{stoppedTurns:o}}),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,...Mi(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:fA(r.readAckRearm,n)}))},publishReadAckNotice:(n,r,s)=>{e(o=>{const i=o.readAckNotice;return i?.sessionId===n&&i.kind===r?o:{readAckNotice:{sessionId:n,kind:r,revision:(i?.revision??0)+1,reason:s}}})},clearReadAckNotice:n=>{e(r=>r.readAckNotice?.sessionId===n?{readAckNotice:null}:r)},applyAttention:(n,r)=>{e(s=>{const o=qd(s.sessions,n,r);return o===s.sessions?s:{...s,sessions:o}})},applyAttentionMany:n=>{e(r=>{let s=r.sessions;for(const o of n){const i=o?.conversation_id;typeof i!="string"||!i.startsWith("session/")||(s=qd(s,i.slice(8),o))}return s===r.sessions?r:{...r,sessions:s}})},markAllRead:async()=>{const n=uA(t().sessions).map(i=>({sessionId:i.session_id,completionToken:i.attention?.completion_token}));if(n.length===0)return{attempted:0,cleared:0,superseded:0,unknown:0,deferred:0};const r=await Ze({op:"attention.seen",items:n});t().applyAttentionMany(r.read);const s=aA(t().sessions,t().placementFacts),o=r.unknown.filter(i=>s.has(i)).length;return{attempted:n.length,cleared:r.read.length,superseded:r.superseded.length,unknown:r.unknown.length,deferred:o}},applySessionStatus:(n,r,s,o)=>{e(i=>{const c=i.sessions.findIndex(h=>h.session_id===n);let l=!1;const d=i.sessions.map(h=>{if(h.status_epoch===void 0&&h.status_revision===void 0||h.status_epoch===o)return h;l=!0;const{status_revision:g,status_epoch:y,...b}=h;return b});if(c<0)return l?{...i,sessions:d}:i;const u=d[c],f=u.status?.code===r.code&&u.status?.label===r.label&&u.status_revision===s&&u.status_epoch===o;return f&&!l?i:(f||(d[c]={...u,status:r,status_revision:s,status_epoch:o}),{...i,sessions:d})})},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 o=(!r&&n?`draft:${n.kind}:${n.name}`:null)??`draft:${crypto.randomUUID()}`,i=t().drafts[o],c=_h(t().activeDraftKey,t().activeDraftKey?t().drafts[t().activeDraftKey]?.sessionId:void 0,t().activeSessionId);if(i?.sessionId&&!i.pending&&i.sessionId!==c){const d=t().drafts[`send:${i.sessionId}`]?`draft:${crypto.randomUUID()}`:`send:${i.sessionId}`;e(u=>{const f={...u.drafts};return delete f[o],f[d]={...i,key:d},{drafts:f}})}const l=t().drafts[o];return e(d=>({activeDraftKey:o,validatingSessionId:null,error:null,drafts:{...d.drafts,[o]:l??{key:o,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),o},restageDraft:(n,r)=>{const s=t().activeDraftKey,o=t().stageDraft(n);return gA(s,o,r),o},startNewChat:n=>{const r=t().stageDraft();return e({activeSessionId:null,validatingSessionId:null}),n&&(it.getState().adoptReturnedText(n),it.getState().inputByConversation[n]?.pendingText===void 0&&it.getState().returnInFlight(n,r)),r},updateDraft:(n,r)=>e(s=>{const o=s.drafts[n],i=r.key!==void 0&&r.createRequestId!==void 0&&r.admissionRequestId!==void 0;return!o&&!i?{}:{drafts:{...s.drafts,[n]:{...s.drafts[n],...r}}}}),setDraftPeer:(n,r)=>e(s=>{const o=s.drafts[n];if(!o)return{};const i=r??void 0;return(o.peer??void 0)===i?{}:{drafts:{...s.drafts,[n]:{...o,peer:i,...o.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}}),setDraftModel:(n,r)=>e(s=>{const o=s.drafts[n];return o?{drafts:{...s.drafts,[n]:{...o,model:r,...o.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}:{}}),ensureDraftWarm:n=>{const r=t();if(!r.draftWarmable)return;const s=r.drafts[n];if(!s||s.sessionId||s.warmId||!r.cwd||s.peer)return;const o=s.draftRequestId??crypto.randomUUID();s.draftRequestId||t().updateDraft(n,{draftRequestId:o});const i=Ec(s.model??null,r.draftFastCarries);Ze({op:"sessions.draft",requestId:o,cwd:r.cwd,...s.target?{target:s.target}:{},...i?{model:i}:{}}).then(c=>{const l=t().drafts[n];l&&!l.warmId&&!l.sessionId&&l.draftRequestId===o&&t().updateDraft(n,{warmId:c.draft_id})}).catch(()=>{})},finishDraft:(n,r)=>e(s=>{ZE(n,r);const o={...s.drafts};return delete o[n],{drafts:o,...s.activeDraftKey===n?{activeDraftKey:null,activeSessionId:r}:{}}}),retireDraftSession:n=>{const r=t().drafts[n];if(!r?.sessionId||r.pending)return;const s=r.sessionId,o=yh(r);e(i=>{const c=i.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...i.drafts,[n]:vh(c)}}}),wh(n,s,o)},retireDraftsForSession:n=>{for(const[r,s]of Object.entries(t().drafts))r.startsWith("draft:")&&s.sessionId===n&&t().retireDraftSession(r)},retireDraftWarm:n=>{const r=Object.entries(t().drafts).filter(([s,o])=>s.startsWith("draft:")&&o.warmId===n&&!o.sessionId);r.length!==0&&e(s=>{const o={...s.drafts};for(const[i]of r){const c=o[i];!c||c.warmId!==n||c.sessionId||(o[i]={...c,warmId:void 0,draftRequestId:crypto.randomUUID()})}return{drafts:o}})},discardDraft:n=>e(r=>{const s={...r.drafts},o=s[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),i=s[n],c=it.getState().inputByConversation[n];Vs(n),o&&o!==n&&Vs(o),delete s[n],it.getState().clearAll(n);const l=i?{at:r.answerSeq+1,keys:[n],drafts:{[n]:i},composer:c?{[n]:c}:{}}:null;return{drafts:s,...l?{answerSeq:l.at,draftsUndo:l}:{},...r.activeDraftKey===n?{activeDraftKey:null}:{}}}),discardDrafts:n=>e(r=>{const s={...r.drafts};let o=!1;const i=[],c={},l={};for(const u of n){if(!(u in s))continue;const f=s[u];if(!f)continue;const h=f.sessionId??(u.startsWith("send:")?u.slice(5):void 0);Vs(u),h&&h!==u&&Vs(h),i.push(u),c[u]=f;const g=it.getState().inputByConversation[u];g&&(l[u]=g),delete s[u],it.getState().clearAll(u),r.activeDraftKey===u&&(o=!0)}if(i.length===0)return{};const d=r.answerSeq+1;return{drafts:s,answerSeq:d,draftsUndo:{at:d,keys:i,drafts:c,composer:l},...o?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,r,s)=>e(o=>{const i=r.map(S=>S.id),c=Object.entries(o.drafts).filter(([,S])=>Ea(S,n)&&S.undelivered!==void 0&&i.includes(S.undelivered.recordId));let l=o.drafts;if(c.length>0){l={...l};for(const[S,x]of c){const N=x.undelivered?.recordId,{undelivered:E,...z}=x;l[S]=z,N!==void 0&&Qd(S,x.sessionId,N)}}const d=Object.entries(l).find(([,S])=>Ea(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,g=i.includes(h);if(!g&&!s)return c.length>0?{drafts:l}:{};if(!g&&!KE(r,f,o.placementFacts[n],o.sessions.find(S=>S.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:y,submittedText:b,submittedAttachments:_,submittedImages:p,submittedMode:R,submittedInputMode:k,submittedInputPath:O,heldClaimCode:L,error:P,errorCode:T,errorRetry:m,...w}=f;return g||va(n,h),{drafts:{...l,[u]:{...w,...g?{}:{undelivered:{recordId:h,text:b??"",attachments:_??[]}},admissionRequestId:crypto.randomUUID()}}}}),retractUndelivered:(n,r)=>{const s=t().drafts[n];!s||s.undelivered?.recordId!==r||(e(o=>{const{undelivered:i,...c}=o.drafts[n];return{drafts:{...o.drafts,[n]:c}}}),Qd(n,s.sessionId,r))},bindSession:(n,r)=>t().setActiveSession(r),beginAnswer:()=>{const n=t().answerSeq+1;return e({answerSeq:n}),n},applySearchAnswer:(n,r)=>e(s=>{let o=null,i=null,c=null;for(const l of r){const d=s.archiveFacts[l.id];if(d!==void 0&&d.at<n&&(c=c??{...s.archiveFacts},delete c[l.id]),!(d!==void 0&&d.at>=n)&&typeof l.archived=="boolean"&&s.sessions.some(f=>f.session_id===l.id&&f.archived!==l.archived)){i=i??s.sessions.map(f=>({...f}));for(const f of i)f.session_id===l.id&&(f.archived=l.archived===!0)}if(typeof l.pinned!="boolean")continue;const u=s.pinFacts[l.id];if(!(u!==void 0&&u.at>=n)&&(u!==void 0&&(o=o??{...s.pinFacts},delete o[l.id]),s.sessions.some(f=>f.session_id===l.id&&f.pinned!==l.pinned))){i=i??s.sessions.map(f=>({...f}));for(const f of i)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return o===null&&i===null&&c===null?{}:{...o===null?{}:{pinFacts:o},...i===null?{}:{sessions:i},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,r,s)=>{const o=t().sessions.find(h=>h.session_id===n),i=t().pinFacts[n]??null,c=o===void 0?i?.pinned??!1:o.pinned===!0,l=o===void 0&&s!==void 0?{session_id:n,title:s.title||"",updated_at:s.updated_at,pinned:r}:null,d=t().beginAnswer(),u=o?.title??s?.title,f=o?.updated_at??s?.updated_at;e(h=>({sessions:l===null?h.sessions.map(g=>g.session_id===n?{...g,pinned:r}:g):[...h.sessions,l],pinFacts:{...h.pinFacts,[n]:{pinned:r,at:d,title:u,updated_at:f}},pinFailure:null}));try{const h=await Ze({op:"sessions.pin",sessionId:n,pinned:r});let g=!1;return e(y=>{const b=y.pinFacts[n];return b===void 0||b.at!==d?{}:(g=!0,{sessions:y.sessions.map(_=>_.session_id===n?{..._,pinned:h.pinned===!0}:_),pinFacts:{...y.pinFacts,[n]:{...b,pinned:h.pinned===!0}}})}),g}catch(h){return e(g=>{const y=g.pinFacts[n];if(y!==void 0&&y.at!==d)return{};const b={...g.pinFacts};return i===null&&o===void 0?delete b[n]:b[n]={pinned:c,at:Math.max(i?.at??0,d),title:i?.title??u,updated_at:i?.updated_at??f},{sessions:g.sessions.map(_=>_.session_id===n?{..._,pinned:c}:_),pinFacts:b,pinFailure:{sessionId:n,pinned:r,title:o?.title||"",detail:qa(h,"")}}}),!1}},upsertSession:n=>e(r=>({sessions:r.sessions.some(o=>o.session_id===n.session_id)?r.sessions.map(o=>o.session_id===n.session_id?Dn(o,n):o):[...r.sessions,n]})),settlePlacement:(n,r)=>{const s=t().beginAnswer();e(o=>({sessions:o.sessions.map(i=>i.session_id===n?Dn(i,{session_id:n,locality:r.locality,owner_device:r.owner_device}):i),placementFacts:{...o.placementFacts,[n]:{locality:r.locality,owner_device:r.owner_device,at:s}}}))},settlePeerCatalogue:(n,r,s={},o=void 0)=>{e(i=>{const c={...i.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"&&i.peerDeviceSnapshotAt>r&&typeof m.owner_device=="string"&&!i.peerDeviceFacts[m.owner_device])return!1;const w=i.placementFacts[m.session_id];return!w||w.at<r}),d={...i.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=i.placementFacts[m.session_id];if(S!==void 0){if(S.at>=r)continue}else if(w!=="remote")continue;h=h===0?i.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 g=o===void 0?null:FE(i.peerDeviceFacts,s,i.peerDeviceSnapshotAt,o),y=g?.facts??LE(i.peerDeviceFacts,Object.fromEntries(Object.entries(s).filter(([,m])=>m.at>i.peerDeviceSnapshotAt))),b=l.filter(m=>m.locality==="remote");let _=i.sessions,p=!1;const R=[],k=new Map;for(let m=0;m<_.length;m+=1)k.set(_[m].session_id,m);for(const m of b){const w=k.get(m.session_id);if(w===void 0){R.push(m);continue}_[w]!==m&&(p||(_=_.slice(),p=!0),_[w]=Dn(_[w],m))}R.length>0&&(_=[..._,...R]);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||_[w]===m||(p||(_=_.slice(),p=!0),_[w]=Dn(_[w],m))}const O=new Set(l.map(m=>m.session_id)),L=new Set;for(const m of l)m.locality==="remote"&&typeof m.owner_device=="string"&&m.owner_device!==""&&m.reachable!==!1&&L.add(m.owner_device);const P=new Set;for(const m of _){if(m.locality!=="remote"||typeof m.owner_device!="string"||!g?.removed.includes(m.owner_device))continue;const w=i.placementFacts[m.session_id];w&&w.at>=(o??0)||(P.add(m.session_id),delete d[m.session_id])}for(const[m,w]of Object.entries(i.placementFacts))w.locality==="remote"&&(O.has(m)||w.at>=r||y[w.owner_device]?.reachable!==!1&&(w.owner_device===""||!L.has(w.owner_device)||(P.add(m),delete d[m])));P.size>0&&(_=_.filter(m=>!P.has(m.session_id)));const T=_.map(m=>UE(m,y));return T.some((m,w)=>m!==_[w])&&(_=T,p=!0),!f&&R.length===0&&!p&&P.size===0&&Object.keys(s).length===0&&o===void 0?{}:{sessions:_,placementFacts:d,peerDeviceFacts:y,peerDeviceSnapshotAt:g?.watermark??i.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:i.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:SA,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 GO(e,t){return t?e.filter(n=>n.archived!==!0):e}function zO(e,t){let n=!1;const r=e.map(s=>{const o=t[s.session_id];return o===void 0||!o.answered||s.archived===o.archived?s:(n=!0,{...s,archived:o.archived})});return n?r:e}function KO(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function VO(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const ZO="This backend cannot archive conversations. Update the backend and try again.",YO="This conversation is already archived. Use /unarchive to restore it.",QO="This conversation is not archived, so there is nothing to restore.",XO="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 JO(e,t,n){return n&&e&&t.trim().length>0}function qO(e,t){return t===e}const ie=e=>{const[t,n,r]=[1,3,5].map(f=>{const h=Number.parseInt(e.slice(f,f+2),16)/255;return h<=.04045?h/12.92:((h+.055)/1.055)**2.4}),s=(t*.4124564+n*.3575761+r*.1804375)/.95047,o=t*.2126729+n*.7151522+r*.072175,i=(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(s),c(o),c(i)];return[116*d-16,500*(l-d),200*(d-u)]},pe=(e,t)=>{const[n,r,s]=ie(e),[o,i,c]=ie(t),l=Math.PI/180,d=180/Math.PI,u=(Math.hypot(r,s)+Math.hypot(i,c))/2,f=.5*(1-Math.sqrt(u**7/(u**7+25**7))),[h,g]=[(1+f)*r,(1+f)*i],[y,b]=[Math.hypot(h,s),Math.hypot(g,c)],_=(F,X)=>{if(F===0&&X===0)return 0;const $e=Math.atan2(F,X)*d;return $e<0?$e+360:$e},[p,R]=[_(s,h),_(c,g)],k=o-n,O=b-y;let L=0;y*b!==0&&(L=R-p,L>180?L-=360:L<-180&&(L+=360));const P=2*Math.sqrt(y*b)*Math.sin(L*l/2),T=(n+o)/2,m=(y+b)/2;let w;y*b===0?w=p+R:(w=Math.abs(p-R)>180?(p+R+360)/2:(p+R)/2,w>=360&&(w-=360));const S=1-.17*Math.cos((w-30)*l)+.24*Math.cos(2*w*l)+.32*Math.cos((3*w+6)*l)-.2*Math.cos((4*w-63)*l),x=1+.015*(T-50)**2/Math.sqrt(20+(T-50)**2),N=1+.045*m,E=1+.015*m*S,z=-Math.sin(2*30*Math.exp(-(((w-275)/25)**2))*l)*2*Math.sqrt(m**7/(m**7+25**7));return Math.sqrt((k/x)**2+(O/N)**2+(P/E)**2+z*(O/N)*(P/E))},To=([e,t,n])=>{const r=(e+16)/116,s=r+t/500,o=r-n/200,i=g=>g>6/29?g**3:3*(6/29)**2*(g-4/29),c=i(s)*.95047,l=i(r),d=i(o)*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(g=>g<=.0031308?12.92*g:1.055*g**(1/2.4)-.055);if(f.some(g=>g<-.0015||g>1.0015))return null;const h=g=>Math.round(Math.min(1,Math.max(0,g))*255).toString(16).padStart(2,"0").toUpperCase();return`#${f.map(h).join("")}`},D=e=>Math.round(e*100)/100,tu=e=>{const t=e.replace("#","").trim(),n=t.length===3?t.split("").map(i=>i+i).join(""):t,[r,s,o]=[0,2,4].map(i=>{const c=Number.parseInt(n.slice(i,i+2),16)/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4});return .2126*r+.7152*s+.0722*o},oe=(e,t)=>{const[n,r]=[tu(e),tu(t)].sort((s,o)=>o-s);return(n+.05)/(r+.05)},EA=/^#[0-9a-fA-F]{3,8}$/,W=e=>typeof e=="string"&&EA.test(e),nu=(e,t,n)=>{const r=f=>{const h=f.replace("#","").trim(),g=h.length===3?h.split("").map(y=>y+y).join(""):h;return[0,2,4].map(y=>Number.parseInt(g.slice(y,y+2),16))},[s,o,i]=r(e),[c,l,d]=r(t),u=(f,h)=>Math.round(f*n+h*(1-n));return`#${[u(s,c),u(o,l),u(i,d)].map(f=>f.toString(16).padStart(2,"0")).join("")}`},Aa=new WeakMap,AA=(e,t)=>{t?Aa.set(e,t):Aa.delete(e)},eP=e=>Aa.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 vs(){return vs=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},vs.apply(this,arguments)}var yn;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(yn||(yn={}));const ru="popstate";function tP(e){e===void 0&&(e={});function t(s,o){let{pathname:i="/",search:c="",hash:l=""}=Xn(s.location.hash.substr(1));return!i.startsWith("/")&&!i.startsWith(".")&&(i="/"+i),Ra("",{pathname:i,search:c,hash:l},o.state&&o.state.usr||null,o.state&&o.state.key||"default")}function n(s,o){let i=s.document.querySelector("base"),c="";if(i&&i.getAttribute("href")){let l=s.location.href,d=l.indexOf("#");c=d===-1?l:l.slice(0,d)}return c+"#"+(typeof o=="string"?o:Eh(o))}function r(s,o){Ic(s.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(o)+")")}return IA(t,n,r,e)}function He(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Ic(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function RA(){return Math.random().toString(36).substr(2,8)}function su(e,t){return{usr:e.state,key:e.key,idx:t}}function Ra(e,t,n,r){return n===void 0&&(n=null),vs({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?Xn(t):t,{state:n,key:t&&t.key||r||RA()})}function Eh(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 Xn(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 IA(e,t,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:o=!1}=r,i=s.history,c=yn.Pop,l=null,d=u();d==null&&(d=0,i.replaceState(vs({},i.state,{idx:d}),""));function u(){return(i.state||{idx:null}).idx}function f(){c=yn.Pop;let _=u(),p=_==null?null:_-d;d=_,l&&l({action:c,location:b.location,delta:p})}function h(_,p){c=yn.Push;let R=Ra(b.location,_,p);n&&n(R,_),d=u()+1;let k=su(R,d),O=b.createHref(R);try{i.pushState(k,"",O)}catch(L){if(L instanceof DOMException&&L.name==="DataCloneError")throw L;s.location.assign(O)}o&&l&&l({action:c,location:b.location,delta:1})}function g(_,p){c=yn.Replace;let R=Ra(b.location,_,p);n&&n(R,_),d=u();let k=su(R,d),O=b.createHref(R);i.replaceState(k,"",O),o&&l&&l({action:c,location:b.location,delta:0})}function y(_){let p=s.location.origin!=="null"?s.location.origin:s.location.href,R=typeof _=="string"?_:Eh(_);return R=R.replace(/ $/,"%20"),He(p,"No window.location.(origin|href) available to create URL for href: "+R),new URL(R,p)}let b={get action(){return c},get location(){return e(s,i)},listen(_){if(l)throw new Error("A history only accepts one active listener");return s.addEventListener(ru,f),l=_,()=>{s.removeEventListener(ru,f),l=null}},createHref(_){return t(s,_)},createURL:y,encodeLocation(_){let p=y(_);return{pathname:p.pathname,search:p.search,hash:p.hash}},push:h,replace:g,go(_){return i.go(_)}};return b}var ou;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(ou||(ou={}));function TA(e,t,n){return n===void 0&&(n="/"),xA(e,t,n)}function xA(e,t,n,r){let s=typeof t=="string"?Xn(t):t,o=Ih(s.pathname||"/",n);if(o==null)return null;let i=Ah(e);CA(i);let c=null;for(let l=0;c==null&&l<i.length;++l){let d=HA(o);c=UA(i[l],d)}return c}function Ah(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let s=(o,i,c)=>{let l={relativePath:c===void 0?o.path||"":c,caseSensitive:o.caseSensitive===!0,childrenIndex:i,route:o};l.relativePath.startsWith("/")&&(He(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=kn([r,l.relativePath]),u=n.concat(l);o.children&&o.children.length>0&&(He(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),Ah(o.children,t,u,d)),!(o.path==null&&!o.index)&&t.push({path:d,score:NA(d,o.index),routesMeta:u})};return e.forEach((o,i)=>{var c;if(o.path===""||!((c=o.path)!=null&&c.includes("?")))s(o,i);else for(let l of Rh(o.path))s(o,i,l)}),t}function Rh(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return s?[o,""]:[o];let i=Rh(r.join("/")),c=[];return c.push(...i.map(l=>l===""?o:[o,l].join("/"))),s&&c.push(...i),c.map(l=>e.startsWith("/")&&l===""?"/":l)}function CA(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:LA(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const OA=/^:[\w-]+$/,PA=3,MA=2,jA=1,$A=10,DA=-2,iu=e=>e==="*";function NA(e,t){let n=e.split("/"),r=n.length;return n.some(iu)&&(r+=DA),t&&(r+=MA),n.filter(s=>!iu(s)).reduce((s,o)=>s+(OA.test(o)?PA:o===""?jA:$A),r)}function LA(e,t){return e.length===t.length&&e.slice(0,-1).every((r,s)=>r===t[s])?e[e.length-1]-t[t.length-1]:0}function UA(e,t,n){let{routesMeta:r}=e,s={},o="/",i=[];for(let c=0;c<r.length;++c){let l=r[c],d=c===r.length-1,u=o==="/"?t:t.slice(o.length)||"/",f=FA({path:l.relativePath,caseSensitive:l.caseSensitive,end:d},u),h=l.route;if(!f)return null;Object.assign(s,f.params),i.push({params:s,pathname:kn([o,f.pathname]),pathnameBase:KA(kn([o,f.pathnameBase])),route:h}),f.pathnameBase!=="/"&&(o=kn([o,f.pathnameBase]))}return i}function FA(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=BA(e.path,e.caseSensitive,e.end),s=t.match(n);if(!s)return null;let o=s[0],i=o.replace(/(.)\/+$/,"$1"),c=s.slice(1);return{params:r.reduce((d,u,f)=>{let{paramName:h,isOptional:g}=u;if(h==="*"){let b=c[f]||"";i=o.slice(0,o.length-b.length).replace(/(.)\/+$/,"$1")}const y=c[f];return g&&!y?d[h]=void 0:d[h]=(y||"").replace(/%2F/g,"/"),d},{}),pathname:o,pathnameBase:i,pattern:e}}function BA(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Ic(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=[],s="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(i,c,l)=>(r.push({paramName:c,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),s+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":e!==""&&e!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,t?void 0:"i"),r]}function HA(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Ic(!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 Ih(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 WA(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?Xn(e):e;return{pathname:n?n.startsWith("/")?n:GA(n,t):t,search:VA(r),hash:ZA(s)}}function GA(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function Di(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 zA(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Tc(e,t){let n=zA(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function xc(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=Xn(e):(s=vs({},e),He(!s.pathname||!s.pathname.includes("?"),Di("?","pathname","search",s)),He(!s.pathname||!s.pathname.includes("#"),Di("#","pathname","hash",s)),He(!s.search||!s.search.includes("#"),Di("#","search","hash",s)));let o=e===""||s.pathname==="",i=o?"/":s.pathname,c;if(i==null)c=n;else{let f=t.length-1;if(!r&&i.startsWith("..")){let h=i.split("/");for(;h[0]==="..";)h.shift(),f-=1;s.pathname=h.join("/")}c=f>=0?t[f]:"/"}let l=WA(s,c),d=i&&i!=="/"&&i.endsWith("/"),u=(o||i===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(d||u)&&(l.pathname+="/"),l}const kn=e=>e.join("/").replace(/\/\/+/g,"/"),KA=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),VA=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,ZA=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function YA(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Th=["post","put","patch","delete"];new Set(Th);const QA=["get",...Th];new Set(QA);/**
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 ys(){return ys=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},ys.apply(this,arguments)}const Cc=I.createContext(null),XA=I.createContext(null),Jn=I.createContext(null),zo=I.createContext(null),un=I.createContext({outlet:null,matches:[],isDataRoute:!1}),xh=I.createContext(null);function nP(e,t){let{relative:n}=t===void 0?{}:t;Ir()||He(!1);let{basename:r,navigator:s}=I.useContext(Jn),{hash:o,pathname:i,search:c}=eR(e,{relative:n}),l=i;return r!=="/"&&(l=i==="/"?r:kn([r,i])),s.createHref({pathname:l,search:c,hash:o})}function Ir(){return I.useContext(zo)!=null}function Ko(){return Ir()||He(!1),I.useContext(zo).location}function Ch(e){I.useContext(Jn).static||I.useLayoutEffect(e)}function JA(){let{isDataRoute:e}=I.useContext(un);return e?fR():qA()}function qA(){Ir()||He(!1);let e=I.useContext(Cc),{basename:t,future:n,navigator:r}=I.useContext(Jn),{matches:s}=I.useContext(un),{pathname:o}=Ko(),i=JSON.stringify(Tc(s,n.v7_relativeSplatPath)),c=I.useRef(!1);return Ch(()=>{c.current=!0}),I.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=xc(d,JSON.parse(i),o,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:kn([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,i,o,e])}function rP(){let{matches:e}=I.useContext(un),t=e[e.length-1];return t?t.params:{}}function eR(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=I.useContext(Jn),{matches:s}=I.useContext(un),{pathname:o}=Ko(),i=JSON.stringify(Tc(s,r.v7_relativeSplatPath));return I.useMemo(()=>xc(e,JSON.parse(i),o,n==="path"),[e,i,o,n])}function tR(e,t){return nR(e,t)}function nR(e,t,n,r){Ir()||He(!1);let{navigator:s,static:o}=I.useContext(Jn),{matches:i}=I.useContext(un),c=i[i.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=Ko(),f;if(t){var h;let p=typeof t=="string"?Xn(t):t;d==="/"||(h=p.pathname)!=null&&h.startsWith(d)||He(!1),f=p}else f=u;let g=f.pathname||"/",y=g;if(d!=="/"){let p=d.replace(/^\//,"").split("/");y="/"+g.replace(/^\//,"").split("/").slice(p.length).join("/")}let b=TA(e,{pathname:y}),_=aR(b&&b.map(p=>Object.assign({},p,{params:Object.assign({},l,p.params),pathname:kn([d,s.encodeLocation?s.encodeLocation(p.pathname).pathname:p.pathname]),pathnameBase:p.pathnameBase==="/"?d:kn([d,s.encodeLocation?s.encodeLocation(p.pathnameBase).pathname:p.pathnameBase])})),i,n,r);return t&&_?I.createElement(zo.Provider,{value:{location:ys({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:yn.Pop}},_):_}function rR(){let e=uR(),t=YA(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return I.createElement(I.Fragment,null,I.createElement("h2",null,"Unexpected Application Error!"),I.createElement("h3",{style:{fontStyle:"italic"}},t),n?I.createElement("pre",{style:s},n):null,null)}const sR=I.createElement(rR,null);class oR extends I.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?I.createElement(un.Provider,{value:this.props.routeContext},I.createElement(xh.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function iR(e){let{routeContext:t,match:n,children:r}=e,s=I.useContext(Cc);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),I.createElement(un.Provider,{value:t},r)}function aR(e,t,n,r){var s;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var o;if(!n)return null;if(n.errors)e=n.matches;else if((o=r)!=null&&o.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let i=e,c=(s=n)==null?void 0:s.errors;if(c!=null){let u=i.findIndex(f=>f.route.id&&c?.[f.route.id]!==void 0);u>=0||He(!1),i=i.slice(0,Math.min(i.length,u+1))}let l=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u<i.length;u++){let f=i[u];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(d=u),f.route.id){let{loaderData:h,errors:g}=n,y=f.route.loader&&h[f.route.id]===void 0&&(!g||g[f.route.id]===void 0);if(f.route.lazy||y){l=!0,d>=0?i=i.slice(0,d+1):i=[i[0]];break}}}return i.reduceRight((u,f,h)=>{let g,y=!1,b=null,_=null;n&&(g=c&&f.route.id?c[f.route.id]:void 0,b=f.route.errorElement||sR,l&&(d<0&&h===0?(pR("route-fallback"),y=!0,_=null):d===h&&(y=!0,_=f.route.hydrateFallbackElement||null)));let p=t.concat(i.slice(0,h+1)),R=()=>{let k;return g?k=b:y?k=_:f.route.Component?k=I.createElement(f.route.Component,null):f.route.element?k=f.route.element:k=u,I.createElement(iR,{match:f,routeContext:{outlet:u,matches:p,isDataRoute:n!=null},children:k})};return n&&(f.route.ErrorBoundary||f.route.errorElement||h===0)?I.createElement(oR,{location:n.location,revalidation:n.revalidation,component:b,error:g,children:R(),routeContext:{outlet:null,matches:p,isDataRoute:!0}}):R()},null)}var Oh=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Oh||{}),Ph=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}(Ph||{});function cR(e){let t=I.useContext(Cc);return t||He(!1),t}function lR(e){let t=I.useContext(XA);return t||He(!1),t}function dR(e){let t=I.useContext(un);return t||He(!1),t}function Mh(e){let t=dR(),n=t.matches[t.matches.length-1];return n.route.id||He(!1),n.route.id}function uR(){var e;let t=I.useContext(xh),n=lR(),r=Mh();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function fR(){let{router:e}=cR(Oh.UseNavigateStable),t=Mh(Ph.UseNavigateStable),n=I.useRef(!1);return Ch(()=>{n.current=!0}),I.useCallback(function(s,o){o===void 0&&(o={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,ys({fromRouteId:t},o)))},[e,t])}const au={};function pR(e,t,n){au[e]||(au[e]=!0)}function sP(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function oP(e){let{to:t,replace:n,state:r,relative:s}=e;Ir()||He(!1);let{future:o,static:i}=I.useContext(Jn),{matches:c}=I.useContext(un),{pathname:l}=Ko(),d=JA(),u=xc(t,Tc(c,o.v7_relativeSplatPath),l,s==="path"),f=JSON.stringify(u);return I.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:s}),[d,f,s,n,r]),null}function hR(e){He(!1)}function iP(e){let{basename:t="/",children:n=null,location:r,navigationType:s=yn.Pop,navigator:o,static:i=!1,future:c}=e;Ir()&&He(!1);let l=t.replace(/^\/*/,"/"),d=I.useMemo(()=>({basename:l,navigator:o,static:i,future:ys({v7_relativeSplatPath:!1},c)}),[l,c,o,i]);typeof r=="string"&&(r=Xn(r));let{pathname:u="/",search:f="",hash:h="",state:g=null,key:y="default"}=r,b=I.useMemo(()=>{let _=Ih(u,l);return _==null?null:{location:{pathname:_,search:f,hash:h,state:g,key:y},navigationType:s}},[l,u,f,h,g,y,s]);return b==null?null:I.createElement(Jn.Provider,{value:d},I.createElement(zo.Provider,{children:n,value:b}))}function aP(e){let{children:t,location:n}=e;return tR(Ia(t),n)}new Promise(()=>{});function Ia(e,t){t===void 0&&(t=[]);let n=[];return I.Children.forEach(e,(r,s)=>{if(!I.isValidElement(r))return;let o=[...t,s];if(r.type===I.Fragment){n.push.apply(n,Ia(r.props.children,o));return}r.type!==hR&&He(!1),!r.props.index||!r.props.children||He(!1);let i={id:r.props.id||o.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&&(i.children=Ia(r.props.children,o)),n.push(i)}),n}const Vo=260,Oc=220,Pc=320,jh=56,Mc=480,cP=8,jc=44,$c=400,$h=1200;function Dc(e){return Math.max(0,Math.min($h,e-Mc))}function Ta(e){return Dc(e)>=$c?"docked":"overlay"}const mR=48,gR=16;function lP(e,t){if(Ta(e)==="docked")return{mode:"docked",width:Math.min(t,Dc(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,$c),e-mR));return e-n>=gR?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function dP({capacity:e,min:t,max:n,drawn:r}){const s=e>=t;return s?{resizable:s,value:Math.min(Math.max(r,t),e),minWidth:t,maxWidth:Math.min(n,e)}:{resizable:s,value:r,minWidth:r,maxWidth:r}}function _R(e,t=Vo,n=jc){return Ta(e-Dh(t)-n)==="overlay"&&Ta(e-jh-n)==="docked"}function Dh(e){return Number.isNaN(e)?Vo:Math.min(Pc,Math.max(Oc,e))}function bR(e,t=jc){return Math.max(0,Math.min(Pc,e-Mc-t))}function uP(e,t,n=Vo,r=!1,s=jc){const o=!t&&r&&_R(e,n,s),i=t||o,c=bR(e,s);return{mode:i?"strip":"docked",width:i?jh:Math.min(Dh(n),c),collapsed:i,resizable:!i&&c>=Oc}}function fP(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const pP=e=>e?"⌘B":"Ctrl+B",vR="data-canvas-shortcuts",yR=`[${vR}]`,wR=e=>Nh(e,yR),kR='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',hP=e=>Nh(e,kR);function Nh(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const mP=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&wR(e.target)?"new-file":null},Lh="small",SR=["small","medium","large"],Uh="before:absolute before:-inset-0.5 before:content-['']",ER={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:Uh},medium:{px:28,className:"size-7",glyphClassName:"size-3.5",hitClassName:""},large:{px:36,className:"size-9",glyphClassName:"size-4",hitClassName:""}},AR={small:{px:4,className:"mb-1"},medium:{px:6,className:"mb-1.5"},large:{px:8,className:"mb-2"}},gP={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:Uh,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 _P(e){for(const t of SR)if(e===t)return t;return Lh}function bP(e){return ER[e].px+AR[e].px}const RR=["active","created"],vP={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"},IR=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function Zo(e){return IR.has(e.status?.code??"")}const TR=new Set(["approval","answer"]);function xR(e){return TR.has(e.status?.code??"")}const CR=24*60*60*1e3,OR=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function Nc(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 PR="last_user_at";function MR(e){const t=e[PR],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 jR(e,t,n){if(Zo(e))return"running";const r=Nc(e,n);if(r===null)return"older";const s=OR(t);return r>=s?"today":r>=s-6*CR?"week":"older"}function yP(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const s of e)r[jR(s,t,n)].push(s);return r}function Fh(e,t,n){const r=Nc(e,n);if(r===null)return null;const s=Math.floor(Math.max(0,t-r)/6e4);if(s<1)return{unit:"now",count:0};if(s<60)return{unit:"minute",count:s};const o=Math.floor(s/60);if(o<24)return{unit:"hour",count:o};const i=Math.floor(o/24);return i<7?{unit:"day",count:i}:i<365?{unit:"week",count:Math.floor(i/7)}:{unit:"year",count:Math.floor(i/365)}}function wP(e,t,n){const r=Fh(e,t,n);return r?v("ui.chat.sidebar_view.relative_short",r):""}function kP(e,t,n){const r=Fh(e,t,n);return r?n==="created"?v("ui.chat.sidebar_view.relative_created",r):v("ui.chat.sidebar_view.relative_active",r):""}const xa=["pinned","running","today","week","older","agents","teams"],SP={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 EP(e){return e==="agents"||e==="teams"}const ws=8;function $R(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function AP(e,t){return{...e,[t]:(e[t]??ws)+ws}}function RP(e,t,n,r,s){const o=!(e[n]??r);return{expanded:{...e,[n]:o},caps:!o&&!s?$R(t,n):t}}function IP(e,t,n,r){return(e||t!=="")&&(r>ws||n.trim()!=="")}const TP="Collapse, then reopen, to restore the compact list";function xP(e){return(e??ws)>ws}const CP=e=>`section-grown-hint-${e}`,DR=e=>e===1?"Show 1 more":`Show ${e} more`;function OP(e,t){return`${DR(e)} ${t}`}const cr={hidden:[],order:[...xa],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},NR=10,Lr=[25,50],LR=50,UR=500,FR=64;function vr(e){const t=Math.max(0,Math.floor(e));return t===0?NR:t<=Lr.length?Lr[t-1]:Lr[Lr.length-1]+(t-Lr.length)*LR}function PP(e,t){const n=vr(e+1)-vr(e),r=Math.max(0,Math.min(n,t));return r===1?"Show 1 more chat":`Show ${r} more chats`}function MP(e,t,n){const r=vr(t+1)-vr(t),s=vr(t),o=Math.min(s+r,e.length);let i=0;for(let l=s;l<o;l+=1)Lc(e[l])&&(i+=1);const c=Math.max(0,o-s-i);return c>0?c:Math.max(0,Math.min(r,n))}function Lc(e){return Zo(e)}function BR(e){return xR(e)?0:Zo(e)?1:2}function HR(e,t){return Zo(e)?MR(e):Nc(e,t)}function WR(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function jP(e,t,n){const r=e.map((s,o)=>({row:s,index:o,lane:t==="active-first"?BR(s):0,at:HR(s,n)}));return r.sort((s,o)=>s.lane-o.lane||WR(s.at,o.at)||s.index-o.index),r.map(s=>s.row)}function $P(e,t){const{limit:n,currentId:r,searching:s=!1}=t;if(s)return{rows:[...e],lifted:!1,remaining:0};const o=[];let i=Math.max(0,n);for(const d of e){if(i>0){o.push(d),i-=1;continue}Lc(d)&&o.push(d)}const c=Math.max(0,e.length-o.length);if(!r)return{rows:o,lifted:!1,remaining:c};const l=e.find(d=>d.session_id===r)??null;return l===null||o.includes(l)?{rows:o,lifted:!1,remaining:c}:{rows:[l,...o],lifted:!0,remaining:c}}function DP(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=vr(t.loads),r=[];let s=n;for(const l of e){if(Lc(l)){r.push(l);continue}s>0&&(r.push(l),s-=1)}const o=t.currentId,i=o==null?null:e.find(l=>l.session_id===o)??null,c=i!==null&&!r.includes(i);return{rows:c&&i!==null?[i,...r]:r,lifted:c,hidden:e.length-r.length-(c?1:0),held:e.length}}function NP(e){if(e.add<=0)return null;const t=e.add===1?"Show 1 more chat":`Show ${e.add} more chats`;if(e.drawn>=e.total)return{label:t,aria:t};const n=`${e.drawn} of ${e.total}`;return{label:`${t} · ${n}`,aria:`${t} · ${n} shown`}}const GR="mt-4",zR="mt-2";function LP(e){return e?GR:zR}function UP(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function FP(e,t){if(t==="section")return null;if(t==="flat")return[{key:"all",label:"",rows:[...e]}];const n=new Map;for(const o of e){const i=o.binding?.team||o.binding?.agent||"",c=i||"ungrouped",l=n.get(c)??{key:c,label:i||"Ungrouped",rows:[]};l.rows.push(o),n.set(c,l)}const r=[...n.values()],s=r.findIndex(o=>o.key==="ungrouped");return s>0&&r.push(...r.splice(s,1)),r}function KR(e,t){return!e.hidden.includes(t)}function Bh(e){return e.order.filter(t=>KR(e,t))}function BP(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function HP(e,t,n){const r=Bh(e),s=r.indexOf(t),o=r[s+n];if(s<0||o===void 0)return e;const i=e.order.indexOf(t),c=e.order.indexOf(o),l=[...e.order];return l[i]=o,l[c]=t,{...e,order:l}}const VR=["running","today","week","older"];function cu(e){return VR.includes(e)}function WP(e,t,n,r){if(!cu(t)||r&&!r(t))return!1;const s=Bh(e),o=s.indexOf(t);if(o<0)return!1;const i=s[o+n];return i===void 0||!cu(i)?!1:r?r(i):!0}const ZR=["section","agent","flat"],YR=["active-first","recent"];function GP(e){if(typeof e!="object"||e===null)return cr;const t=e,n=new Set(xa),r=[];if(Array.isArray(t.order))for(const h of t.order)typeof h=="string"&&n.has(h)&&(r.includes(h)||r.push(h));for(const h of xa)r.includes(h)||r.push(h);const s=[];if(Array.isArray(t.hidden))for(const h of t.hidden)typeof h=="string"&&n.has(h)&&(s.includes(h)||s.push(h));const o=ZR.includes(t.groupBy)?t.groupBy:cr.groupBy,i=RR.includes(t.basis)?t.basis:cr.basis,c=YR.includes(t.orderBy)?t.orderBy:cr.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(UR,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>=FR)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:s,order:r,groupBy:o,tagsEnabled:typeof t.tagsEnabled=="boolean"?t.tagsEnabled:!1,autoTagForks:typeof t.autoTagForks=="boolean"?t.autoTagForks:cr.autoTagForks,basis:i,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const Hh={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},QR=["recent","name","kind","modified","created","size"],XR=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function Uc(e){const t=e&&typeof e=="object"?e:{};return{sort:QR.includes(t.sort??"")?t.sort:Hh.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=>[ks,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>XR.includes(n)))]:[]}}const ks="Attachments";function zP(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,s)=>{const o=n(r),i=n(s);if(o===null||i===null)return o===i?0:o===null?1:-1;const c=typeof o=="string"&&typeof i=="string"?o.localeCompare(i,void 0,{numeric:!0}):Number(o)-Number(i);return(t.order==="asc"?c:-c)||r.mentioned-s.mentioned})}const JR=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 KP(e,t,n,r,s=[]){const o=e.filter(l=>l.highlighted),i=e.filter(l=>!l.highlighted),c=[];if(s.length&&c.push({id:ks,label:v("ui.canvas.files.attachments"),items:s,open:n||!r.has(ks),highlights:!1}),o.length&&c.push({id:"Highlights",label:v("ui.canvas.finder_layout.highlights"),items:o,open:n||!r.has("Highlights"),highlights:!0}),o.length&&i.length&&(c.push({id:"Working files",label:v("ui.canvas.finder_layout.working_files"),items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return c;if(!t.group)i.length&&c.push({id:"Files",label:v("ui.canvas.finder_layout.files"),items:i,open:!0,highlights:!1});else for(const l of["Images","Videos","Sounds","Documents","Spreadsheets","Other"]){const d=i.filter(u=>JR(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const qR=32,VP=4,Wh=32,Gh=18;function ZP(e){return e.height-Wh-(e.kind==="tiles"&&e.section.id===ks?Gh:0)}function YP(e,t,n){const r=[],s=new Map,o=Math.max(136,t-16),i=Math.max(1,Math.floor((o+4)/140));let c=0;const l=(d,u,f,h,g=1)=>{h.forEach((y,b)=>s.set(y.row.document.id,{band:r.length,column:b})),r.push({section:d,kind:u,height:f,top:c,items:h,cols:g}),c+=f};for(const d of e)if(l(d,"header",qR,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(d.id===ks){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=(o-4*(i-1))/i,g=Math.round((h-8)*3/4)+Wh+Gh;for(let y=0;y<f.length;y+=i)l(d,"tiles",g,f.slice(y,y+i),i)}else if(n&&d.id==="Images"){const u=(o-4*(i-1))/i,f=Math.round((u-8)*3/4)+32;for(let h=0;h<d.items.length;h+=i)l(d,"tiles",f,d.items.slice(h,h+i),i)}else if(n&&d.id==="Videos")for(const u of d.items)l(d,"video",Math.min(Math.round((o-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:i,positions:s}}function QP(e,t,n,r){const s=Math.max(600,n*.75);let o=0,i=e.bands.length;for(;o<i;){const d=o+i>>>1,u=e.bands[d];u.top+u.height<t-s?o=d+1:i=d}const c=new Set;for(let d=o;d<e.bands.length&&e.bands[d].top<=t+n+s;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 XP(e,t,n,r){const s=e.positions.get(t);if(!s)return null;const o=e.bands[s.band],i=e.bands.filter(u=>u.section.id===o.section.id&&u.items.length);if(n==="Home")return i[0]?.items[0]?.row.document.id??null;if(n==="End")return i.at(-1)?.items.at(-1)?.row.document.id??null;if(n==="ArrowLeft"||n==="ArrowRight")return o.items[s.column+(n==="ArrowLeft"?-1:1)]?.row.document.id??null;const c=n==="ArrowUp"||n==="PageUp"?-1:1,l=o.top+(n.startsWith("Page")?r*c:c);let d=s.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(s.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 eI="both",zh="by-turn",Ca=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function JP(e){for(const t of Ca)if(e===t.value)return t.value;return zh}function qP(e){return Ca.find(t=>t.value===e)?.label??Ca[0].label}const eM="primary+alt+shift+space",tI=/^f([1-9]|1[0-9]|2[0-4])$/;function nI(e){return tI.test(e)}function rI(e,t){const n=sI(e,t);return t==="mac"?n.join(""):n.join("+")}function sI(e,t){const r=t==="mac"?{primary:"⌘",meta:"⌘",ctrl:"⌃",alt:"⌥",shift:"⇧"}:{primary:"Ctrl",meta:t==="win"?"Win":"Super",ctrl:"Ctrl",alt:"Alt",shift:"Shift"},s={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(o=>o.trim().toLowerCase()).filter(o=>o.length>0).map(o=>o in r?r[o]:o in s?s[o]:nI(o)||o.length===1?o.toUpperCase():o)}const Yo=[{id:"panel.console",get label(){return v("ui.settings.shortcuts.action.open_console")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return v("ui.settings.shortcuts.action.open_canvas")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return v("ui.settings.shortcuts.action.open_run_details")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return v("ui.settings.shortcuts.action.open_asks")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return v("ui.settings.shortcuts.action.open_browser")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return v("ui.settings.shortcuts.action.open_code_review")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],oI=new Map(Yo.map(e=>[e.id,e])),iI=e=>oI.get(e),aI=new Set(["primary+0","primary+r","primary+shift+r","primary+t","primary+shift+t","primary+l",...[1,2,3,4,5,6,7,8,9].map(e=>`primary+${e}`)]);class cI 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,s]of this)t.call(n,s,r,this)}[Symbol.iterator](){return this.entries()}}const Fc=new cI([["primary+p",()=>v("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>v("ui.settings.shortcuts.reserved.palette_commands")],["primary+k",()=>v("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>v("ui.settings.shortcuts.reserved.new_chat")],["primary+b",()=>v("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>v("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>v("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>v("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>v("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>v("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>v("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>v("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>v("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>v("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>v("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>v("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>v("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>v("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>v("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>v("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>v("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>v("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>v("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>v("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>v("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>v("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>v("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>v("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>v("ui.settings.shortcuts.reserved.browser_last_tab"):()=>v("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>v("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>v("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>v("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>v("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>v("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>v("ui.settings.shortcuts.reserved.close")],["primary+m",()=>v("ui.settings.shortcuts.reserved.minimise")]]),lI=["primary","alt","shift"],dI={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},uI=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),fI=e=>uI.has(e)||/^[a-z0-9]$/.test(e);function Bc(e){if(typeof e!="string")return null;const t=e.toLowerCase().split("+").map(o=>o.trim()).filter(o=>o.length>0);if(t.length===0)return null;const n=t[t.length-1];if(!fI(n))return null;const r=new Set;for(const o of t.slice(0,-1)){const i=dI[o];if(i===void 0)return null;r.add(i)}return[...lI.filter(o=>r.has(o)),n].join("+")}const Kh=e=>e.split("+").includes("primary");function Qo(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!Fc.has(n)?n:iI(e)?.defaultChord??null}function tM(e){const t=new Map;for(const n of Yo){const r=Qo(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const pI=e=>e==="mac"?v("ui.settings.shortcuts.capture.needs_modifier_mac"):v("ui.settings.shortcuts.capture.needs_modifier");function hI(e,t,n,r="linux",s=new Map){const o=e===null?null:Bc(e);if(o===null)return v("ui.settings.shortcuts.capture.unbindable");if(!Kh(o))return pI(r);const i=Fc.get(o);if(i!==void 0)return i;const c=s.get(o);if(c!==void 0)return v("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of Yo)if(l.id!==t&&Qo(l.id,n)===o)return v("ui.settings.shortcuts.capture.already_assigned",{label:l.label});return null}function mI(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const s of Yo){const o=t[s.id];if(o===null){r[s.id]=null;continue}const i=typeof o=="string"?Bc(o):null,c=i!==null&&aI.has(i),l=i!==null&&Kh(i)&&(c||!Fc.has(i)&&!n.has(i))?i:null;l!==null&&(r[s.id]=l);const d=Qo(s.id,r);d!==null&&n.add(d)}return r}function nM(e,t,n){const r=Qo(e,t);return r===null?null:Vh(r,n)}function Vh(e,t){return rI(e,t)}function rM(e,t){const n=e.split("+"),r=n[n.length-1],s=n.slice(0,-1).map(o=>o==="primary"?t==="mac"?"Meta":"Control":o==="shift"?"Shift":o==="alt"?"Alt":o);return{glyph:Vh(e,t),aria:[...s,r.length===1?r.toUpperCase():r].join("+")}}const lu=e=>{for(const t of[e.role,...e.variants])if(!ym.includes(t))throw new Error(`Unknown accent role: ${t}`);return Object.freeze({...e,variants:Object.freeze(e.variants)})},Zh=Object.freeze([lu({id:"primary",role:"accent",storage:"seeds",labelKey:"ui.settings.appearance.editor.accent.primary",usageKey:"ui.settings.appearance.editor.accent.primary_usage",variants:["accentHover","accentActive","accentWash","onAccent"],preview:"interaction",ink:"accent",wash:"accentWash"}),lu({id:"secondary",role:"accentAlt",storage:"overrides",labelKey:"ui.settings.appearance.editor.accent.secondary",usageKey:"ui.settings.appearance.editor.accent.secondary_usage",variants:["accentAltWash"],preview:"identity",ink:"accentAlt",wash:"accentAltWash"})]),sM=e=>Zh.some(t=>t.role===e||t.variants.includes(e)),Me={strongText:7,text:4.5,nonText:3},du=new Set(["inkDisabled"]),Be=["canvas","surface","elevated","sunken"],Yh=[["ink",Me.strongText],["inkMuted",5.5],["inkDim",5]],on=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Wt={dark:{canvasMin:9,canvasMax:15,elevatedMax:22},light:{canvasMax:94,sunkenMin:80}},bn={canvasSurface:[2.5,5],surfaceElevated:[2,6],canvasSunken:[1.5,6]},gI=2,_I=1.03,Hc=8,xo=2,uu=.8,fu=3,pu=2,hu=4,Oa=2.5,mu=4,gu=2.5,_u=2,bu=2,bI=[{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:Be,fill:"accent",border:"accent",ink:"onAccent"},{name:"primary button (hover)",on:Be,fill:"accentHover",border:"accentHover",ink:"onAccent"},{name:"primary button (pressed)",on:Be,fill:"accentActive",border:"accentActive",ink:"onAccent"},{name:"outline control",on:Be,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:"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 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:Be,fill:"accentWash",border:null,ink:"inkMuted",edge:!1},{name:"input field",on:Be,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:Be,fill:"surface",border:"borderControl",ink:"ink"},{name:"browser file-transfer row (refused)",on:Be,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:Be,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}],vI=[{name:"context wheel arc against its track",a:["info","warning","danger"],b:"sunken",floor:Me.nonText}],yI=[{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-subagent mark",on:["surface","rowSelected","rowHover"],fg:"accent"},{name:"spinner track against its ground",on:Be,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"}],wI=[{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}],kI=["borderControl","accent","successBorder","warningBorder","dangerBorder","infoBorder"],SI=["accent","success","warning","danger","info"],EI=[{fg:"surface",on:"accent",floor:Me.text,name:"the console terminal's cursor ink on its own cursor (9.1)"}],AI=[],RI=[{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"}],lr=15,dr=8,II=[{theme:"catppuccinMocha",a:"accentAlt",b:"info",floor:lr,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:lr,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:lr,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:lr,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:lr,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:dr,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:dr,got:0,why:"`info` IS `accent` (`#00EFFF`), the palette's single cyan"},{theme:"obsidian",a:"info",b:"accent",floor:dr,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:dr,got:0,why:"`info` IS `accent` (`#91B7E9`), the palette's single steel blue"},{theme:"githubLight",a:"info",b:"accent",floor:dr,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"}],TI=[],xI=[],CI=["mode",...Be,"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"],Qs=["success","warning","danger","info"],OI=["success","warning","danger","info","ink"],hr=8,Ur="tokenCommand",Xs=hr,PI=["surface","elevated","messageSurface"],MI=[{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."}],nn=15,Ss=15,qr=hr,ot=2,vu=4,jI=.75,yu=.12,$I=[["surface","canvas"],["surface","elevated"],["elevated","canvas"]],DI=4,NI=2,LI=2,Ni=1,Co=2,Li=2,wu=.5,UI=1.5,FI=1.5,Qh=5,Oo=2.5,Xh=.5,Po=5,Pa=4,Ma=24,ku=12,BI=.45,Su=.75,HI=.25,an=2,Jh=2,WI=[{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"}],GI=[{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"}],ja=10,Js="surface",Eu=2,Au=1.15,zI=({composed:e=!1,capturePairs:t=!1}={})=>{const n={assertions:0,failures:0,composed:e},r=[],s=(T,m)=>e?m>=T-.01:Math.abs(T-m)<.01,o=(T,m,w)=>e?m>=T-w:Math.abs(T-m)<=w,i=new Set,c=(T,m,w,S)=>{const x=RI.find(N=>N.theme===T&&N.role===m&&N.ground===w&&s(N.got,S));return x&&i.add(x),x},l=new Set,d=(T,m,w,S)=>{const x=II.find(N=>N.theme===T&&N.a===m&&N.b===w&&s(N.got,S));return x&&l.add(x),x},u=new Set,f=new Set,h=new Set,g=(T,m,w)=>`${T} on ${m} in ${w}`,y=[],b=T=>{n.failures++,y.push(`FAIL ${T}`)},_=new Set,p=(T,m,w,S)=>{const x=AI.find(N=>N.theme===T&&N.fg===m&&N.bg===w&&s(N.got,S));return x&&_.add(x),x};return Object.assign(n,{readings:r,pinMatches:s,ledgerHolds:o,log:y,fail:b,exceptionSeen:_,perceptibleSeen:i,pairPinSeen:l,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:h,controlEdgeKey:g,pinClaims:new Set,findException:p,findPerceptibleException:c,findPairPin:d,assertPair:(T,m,w,S,x,N)=>{const E=m[w],z=m[S];if(!W(E)||!W(z))return;n.assertions++;const F=oe(E,z);if(t&&r.push({foreground:w,background:S,value:F,floor:x}),F>=x)return;const X=D(F);p(T,w,S,X)||b(`${T}: ${N} — ${w} ${E} on ${S} ${z} = ${X}:1, need ${x}:1`)},assertIdentityPair:(T,m,w,S,x,N)=>{const E=m[w],z=m[S];if(!W(E)||!W(z))return;n.assertions++;const F=D(pe(E,z));if(F>=x)return;const X=d(T,w,S,F);if(X){X.floor!==x&&b(`${T}: \`${w}\`/\`${S}\` is pinned at floor ${X.floor} but this assertion asks for ${x} — a pin records the bound it was granted under, so the pin and the floor have to be raised together`);return}b(`${T}: ${N} — \`${w}\` ${E} and \`${S}\` ${z} are ΔE00 ${F} apart (need ${x}) — two roles a reader has to tell apart at this site cannot be one colour at two weights; move the palette value, or pin the palette in \`PAIR_PINS\` with the constraint that refuses it`)},floorUnreachablePin:(T,m)=>WI.find(S=>S.id===T&&S.role===m)??null,shortfallPin:(T,m,w)=>GI.find(x=>x.id===T&&x.role===m&&x.bound===w)??null}),n},KI=(e,t)=>{const{fail:n,assertPair:r,assertIdentityPair:s,findException:o,findPerceptibleException:i,floorUnreachablePin:c,shortfallPin:l,pinClaims:d,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:h,controlEdgeKey:g,pinMatches:y,ledgerHolds:b}=e;for(const{id:_,palette:p}of[t]){for(const m of CI)e.assertions++,m in p||n(`${_}: missing required role \`${m}\``);for(const[m,w]of Yh)if(!du.has(m))for(const S of on)r(_,p,m,S,w,"body ink");for(let m=0;m<Be.length;m++)for(let w=m+1;w<Be.length;w++){const S=p[Be[m]],x=p[Be[w]];!W(S)||!W(x)||(e.assertions++,oe(S,x)<1.03&&n(`${_}: grounds \`${Be[m]}\` ${S} and \`${Be[w]}\` ${x} are indistinguishable (${D(oe(S,x))}:1) — elevation is a lightness step here, so they must differ`))}const R=[{role:"rowHover",castFloor:m=>Math.max(Oo,Xh*m),castCeiling:m=>Math.max(m,Oo),stepFloor:UI,stepCeiling:null},{role:"rowSelected",castFloor:m=>Math.max(Po,m),castCeiling:m=>Math.min(Math.max(m+Pa,Po),Ma),stepFloor:FI,stepCeiling:Qh}];for(const m of R){const w=m.role,S=p[w];if(!W(S))continue;const[x,N,E]=ie(S),[z,F,X]=ie(p.surface),[,$e,We]=ie(p.accent),K=Math.hypot($e,We),he=Math.hypot(F,X),re=Math.hypot(N,E),Pe=m.castFloor(he),De=m.castCeiling(he),Ge=he<an;e.assertions++;const qe=he>=an?{name:"the panel's",hue:Math.atan2(X,F)}:K>=Jh?{name:"`accent`'s",hue:Math.atan2(We,$e)}:{name:"the panel's",hue:Math.atan2(X,F)},me=Math.atan2(E,N),Ie=Math.abs(((me-qe.hue)*180/Math.PI+540)%360-180);re>=an&&Ie>ku&&n(`${_}: \`${w}\` ${S} sits ${D(Ie)} degrees off ${qe.name} hue (the limit is ${ku}) — a row state has to be the colour of the backdrop it is a state of, and the values this round replaced took the \`accent\`'s hue instead, which is more than 45 degrees off the panel on 25 of the 59 palettes and is the off-colour the operator reported. Take the hue from ${qe.name} and re-author the value at it`),e.assertions++,Pe>De+1e-9?(d.add(`${_}:${w}:floor`),e.assertions++,c(_,w)||n(`${_}: \`${w}\` ${S} carries C* ${D(re)}, and its cast floor ${D(Pe)} is ABOVE its ceiling ${D(De)} — the panel's own cast is louder than this role is allowed to be, so the value has to sit at the ceiling and \`${_}\`'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++,re<De-Su&&n(`${_}: \`${w}\` ${S} carries C* ${D(re)} where its cast floor ${D(Pe)} is above its ceiling ${D(De)} — the floor cannot be held, but the CEILING is reachable and is what the ledger row promises this value sits at`)):re<Pe-BI&&n(`${_}: \`${w}\` ${S} carries C* ${D(re)}, under the cast floor ${D(Pe)} — 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++,re>De+Su&&n(`${_}: \`${w}\` ${S} carries C* ${D(re)}, past the ${D(De)} this file allows — ${w==="rowHover"?"the hover may be lighter than its ground, it may not be a MORE coloured plane than it":`the selection may carry the panel's cast and the rule's rise of ${Pa} above it, and no more`}, and the flat cap is ${Ma}. 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=x-z,Ne=p.mode==="dark"?Et:-Et;if(Ne<m.stepFloor-1e-9&&n(`${_}: \`${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+HI+1e-9&&n(`${_}: \`${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"&&W(p.rowHover)){const[Se,dt,mt]=ie(p.rowHover),Ot=p.mode==="dark"?Se-z:z-Se,Tr=Math.hypot(dt,mt);if(e.assertions++,Ne<Ot+Ni-1e-9){const qn=l(_,"rowSelected","rank");d.add(`${_}:rowSelected:rank`),e.assertions++,qn?b(qn.measured,Ne-Ot,.05)||n(`${_}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${qn.measured} and the pair now ranks ${D(Ne-Ot)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${_}: \`rowSelected\` ${S} is ${D(Ne)} \`L*\` from \`surface\` where \`rowHover\` ${p.rowHover} is ${D(Ot)} — the selection has to be at least ${Ni} \`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(_,"rowSelected","rank")&&n(`${_}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — the pair ranks ${D(Ne-Ot)} \`L*\`, clear of the ${Ni} the row claims it misses. Remove the row`);e.assertions++,re<Tr+Co-1e-9&&n(`${_}: \`rowSelected\` ${S} carries C* ${D(re)} where \`rowHover\` ${p.rowHover} carries ${D(Tr)} — the selection has to carry at least ${Co} 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++,Ot<wu*Ne-1e-9&&n(`${_}: \`rowHover\` ${p.rowHover} takes ${D(Ot)} \`L*\` of the ${D(Ne)} the selection takes (${Math.round(Ot/Ne*100)}%), under the ${Math.round(wu*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 Ct=pe(S,p.surface);if(Ct<ot-1e-9){const Se=l(_,w,"band");d.add(`${_}:${w}:band`),e.assertions++,Se?b(Se.measured,Ct,.05)||n(`${_}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Se.measured} and the palette now measures ${D(Ct)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${_}: \`${w}\` ${S} is ΔE00 ${D(Ct)} from \`surface\` ${p.surface} (the field floor is ${ot}) — 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(_,w,"band")&&n(`${_}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${D(Ct)} from \`surface\`, clear of the ${ot} the row claims it misses. Remove the row`);e.assertions++;const _e=pe(S,p.accentWash);if(!Ge&&_e<Li){const Se=l(_,w,"wash");d.add(`${_}:${w}:wash`),e.assertions++,Se?b(Se.measured,_e,.05)||n(`${_}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Se.measured} and the palette now measures ${D(_e)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${_}: \`${w}\` ${S} is ΔE00 ${D(_e)} from \`accentWash\` ${p.accentWash} (need ${Li}) — a hovered row beside a hovered button would merge into one mark, and they are a row state and a control state, so they have to be two. A backdrop-relative fill and an accent-derived wash are the same kind of rung, so this can bite on a palette with a strong cast in both; that is a ledger row with the reading, not a widened floor`)}else!e.composed&&!Ge&&l(_,w,"wash")&&n(`${_}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${D(_e)} from \`accentWash\`, clear of the ${Li} the row claims it misses. Remove the row`)}if(W(p.rowHover)&&W(p.rowSelected)){e.assertions++;const m=pe(p.rowSelected,p.rowHover),w=LI;m<w-1e-9&&n(`${_}: \`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(W(p.sunken)&&W(p.rowHover)&&W(p.rowSelected)&&W(p.borderControl))for(const m of["rowHover","rowSelected"]){e.assertions++;const w=pe(p.sunken,p[m]),S=oe(p.borderControl,p[m]);w<ot&&S<Me.nonText&&n(`${_}: the agents sidebar's avatar plate has no perceivable edge against \`${m}\` — its \`sunken\` fill ${p.sunken} is ΔE00 ${D(w)} from it (need ${ot}) and the plate's \`borderControl\` edge ${p.borderControl} is ${D(S)}:1 against that same fill (need ${Me.nonText}:1), so the row's own ${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"&&W(p.ink)){const m=p.scrim.match(/rgb\((\d+)\s+(\d+)\s+(\d+)\s*\/\s*([\d.]+)\)/);if(m){const[w,S,x,N]=m.slice(1).map(Number);for(const E of on){if(!W(p[E]))continue;const z=[1,3,5].map($e=>Number.parseInt(p[E].slice($e,$e+2),16)),F=`#${[w,S,x].map(($e,We)=>Math.round($e*N+z[We]*(1-N)).toString(16).padStart(2,"0")).join("")}`;e.assertions++;const X=oe(p.ink,F);X<Me.nonText&&n(`${_}: the lightbox's current-tile ring has no perceivable edge over \`${E}\` — \`ink\` is ${D(X)}:1 against the scrim composited over it (need ${Me.nonText}:1). The scrim dims whatever is open under it, so the ring's role has to clear every ground the overlay can open over`)}}}for(const m of kI)for(const w of Be)r(_,p,m,w,Me.nonText,"structural edge");const k=[...Be,"accentWash","messageSurface"];for(const m of SI)for(const w of k)r(_,p,m,w,Me.text,"colour as text");r(_,p,"warning","elevated",Me.text,"the picker's partial-listing note"),r(_,p,"danger","elevated",Me.text,"danger as text on a dialog's ground"),r(_,p,"warning","rowSelected",Me.text,"integration status text on a deep-linked row"),r(_,p,"accent","warningWash",Me.text,"model-access band links on the warning wash"),r(_,p,"warning","rowHover",Me.text,"the partial delivery word on the hovered row's ground"),r(_,p,"dangerBorder","elevated",Me.nonText,"the danger control's only edge on a dialog's ground");for(const m of bI)for(const w of m.on){const S=p[w],x=m.fill?p[m.fill]:S,N=p[m.ink],E=m.border?p[m.border]:null;if(!W(S)||!W(x)||!W(N))continue;e.assertions++;const z=oe(N,x);if(z<Me.text&&!du.has(m.ink)&&!o(_,m.ink,m.fill??w,z)&&n(`${_}: ${m.name} on ${w} — ink ${m.ink} ${N} on fill ${x} = ${z}:1, need ${Me.text}:1`),m.edge!==!1){e.assertions++;const F=oe(x,S),X=W(E)?oe(E,S):0,$e=Math.max(F,X);if($e<Me.nonText){const We=xI.find(K=>K.control===m.name&&K.ground===w&&K.theme===_&&y(K.got,D($e)));We?h.add(g(We.control,We.ground,We.theme)):n(`${_}: ${m.name} on ${w} has no perceivable edge — fill ${F}:1, border ${X}:1, need one at ${Me.nonText}:1`)}}}for(const m of EI)r(_,p,m.fg,m.on,m.floor,m.name);for(const m of yI)for(const w of m.on)r(_,p,m.fg,w,m.floor??Me.nonText,m.name);for(const m of vI){const w=p[m.b];if(W(w))for(const S of m.a){const x=p[S];if(!W(x))continue;e.assertions++;const N=oe(x,w);N<m.floor&&!o(_,S,m.b,N)&&n(`${_}: ${m.name} — ${S} ${x} against ${m.b} ${w} = ${N}:1, need ${m.floor}:1`)}}for(const m of wI){const w=p[m.role];if(!W(w))continue;for(const F of m.on){if(!W(p[F]))continue;e.assertions++;const X=pe(w,p[F]);X<m.minDeltaE&&!i(_,m.role,F,D(X))&&n(`${_}: ${m.name} — ${m.role} ${w} on ${F} ${p[F]} is ΔE00 ${D(X)}, need ${m.minDeltaE} to be seen at all`)}if(!m.pairedWith||!m.against)continue;const S=p[m.pairedWith],x=p[m.against];if(!W(S)||!W(x))continue;e.assertions++;const N=oe(w,x),E=oe(S,x),z=Math.max(N/E,E/N);z>m.maxWeightChange&&n(`${_}: ${m.name} — ${m.role} is ${D(z)}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<Qs.length;m++)for(let w=m+1;w<Qs.length;w++){const[S,x]=[Qs[m],Qs[w]];if(!W(p[S])||!W(p[x]))continue;e.assertions++;const N=pe(p[S],p[x]);N<nn&&n(`${_}: \`${S}\` ${p[S]} and \`${x}\` ${p[x]} are too close to tell apart (ΔE00 ${D(N)}, need ${nn}) — a semantic a reader cannot distinguish from another semantic is not a semantic`)}if(W(p.accentAlt)){if(W(p.accent)){e.assertions++;const x=pe(p.accentAlt,p.accent);x<nn&&n(`${_}: the second accent \`accentAlt\` ${p.accentAlt} is ΔE00 ${D(x)} from \`accent\` ${p.accent} (need ${nn}) — two accents have to be two accents at the sizes this one is drawn at, and a value that buys its separation by darkening is the same hue at another weight rather than a second hue`)}for(const x of["success","warning","danger"]){if(!W(p[x]))continue;e.assertions++;const N=pe(p.accentAlt,p[x]);N<nn&&n(`${_}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${D(N)} from \`${x}\` ${p[x]} (need ${nn}) — a decorative mark a reader can mistake for "${x==="danger"?"something broke":x}" costs them something real, so the palette moves the hue rather than the assertion`)}if(W(p.info)){e.assertions++;const x=pe(p.accentAlt,p.info);x<hr&&n(`${_}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${D(x)} from \`info\` ${p.info} (need ${hr}) — \`info\` is the family the port mapped the TUI's \`signal\` onto, so the floor here is the reduced one and not ${nn}; below it the two take the same name`)}const[,m,w]=ie(p.accentAlt),S=Math.hypot(m,w);e.assertions++,S<Ss&&n(`${_}: \`accentAlt\` ${p.accentAlt} is C* ${D(S)} (need ${Ss}) — a second accent drained toward the ink passes every separation above and stops being a hue, which is the one way this role fails while the gate stays green`);for(const x of["canvas","surface","sunken"])r(_,p,"accentAlt",x,Me.text,"second accent as text");r(_,p,"accentAlt","elevated",Me.text,"second accent as text on a row's state ground")}if(s(_,p,"accentAlt","info",lr,"the tool row's two category inks"),s(_,p,"info","accent",dr,"the settled read ink against the liveness ink"),W(p.accentAltWash)&&W(p.accentWash)){e.assertions++;const m=pe(p.accentAltWash,p.accentWash);m<ot&&n(`${_}: \`accentAltWash\` ${p.accentAltWash} is ΔE00 ${D(m)} from \`accentWash\` ${p.accentWash} (need ${ot}) — 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 OI){if(!W(p[m])||!W(p.inkDim))continue;e.assertions++;const w=pe(p[m],p.inkDim);w<hr&&n(`${_}: syntax \`${m}\` ${p[m]} sits at ΔE00 ${D(w)} from comment \`${p.inkDim}\` (need ${hr}) — a token the eye cannot separate from the comment beside it is not highlighted`)}if(W(p[Ur])&&W(p.ink)){const m=MI.find(w=>w.theme===_);for(const w of PI){if(!W(p[w]))continue;e.assertions++;const S=oe(p[Ur],p[w]);S<4.5&&n(`${_}: the command token \`tokenCommand\` ${p[Ur]} reads ${D(S)}:1 on \`${w}\` (need 4.5) - the token is text a user typed (the composer's leading /word, or the sent \`$skill\` mention), not decoration`)}for(const w of["ink","accent","success"]){if(!W(p[w]))continue;e.assertions++;const S=pe(p[Ur],p[w]);if(!!m?.against.includes(w)){y(m.got,S)||n(`${_}: 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<Xs&&n(`${_}: the command token \`tokenCommand\` ${p[Ur]} sits at ΔE00 ${D(S)} from \`${w}\` ${p[w]} (need ${Xs}) - the composer paints this run in the same box as that ink, so a reader cannot tell which is which`)}if(W(p.success)){e.assertions++;const w=pe(p.success,p.ink);w<Xs&&n(`${_}: the roster NAME's ink \`success\` ${p.success} sits at ΔE00 ${D(w)} from prose \`ink\` ${p.ink} (need ${Xs}) - a resolved name that reads as prose is not a run`)}}if(W(p.inkMuted)&&W(p.inkDim)){e.assertions++,u.add(_);const m=pe(p.inkMuted,p.inkDim),w=TI.find(S=>S.theme===_);w&&f.add(w),m<qr?w?y(w.got,m)||n(`${_}: 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(`${_}: the control ink \`inkMuted\` ${p.inkMuted} sits at ΔE00 ${D(m)} from the readout ink \`inkDim\` ${p.inkDim} (need ${qr}) - a chip that opens cannot be told from a reading that does not`):w&&!e.composed&&n(`${_}: the ink step is pinned at ${w.got} but now measures ${D(m)}, clearing the ${qr} floor - delete the pin rather than leaving dead weight in the contract`)}for(const[m,w,S=ot]of[["canvas","surface"],["surface","elevated"],["elevated","sunken"],["accent","accentHover"],["accentHover","accentActive"],["accent","accentActive"],["surface","sunken"],["canvas","elevated",DI]]){if(!W(p[m])||!W(p[w]))continue;e.assertions++;const x=pe(p[m],p[w]);x<S&&n(`${_}: adjacent \`${m}\` and \`${w}\` are ΔE00 ${D(x)} apart (need ${S}) — a step the eye cannot see is not a step`)}{const m=ie(p.canvas)[0],w=ie(p.surface)[0],S=ie(p.elevated)[0],x=ie(p.sunken)[0],N=p.mode==="dark";e.composed||(e.assertions++,N&&(m<Wt.dark.canvasMin||m>Wt.dark.canvasMax)&&n(`${_}: dark \`canvas\` ${p.canvas} sits at L* ${D(m)} — the band is [${Wt.dark.canvasMin}, ${Wt.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>Wt.dark.elevatedMax&&n(`${_}: dark \`elevated\` ${p.elevated} sits at L* ${D(S)} — the ceiling is L* ${Wt.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>Wt.light.canvasMax&&n(`${_}: light \`canvas\` ${p.canvas} sits at L* ${D(m)} — the ceiling is L* ${Wt.light.canvasMax}. \`elevated\` at L* 100 is the end of sRGB's ramp and the minimum canvas-to-elevated spread is 2.5 + 2.5 L*, so a canvas above 95 has no room for both steps; 94 leaves 1 L* for 8-bit rounding`),e.assertions++,!N&&x<Wt.light.sunkenMin&&n(`${_}: light \`sunken\` ${p.sunken} sits at L* ${D(x)} — the floor is L* ${Wt.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[E,z,F,[X,$e],We]of[["canvas -> surface","canvas","surface",bn.canvasSurface,w-m],["surface -> elevated","surface","elevated",bn.surfaceElevated,S-w],["canvas -> sunken","canvas","sunken",bn.canvasSunken,m-x]])if(e.assertions++,(We<X-1e-9||We>$e+1e-9)&&n(`${_}: the ${E} step is ${D(We)} L*, outside [${X}, ${$e}] — 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(_,p,z,F,_I,`${E} step`),z==="canvas"&&F==="sunken"||z==="surface"&&F==="elevated"){e.assertions++;const K=pe(p[z],p[F]),he=z==="canvas"?gI:NI;K<he&&n(z==="canvas"?`${_}: \`canvas\` and \`sunken\` are ΔE00 ${D(K)} apart (need ${he}) — 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`:`${_}: \`surface\` ${p.surface} and \`elevated\` ${p.elevated} are ΔE00 ${D(K)} apart (need ${he}) — 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(_,p,"ink","canvas",Hc,"the transcript's body ink");for(const m of on){if(!W(p.inkDisabled)||!W(p.inkDim)||!W(p[m]))continue;e.assertions++;const w=oe(p.inkDisabled,p[m]),S=oe(p.inkDim,p[m]);w>uu*S+1e-9&&n(`${_}: \`inkDisabled\` on ${m} measures ${D(w)}:1 against \`inkDim\`'s ${D(S)}:1 — a factor of ${D(w/S)}, over the ${uu} ceiling. A disabled control that meets the ink floors does not read as disabled`)}for(const[m,w]of[["inkDim","inkMuted"],["inkMuted","ink"]]){if(!W(p[m])||!W(p[w]))continue;e.assertions++;const S=pe(p[m],p[w]);S<xo&&n(`${_}: \`${w}\` and \`${m}\` are ΔE00 ${D(S)} apart (need ${xo}) — the three weights are a ladder, and a rung the eye cannot see is not a rung`)}{const m=pe(p.sunken,p.elevated);e.assertions++,m<fu&&n(`${_}: the palette/picker active row (\`sunken\` ${p.sunken}) is ΔE00 ${D(m)} from the dialog ground it is painted on (\`elevated\` ${p.elevated}), need ${fu} — a selection is a state the reader has to find while scanning, not a surface they read, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ie(p.sunken)[0]-ie(p.elevated)[0]);w<pu&&n(`${_}: the palette/picker active row sits ${D(w)} L* from \`elevated\`, under the ${pu} L* floor — ΔE00 is a budget a chroma-only step can spend while the mark vanishes in a greyscale render, so the lightness half is asserted too`)}{if(p.messageSurface===void 0)continue;if(!W(p.messageSurface)){n(`${_}: the user message block's fill \`messageSurface\` ${JSON.stringify(p.messageSurface)} is present but not a flat hex colour, so the role's floor would be silently unmeasured - a malformed value must not switch a floor off`);continue}if(!W(p.canvas))continue;const m=pe(p.messageSurface,p.canvas);e.assertions++,m<hu&&n(`${_}: the user message block's fill \`messageSurface\` ${p.messageSurface} is ΔE00 ${D(m)} from \`canvas\` ${p.canvas} (need ${hu}) — the fill IS the block's boundary, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ie(p.messageSurface)[0]-ie(p.canvas)[0]);w<Oa&&n(`${_}: the user message block's fill sits ${D(w)} L* from \`canvas\`, under the ${Oa} L* floor — ΔE00 is a budget a chroma-only step can spend while the mark vanishes in a greyscale render, so the lightness half is asserted too`)}{if(p.mediaSurface===void 0)continue;if(!W(p.mediaSurface)){n(`${_}: the media tile's fill \`mediaSurface\` ${JSON.stringify(p.mediaSurface)} is present but not a flat hex colour, so the role's floor would be silently unmeasured - a malformed value must not switch a floor off`);continue}if(!W(p.canvas))continue;const m=pe(p.mediaSurface,p.canvas);e.assertions++,m<mu&&n(`${_}: the media tile's fill \`mediaSurface\` ${p.mediaSurface} is ΔE00 ${D(m)} from \`canvas\` ${p.canvas} (need ${mu}) — the fill IS the borderless tile's extent, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ie(p.mediaSurface)[0]-ie(p.canvas)[0]);w<gu&&n(`${_}: the media tile's fill sits ${D(w)} L* from \`canvas\`, under the ${gu} 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 Be){if(!W(p.accentWash)||!W(p[m]))continue;e.assertions++;const w=pe(p.accentWash,p[m]);w<_u&&n(`${_}: the accent wash on ${m} is ΔE00 ${D(w)} (need ${_u}) — 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(!W(p.sunken)||!W(p[m]))continue;e.assertions++;const w=pe(p.sunken,p[m]);w<bu&&n(`${_}: the keycap's ground \`sunken\` ${p.sunken} is ΔE00 ${D(w)} from ${m} ${p[m]} (need ${bu}) — the cap annotates the row the reader has just selected, so its ground has to survive being painted on that row`)}if(W(p.chartBarHover)&&W(p.accent)&&W(p[Js])){e.assertions++;const m=pe(p.chartBarHover,p.accent);m<ja&&n(`${_}: \`chartBarHover\` ${p.chartBarHover} is ΔE00 ${D(m)} from \`accent\` ${p.accent}, need ${ja} — 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[Js]),S=oe(p.accent,p[Js]);w<S&&n(`${_}: \`chartBarHover\` is ${D(w)}:1 on ${Js} where \`accent\` is ${D(S)}:1 — the hovered mark must not recede toward the ground it is drawn on`)}for(const m of Be){if(!W(p.hairline)||!W(p[m]))continue;e.assertions++;const w=pe(p.hairline,p[m]);w<vu&&n(`${_}: \`hairline\` on \`${m}\` is ΔE00 ${D(w)} (need ${vu}) — 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<Au&&n(`${_}: \`hairline\` on \`${m}\` is ${D(S)}:1 (need ${Au}) — its ΔE00 is carried in chroma, which a 1px line does not survive`),e.assertions++,S>Eu&&n(`${_}: \`hairline\` on \`${m}\` is ${D(S)}:1 (max ${Eu}) — past this it is drawing a border, and the system already has one of those`)}for(const[m,w]of $I){if(!W(p.hairline)||!W(p[m])||!W(p[w]))continue;const S=nu(p.hairline,p[m],jI);e.assertions++;const x=pe(S,p[m]);x<ot&&n(`${_}: the panel seam over \`${m}\` is ΔE00 ${D(x)} from that ground (need ${ot}) — the seam is half the boundary, and half a boundary the reader cannot see is a panel edge that disappears`),e.assertions++;const N=pe(S,p[w]);N<ot&&n(`${_}: the panel seam over \`${m}\` is ΔE00 ${D(N)} from \`${w}\` (need ${ot}) — the seam has to read from the plane it faces as well as the one it sits on`)}const O=nu(p.accent,p.surface,yu);for(const[m,w,S]of[["inkMuted",Me.text,"washed row metadata ink"],["ink",Me.text,"washed row body ink"]]){const x=p[m];if(!W(x))continue;e.assertions++;const N=D(oe(x,O));N>=w||n(`${_}: ${S} — ${m} ${x} on the arrival band ${O} (accent ${yu} over surface) = ${N}:1, need ${w}:1`)}const L=oe(O,p.surface),P=oe(p.rowHover,p.surface),T=oe(p.rowSelected,p.surface);e.assertions+=2,L<=P&&n(`${_}: the arrival band is ${D(L)}:1 over the pane and the row hover is ${D(P)}:1 — the mark the reader was TOLD about cannot be drawn more quietly than one their pointer rests on`),L<=T&&n(`${_}: the arrival band is ${D(L)}:1 over the pane and the selected row is ${D(T)}:1 — the arrival must outrank the row the reader is already on, or the landing reads as a selection`)}},VI=Object.freeze({soft:-100,gentle:-50,standard:0,strong:50,high:100}),ZI=Object.freeze({dark:Object.freeze({high:5,soft:20}),light:Object.freeze({high:97,soft:89})}),YI=["canvas","surface","elevated","sunken","messageSurface","mediaSurface","rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash","hairline","hairlineStrong","inkDisabled"],QI=new Set(["rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash"]),oo=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],It=oo.slice(0,4),Fr=[...It,"accentWash","messageSurface"],Ui={ink:[oo,7],inkMuted:[oo,5.5],inkDim:[oo,5],borderControl:[It,3],accent:[[...Fr,"warningWash"],4.5],accentHover:[It,4.5],accentActive:[It,4.5],tokenCommand:[["surface","elevated","messageSurface"],4.5],accentAlt:[It,4.5],success:[Fr,4.5],warning:[[...Fr,"rowSelected","rowHover"],4.5],danger:[Fr,4.5],info:[Fr,4.5],successBorder:[It,3],warningBorder:[It,3],dangerBorder:[It,3],infoBorder:[It,3],chartBarHover:[["surface"],3]},xt=.05,Ru=.3,Iu=4.1,XI=.06,JI=/^#[0-9A-Fa-f]{6}$/,rt=e=>typeof e=="string"&&JI.test(e),Lt=e=>e.slice(0,7).toUpperCase(),at=(e,t,n)=>{const r=Math.max(0,Math.min(100,e));for(let s=1;s>=0;s-=.02){const o=To([r,t*s,n*s]);if(o)return o}return To([r,0,0])},zn=(e,t,n)=>Math.min(...n.filter(r=>rt(e[r])).map(r=>oe(t,e[r]))),$a=(e,t,n,r,s=()=>!0)=>{const o=e[t];if(!rt(o)||zn(e,o,n)>=r+xt&&s(o))return o;const[i,c,l]=ie(o),d=e.mode==="dark"?1:-1;for(let u=.25;u<=100;u+=.25){const f=at(i+d*u,c,l);if(zn(e,f,n)>=r+xt&&s(f))return f}return o},Wc=(e,t)=>{const n=t.filter(rt).map(Lt),r=n.find(s=>oe(s,e)>=4.5);return r||[...n].sort((s,o)=>oe(o,e)-oe(s,e))[0]},qs=e=>1+.015*(e-50)**2/Math.sqrt(20+(e-50)**2),Kn=e=>{const[,t,n]=ie(e);return Math.hypot(t,n)},Tu=(e,t)=>{const[n,r,s]=ie(e),o=Math.hypot(r,s);return o<1e-6?e:at(n,r/o*t,s/o*t)},qI=e=>{if(!rt(e.rowHover)||!rt(e.rowSelected))return;nT(e);const t=Kn(e.surface),n=Math.max(Oo,Xh*t),r=Math.max(t,Oo),s=Math.max(Po,t),o=Math.min(Math.max(t+Pa,Po),Ma),i=(f,h,g)=>Math.min(Math.max(f,h),g),c=Kn(e.rowHover),l=Kn(e.rowSelected);if(c>=n&&c<=r&&l>=s&&l<=o&&l>=c+Co)return;const d=i(c,n+.1,r-.1),u=i(Math.max(l,d+Co+.2),s+.1,o-.1);e.rowHover=Tu(e.rowHover,d),e.rowSelected=Tu(e.rowSelected,u)},eT=6,tT=e=>{const[,t,n]=ie(e);return Math.atan2(n,t)},nT=e=>{const n=Kn(e.surface)>=an?e.surface:Kn(e.accent)>=Jh?e.accent:e.surface,r=tT(n);for(const s of["rowHover","rowSelected"]){const[o,i,c]=ie(e[s]),l=Math.hypot(i,c);l<an||Math.abs(((Math.atan2(c,i)-r)*180/Math.PI+540)%360-180)<=eT||(e[s]=at(o,l*Math.cos(r),l*Math.sin(r)))}},rT=e=>{const t=e.mode==="dark"?1:-1,n=(r,s,o,i,c)=>{const l=e[r];if(!rt(l))return;const d=g=>zn(e,g,s)>=o+xt&&(!i||pe(g,e[i])>=c+xt)&&(r!=="ink"||oe(g,e.canvas)>=Hc+xt);if(d(l))return;const[u,f,h]=ie(l);for(let g=.25;g<=100;g+=.25){const y=at(u+t*g,f,h);if(d(y)){e[r]=y;return}}};n("inkDim",on,io("inkDim"),null,0),n("inkMuted",on,io("inkMuted"),"inkDim",qr),n("ink",on,io("ink"),"inkMuted",xo)},io=e=>Yh.find(([t])=>t===e)[1],sT=.15,qh=.12,oT=(e,t,n)=>{if(!rt(e.ink)||!rt(e.canvas))return;const r=Math.abs(n)/100,s=e.mode==="dark"?1:-1;if(n>0){const[l,d,u]=ie(e.ink),f=t*(1+sT*r);if(oe(e.ink,e.canvas)>=f)return;for(let h=.25;h<=100;h+=.25){const g=l+s*h;if(g<0||g>100)break;const y=at(g,d,u);if(e.ink=y,oe(y,e.canvas)>=f)return}return}const o=t*(1-qh*r),i=["ink","inkMuted","inkDim"].filter(l=>rt(e[l])),c=l=>i.every(d=>zn(e,l[d],on)>=io(d)+xt)&&oe(l.ink,e.canvas)>=Hc&&(!l.inkMuted||pe(l.ink,l.inkMuted)>=xo+xt)&&(!l.inkMuted||!l.inkDim||pe(l.inkMuted,l.inkDim)>=qr+xt);for(const l of[i,i.slice(0,2),i.slice(0,1)]){const d=Object.fromEntries(l.map(u=>[u,ie(e[u])]));for(let u=.25;u<=60;u+=.25){if(oe(e.ink,e.canvas)<=o)return;const f={...e};for(const h of l){const[g,y,b]=d[h];f[h]=at(g-s*u,y,b)}if(!c(f))break;for(const h of l)e[h]=f[h]}}},eo=(e,t,n,r,s=()=>!0)=>{const o=e[t];if(!rt(o)||!n.split(",").every(f=>rt(e[f])))return;const i=f=>n.split(",").every(h=>pe(f,e[h])>=r+xt)&&s(f);if(i(o))return;const[c,l,d]=ie(o),u=e.mode==="dark"?1:-1;for(const f of[u,-u])for(let h=.25;h<=40;h+=.25){const g=at(c+f*h,l,d);if(i(g)){e[t]=g;return}}},em=(e,t,{spread:n=1,narrow:r=!1,ease:s=XI,travel:o=1}={})=>{if(t===0)return e;const i=t>0?"high":"soft",c=Math.abs(t)/100,l={...e},d=K=>ie(Lt(e[K])),u=d("canvas")[0],f=ZI[e.mode][i],h=YI.filter(K=>rt(e[K])),g=i==="high"==(e.mode==="light")?1:-1;let y=Math.max(0,(f-u)*g)*g*c*o,b=u+y;const _=i==="soft"?1-.4*c:1,p=qs(b)/qs(u),R=(i==="soft"?p:Math.max(1,p))*n,k=Object.fromEntries(h.map(K=>[K,b+(d(K)[0]-u)*R])),O=e.mode==="dark"?1:-1,L=(K,[,he],re)=>{const Pe=(d(K)[0]-u)*re,De=(k[K]-b)*re,Ge=Math.max(Pe,he-.15);De>Ge&&(k[K]=b+re*Ge)};L("surface",bn.canvasSurface,O),L("sunken",bn.canvasSunken,-O);{const K=(d("elevated")[0]-d("surface")[0])*O,he=(k.elevated-k.surface)*O,re=Math.max(K,bn.surfaceElevated[1]-.15);he>re&&(k.elevated=k.surface+O*re)}const P=d("surface")[0],T=e.mode==="dark"?1:-1,m=(d("rowSelected")[0]-P)*T,w=(d("rowHover")[0]-P)*T,S=m>0?Math.min(R,Qh/m):R,x=i==="soft"?S:Math.max(1,S);if(k.rowSelected=k.surface+T*m*x,k.rowHover=k.surface+T*w*x,e.mode==="light"&&i==="high"){const K=u+y,he=Object.keys(k).filter(Pe=>d(Pe)[0]>u),re=Math.max(0,...he.map(Pe=>d(Pe)[0]-u));if(re>0){const Pe=_e=>{const Se=Math.min(1,(100-Ru-_e)/re),dt={canvas:at(_e,...d("canvas").slice(1))};for(const mt of he)dt[mt]=at(_e+(d(mt)[0]-u)*Se,...d(mt).slice(1));return dt},De=[["canvas","surface",ot],["surface","elevated",ot],["canvas","elevated",Iu],["canvas","messageSurface",Iu]].filter(([_e,Se])=>(_e==="canvas"||he.includes(_e))&&he.includes(Se)),Ge=[["canvas","surface",bn.canvasSurface[0]],["surface","elevated",bn.surfaceElevated[0]],["canvas","messageSurface",Oa]].filter(([_e,Se])=>(_e==="canvas"||he.includes(_e))&&he.includes(Se)),qe=(_e,Se,dt)=>dt+.02,me=_e=>De.every(([Se,dt,mt])=>pe(_e[Se],_e[dt])>=qe(Se,dt,mt))&&Ge.every(([Se,dt,mt])=>ie(_e[dt])[0]-ie(_e[Se])[0]>=mt+.15);let Ie=K;for(;Ie>u&&!me(Pe(Ie));)Ie=Math.max(u,Ie-.25);const Et=Ie<=u?1:Math.min(1,(100-Ru-Ie)/re),Ne=Math.max(1,qs(Ie)/qs(u))*n,Ct={rowHover:k.rowHover-k.surface,rowSelected:k.rowSelected-k.surface};for(const _e of Object.keys(k))k[_e]=he.includes(_e)?Ie+(d(_e)[0]-u)*Et:Ie+(k[_e]-K)*(Ne/R);for(const _e of["rowHover","rowSelected"])_e in k&&Number.isFinite(Ct[_e])&&(k[_e]=k.surface+Ct[_e]);b=Ie,y=Ie-u}}if(i==="soft"&&r){const K=me=>e.mode==="dark"?me>b:me<b,he=me=>me>8?((me+16)/116)**3:Math.max(0,me)/903.3,re=(me,Ie)=>{const[Et,Ne]=[he(me),he(Ie)];return(Math.max(Et,Ne)+.05)/(Math.min(Et,Ne)+.05)},Pe=on.filter(me=>me in k&&K(k[me])),Ge=Math.max(1,...on.filter(me=>me in k&&(e.mode==="dark"?d(me)[0]>u:d(me)[0]<u)).map(me=>re(u,d(me)[0])))*(1-s*c),qe=me=>Math.max(1,...Pe.map(Ie=>re(b,b+(k[Ie]-b)*me)));if(Pe.length>0&&qe(1)>Ge){let me=1;for(;me>.3&&qe(me)>Ge;)me-=.01;for(const Ie of Object.keys(k))K(k[Ie])&&(k[Ie]=b+(k[Ie]-b)*me)}}const N=Math.min(...Object.values(k)),E=Math.max(...Object.values(k)),z=N<.5?.5-N:E>100?100-E:0,F=Kn(Lt(e.surface)),X=F>=an?Math.max(_,Math.min(1,(an+.4)/F)):_;for(const K of h){const[,he,re]=d(K),Pe=QI.has(K)?1:K==="surface"?X:_;l[K]=at(k[K]+z,he*Pe,re*Pe)}qI(l),y=b+z-u;for(const K of Object.keys(Ui))rt(e[K])&&(l[K]=Lt(e[K]));rT(l),oT(l,oe(Lt(e.ink),Lt(e.canvas)),t);const $e=ie(l.accent)[0];l.accent=$a(l,"accent",...Ui.accent);const We=ie(l.accent)[0]-$e;for(const K of["accentHover","accentActive"]){if(!rt(l[K])||We===0)continue;const[he,re,Pe]=ie(l[K]);l[K]=at(he+We,re,Pe)}for(const[K,[he,re]]of Object.entries(Ui))K.startsWith("ink")||K==="accent"||(l[K]=$a(l,K,he,re));return eo(l,"accentHover","accent",ot,K=>zn(l,K,It)>=4.5+xt),eo(l,"accentActive","accent,accentHover",ot,K=>zn(l,K,It)>=4.5+xt),eo(l,"accentAlt","accent",nn,K=>zn(l,K,It)>=4.5+xt&&Kn(K)>=Ss),eo(l,"chartBarHover","accent",ja,K=>oe(K,l.surface)>=oe(l.accent,l.surface)),l.onAccent=Wc(l.accent,[e.onAccent,l.ink,l.canvas,"#FFFFFF","#000000"]),l},Mo=(e,t="custom")=>{const n=zI({composed:!0});return KI(n,{id:t,palette:e}),n.log},ao=(e,t)=>{const n=Wc(e.accent,[t.onAccent,e.ink,e.canvas,"#FFFFFF","#000000"]);return n===e.onAccent?e:{...e,onAccent:n}},xu=new Set(["mode","overlayShadow","scrim","onAccent"]),iT=["rowHover","rowSelected","accentWash","surface"],aT=/\b[a-z][A-Za-z]+\b/g,cT=(e,t)=>{const n=new Map;for(const[s,o]of Object.entries(e))!xu.has(s)&&rt(o)&&n.set(o.toUpperCase(),s);const r=new Set;for(const s of t){if(s.includes("ROW_STATE_MEASURED_SHORTFALL"))for(const o of iT)r.add(o);for(const[o]of s.matchAll(aT))o in e&&!xu.has(o)&&rt(e[o])&&r.add(o);for(const[o]of s.matchAll(lT)){const i=n.get(o.toUpperCase());i&&r.add(i)}}return[...r]},lT=/#[0-9A-Fa-f]{6}\b/g,dT=/(?:= |ΔE00 )(\d+(?:\.\d+)?)(?::1)?[\s\S]*?need (\d+(?:\.\d+)?)/,uT=e=>{let t=0;for(const n of e){const r=n.match(dT);if(!r){t+=1;continue}const s=Number(r[1]),o=Number(r[2]);t+=o>0?Math.min(1,Math.max(0,(o-s)/o)):1}return t},Cu=e=>e.length*1e3+uT(e),fT=[.5,-.5,1,-1,2,-2,4,-4,7,-7,11,-11],pT=[.7,.85,1.15,1.35],hT=60,tm=(e,t,n=e,{pinned:r=[],maxEvaluations:s=Number.POSITIVE_INFINITY,lightnessOnly:o=!1}={})=>{const i=new Set(r),c=h=>i.has("onAccent")?h:ao(h,n);let l=0,d=c(e),u=Mo(d,t),f=Cu(u);for(let h=0;h<hT&&u.length>0;h++){let g=null;for(const y of cT(d,u)){if(i.has(y))continue;const[b,_,p]=ie(d[y]),R=[...fT.map(k=>at(b+k,_,p)),...o?[]:pT.map(k=>at(b,_*k,p*k))];for(const k of R){if(k===d[y])continue;if(++l>s)return{palette:d,findings:u};const O=c({...d,[y]:k}),L=Mo(O,t),P=Cu(L);P<(g?g.score:f)-1e-9&&(g={next:O,findings:L,score:P})}}if(!g)break;d=g.next,u=g.findings,f=g.score}return{palette:d,findings:u}},mT=5,gT=[1,1.15],_T=[{spread:1,narrow:!0},{spread:1,narrow:!0,ease:0},...gT.map(e=>({spread:e})),{spread:1,travel:.5,soft:!0},{spread:1,travel:0,soft:!0}],Ou=.015,bT=(e,t,n)=>{const r=oe(Lt(e.ink),Lt(e.canvas)),s=oe(t.ink,t.canvas),o=ie(Lt(e.canvas))[0],i=ie(t.canvas)[0],c=n>0==(e.mode==="light")?1:-1;return n>0?s>=r-Ou&&(i-o)*c>=-.05:s<=r+Ou},vT=(e,t,n,r)=>{const o=oe(Lt(t.ink),Lt(t.canvas))*(1-qh*(Math.abs(n)/100)),i=e.mode==="dark"?-1:1,c=["ink","inkMuted","inkDim"].filter(d=>rt(e[d]));let l=e;for(const d of[c,c.slice(0,2),c.slice(0,1)]){const u=Object.fromEntries(d.map(f=>[f,ie(l[f])]));for(let f=.25;f<=20;f+=.25){if(oe(l.ink,l.canvas)<=o)return l;const h={...l};for(const g of d){const[y,b,_]=u[g];h[g]=at(y+i*f,b,_)}if(Mo(ao(h,t),r).length>0)break;l=ao(h,t)}}for(let d=0;d<6&&oe(l.ink,l.canvas)>o;d++){let u=null;for(const f of[0,1,2])for(const h of[1,-1]){const y=Number.parseInt(l.ink.slice(1+2*f,3+2*f),16)+h;if(y<0||y>255)continue;const b=`#${l.ink.slice(1,1+2*f)}${y.toString(16).padStart(2,"0").toUpperCase()}${l.ink.slice(3+2*f)}`,_=oe(b,l.canvas);if(_>=oe(l.ink,l.canvas))continue;const p=ao({...l,ink:b},t);Mo(p,r).length>0||(!u||_>u.r)&&(u={r:_,next:p})}if(!u)break;l=u.next}return l},yT=(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 s=t;s!==0;s-=r*Math.min(mT,Math.abs(s)))for(const o of _T){if((o.narrow||o.soft)&&s>0)continue;const i=em(e,s,o),c=tm(i,n,e);if(s<0&&c.findings.length===0&&(c.palette=vT(c.palette,e,s,n)),c.findings.length===0&&bT(e,c.palette,s))return{palette:c.palette,effectiveContrast:s}}return{palette:e,effectiveContrast:0}},Nn=/^#[0-9A-Fa-f]{6}$/,wT=/^#[0-9A-Fa-f]{3}$/,ht=e=>{if(typeof e!="string")return null;let t=e.trim();return t.startsWith("#")||(t=`#${t}`),wT.test(t)&&(t=`#${[...t.slice(1)].map(n=>n+n).join("")}`),Nn.test(t)?t.toUpperCase():null},kT=["accentHover","accentActive","accentWash","chartBarHover"],Dt=e=>{const[t,n,r]=ie(e);return[t,Math.hypot(n,r),Math.atan2(r,n)]},ST=e=>Dt(e)[1],jo=(e,t,n)=>at(e,Math.max(0,t)*Math.cos(n),Math.max(0,t)*Math.sin(n)),ET=4,AT=(e,t,n)=>{const[r,s,o]=Dt(e),[i,c,l]=Dt(t),[d,u,f]=Dt(n);return s<ET?jo(d+(i-r),c,f):jo(d+(i-r),u*(c/s),f+(l-o))},RT=(e,t,n)=>{if(!e||e.kind==="theme")return null;if(e.kind==="theme-alt")return ht(t.accentAlt);if(e.kind==="palette"){const r=typeof n=="function"?n(e.id):null;return ht(r)}return e.kind==="custom"?ht(e.hex):null},IT=(e,t,{authored:n=e,id:r="custom",paletteAccent:s,preserveSecondary:o=!1}={})=>{const i=RT(t,n,s);if(!i)return{palette:e,applied:!1,adjusted:0,requested:i};const c={...e,accent:i};for(const h of kT)!Nn.test(n[h]??"")||!Nn.test(n.accent??"")||(c[h]=AT(n.accent,n[h],i));if(Nn.test(e.accentWash??"")&&Nn.test(n.accentWash??"")){const h=Dt(e.accentWash)[0],[,g,y]=Dt(c.accentWash);c.accentWash=jo(h,Math.max(g,Dt(n.accentWash)[1]),y)}if(ST(c.surface)<an){const h=Dt(c.accent)[2];for(const g of["rowHover","rowSelected"]){if(!Nn.test(c[g]??""))continue;const[y,b]=Dt(c[g]);b>=an&&(c[g]=jo(y,b,h))}}!o&&t.kind==="theme-alt"?Dt(n.accent)[1]>=Ss&&(c.accentAlt=ht(n.accent)):!o&&pe(c.accent,c.accentAlt)<nn&&Dt(n.accent)[1]>=Ss&&(c.accentAlt=ht(n.accent));const l=ie(c.accent)[0];c.accent=$a(c,"accent",TT,4.5,h=>pe(h,c.ink)>=3);const d=ie(c.accent)[0]-l;if(d!==0)for(const h of["accentHover","accentActive","chartBarHover"]){if(!Nn.test(c[h]??""))continue;const[g,y,b]=ie(c[h]);c[h]=at(g+d,y,b)}c.onAccent=Wc(c.accent,[n.onAccent,c.ink,c.canvas,"#FFFFFF","#000000"]);const u=tm(c,r,n);return o&&Zh.filter(h=>h.storage==="overrides").flatMap(h=>[h.role,...h.variants]).some(h=>u.palette[h]!==e[h])||u.findings.length>0||pe(u.palette.accent,u.palette.ink)<3?{palette:e,applied:!1,adjusted:0,requested:i}:{palette:u.palette,applied:!0,adjusted:pe(i,u.palette.accent),requested:i}},TT=["canvas","surface","elevated","sunken","accentWash","messageSurface","warningWash"],Pu=["dark","light"],xT=12,oM=50,iM="custom-themes-storage",CT=60,nm=Object.freeze({dark:0,light:0}),vn=Object.freeze({kind:"theme"}),rm=Object.freeze({dark:vn,light:vn}),Da=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(-100,Math.min(100,Math.round(e))),sm=e=>!e||typeof e!="object"?nm:{dark:Da(e.dark),light:Da(e.light)},Na=(e,t=()=>!0)=>{if(!e||typeof e!="object")return vn;switch(e.kind){case"theme":return vn;case"theme-alt":return{kind:"theme-alt"};case"palette":return typeof e.id=="string"&&t(e.id)?{kind:"palette",id:e.id}:vn;case"custom":{const n=ht(e.hex);return n?{kind:"custom",hex:n}:vn}default:return vn}},om=(e,t)=>!e||typeof e!="object"?rm:{dark:Na(e.dark,t),light:Na(e.light,t)},Ar=e=>{if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=ht(n);if(r&&!t.includes(r)&&t.push(r),t.length===xT)break}return t},OT=(e,t)=>{const n=ht(t);return Ar(n?[n,...Array.isArray(e)?e:[]]:e)},PT=/^custom-[a-z0-9]{1,30}$/,Gc=e=>typeof e=="string"&&PT.test(e)?e:null,aM=(e,{isThemeName:t,isRole:n})=>{if(!e||typeof e!="object"||e.format!=="local-operator-theme"||e.version!==1)return null;const r=Gc(e.id);if(!r||!Wa(r)||typeof e.base!="string"||!t(e.base))return null;const s=typeof e.name=="string"&&e.name.trim()?e.name.trim().slice(0,CT):null;if(!s)return null;const o=i=>{const c={};if(!i||typeof i!="object")return c;for(const[l,d]of Object.entries(i)){if(!n(l))continue;const u=ht(d);u&&Ga(u)&&(c[l]=u)}return c};return{format:"local-operator-theme",version:1,id:r,name:s,base:e.base,seeds:o(e.seeds),overrides:o(e.overrides),updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:0}},Vt=Object.freeze(Object.entries(VI).sort(([,e],[,t])=>e-t).map(([e,t])=>Object.freeze({name:e,value:t}))),Mu=5,MT=8,jT=e=>Math.max(-100,Math.min(100,e)),cM=(e,{snap:t=!0}={})=>{if(!Number.isFinite(e))return 0;const n=jT(Math.round(e/Mu)*Mu);if(!t)return n;for(const{value:r}of Vt)if(Math.abs(e-r)<=MT)return r;return n},$T=e=>Vt.find(t=>t.value===e)?.name??null,lM=e=>{let t=Vt[2];for(const n of Vt){const r=Math.abs(n.value-e),s=Math.abs(t.value-e);(r<s||r===s&&Math.abs(n.value)<Math.abs(t.value))&&(t=n)}return t.name},dM=e=>{if($T(e))return null;for(let t=1;t<Vt.length;t++)if(e<Vt[t].value)return[Vt[t-1].name,Vt[t].name];return null},uM=(e,t)=>{const r=(t>0?Vt:[...Vt].reverse()).find(s=>t>0?s.value>e:s.value<e);return r?r.value:e},DT=[[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"]],zc=8,Kc=e=>{const[t,n,r]=ie(e),s=Math.atan2(r,n)*180/Math.PI;return{L:t,C:Math.hypot(n,r),h:s<0?s+360:s}},fM=e=>{const{C:t,h:n}=Kc(e);if(t<zc)return"neutral";for(const[r,s]of DT)if(n<r)return s;return"pink"},pM=(e,t,n)=>{const r=e.find(l=>l.id===n)?.palette.accent,s=e.filter(l=>l.palette.mode===t&&l.id!==n&&typeof l.palette.accent=="string"&&l.palette.accent.toUpperCase()!==r?.toUpperCase()),o=new Map;let i=null;for(const l of s){const{C:d,h:u}=Kc(l.palette.accent);if(d<zc){(!i||d<i.C)&&(i={...l,C:d});continue}const f=Math.floor(u/36),h=Math.abs(u-(f*36+18)),g=o.get(f);(!g||h<g.off||h===g.off&&l.id<g.id)&&o.set(f,{...l,off:h})}const c=[...o.entries()].sort(([l],[d])=>l-d).map(([,l])=>({id:l.id,hex:l.palette.accent.toUpperCase()}));return i&&c.push({id:i.id,hex:i.palette.accent.toUpperCase()}),c},hM=(e,t)=>{const n=new Set,r=[];for(const o of e){if(o.palette.mode!==t)continue;const i=String(o.palette.accent).toUpperCase();n.has(i)||(n.add(i),r.push({id:o.id,hex:i}))}const s=o=>{const{C:i,h:c}=Kc(o);return i<zc?1e3:c};return r.sort((o,i)=>s(o.hex)-s(i.hex))},NT=40,co=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return{};const n={};for(const r of Array.isArray(t)?t:[]){const s=e[r];if(typeof s!="string")continue;const o=[...s].map(i=>{const c=i.codePointAt(0)??0;return c<32||c===127?" ":i}).join("").replace(/\s+/g," ").trim().slice(0,NT);o&&(n[r]=o)}return n},mM=Object.freeze({strip:"lo-preview",chip:e=>`lo-preview-${e}`}),gM=(e,t,n=null)=>{const r=[];for(const{id:s,contrast:o}of t){if(!Wa(s))continue;const i=o===0?e:em(e,o),c=n?{...i,...n}:i;Object.entries(c).every(([d,u])=>d==="mode"||Ga(u))&&r.push(Hu(s,c))}return r.join(`
65
+ `)},_M=e=>{const[t,n,r]=ie(e),s=Math.atan2(r,n)*180/Math.PI;return{l:t,c:Math.hypot(n,r),h:s<0?s+360:s}},bM=({l:e,c:t,h:n})=>{const r=Math.max(0,Math.min(100,e)),s=n*Math.PI/180;for(let o=Math.max(0,t);o>=0;o-=1){const i=To([r,o*Math.cos(s),o*Math.sin(s)]);if(i)return i}return To([r,0,0])??"#000000"},vM=e=>{const t=oe("#FFFFFF",e),n=oe("#000000",e);return t>=n?{ink:"#FFFFFF",ratio:t}:{ink:"#000000",ratio:n}},yM=Object.freeze(["accent","accentHover","accentActive","accentWash","onAccent","chartBarHover","accentAlt","accentAltWash"]),ju=64,La=["canvas","run","browser","console","code"],LT={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function im(e){return typeof e=="string"&&La.includes(e)}function Vc(e){return e.startsWith("draft:")}function Cs(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function Zc(e){return e.length>ju?e.slice(e.length-ju):e}function am(e,t,n){return Zc([...e.filter(([r])=>r!==t),[t,n]])}function UT(e,t,n){return Cs(e,t)!==n?e:e.filter(([r])=>r!==t)}function FT(e,t){return Cs(e,t)===void 0?e:e.filter(([n])=>n!==t)}function BT(e,t,n){const r=Cs(e,t);return r===void 0?e:Zc([...e.filter(([s])=>s!==t&&s!==n),[n,r]])}const $u=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function Du(e,t,n){if(n||typeof t!="string")return $u;const r=Cs(e,t);return r===void 0?$u:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function HT(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,s]=n;typeof r!="string"||r===""||Vc(r)||im(s)&&(t.delete(r),t.set(r,s))}return Zc([...t.entries()])}function wM(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 Nu(e){return LT[e]}const WT={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},Os=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,Xo=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,GT=e=>{const t=Os(e);return t===null||t==="ask"?null:WT[t]},_n=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Mn=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:am(e.rightSlotMemory,n,t)}},Br=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=UT(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},zT=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=FT(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},KT=Object.freeze({mounted:!1,session:!1}),cm=Object.freeze([]);function kM(e,t){const n=Os(t);if(n===null||!Xo(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=Hr($c,t.rightSlotWidth);break;case"run":r=Hr(Uu,t.rightSlotWidth);break;case"browser":r=Hr(XT,t.rightSlotWidth);break;case"console":r=Hr(JT,t.rightSlotWidth);break;case"code":r=Hr(Uu,t.rightSlotWidth);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,Dc(e)):Math.min(r,Math.max(0,e-Mc))}function Hr(e,t){return Math.min($h,Math.max(e,t||VT))}function SM(e){const t=Os(e);return t!==null&&Xo(t,e)}function EM(e){const t=Os(e);return t!==null&&Xo(t,e)?t:null}function AM(e){const t=Os(e);return(t==="canvas"||t==="ask")&&Xo(t,e)}const VT=640,Lu=Vo,ZT=20,YT=4,QT=20,Uu=320,XT=480,JT=480,qT=5e3,RM=(e,t)=>e.some(n=>n.surface===t),IM=(e,t=Date.now())=>e.some(n=>t-n.at<qT),ex=[],tx=5,nx=["chatMeasureWidth"],TM=Rs()(Uo((e,t)=>({finderFiles:Hh,setFinderFiles:n=>e({finderFiles:Uc({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:zh,agentAvatarSize:Lh,themeName:_m,contrast:nm,accent:rm,customAccents:[],customAccentNames:{},customThemeId:null,setContrast:(n,r)=>e(s=>({contrast:{...s.contrast,[n]:Da(r)}})),setAccent:(n,r)=>e(s=>({accent:{...s.accent,[n]:Na(r,Ba)}})),addCustomAccent:(n,r)=>e(s=>{const o=OT(s.customAccents,n),i=ht(n),c=co(s.customAccentNames,o);return!r||!i?{customAccents:o,customAccentNames:c}:{customAccents:o,customAccentNames:c,accent:{...s.accent,[r]:{kind:"custom",hex:i}}}}),removeCustomAccent:n=>e(r=>{const s=ht(n),o={...r.accent};for(const c of Pu){const l=o[c];l.kind==="custom"&&l.hex===s&&(o[c]=vn)}const i={...r.customAccentNames};return s&&delete i[s],{customAccents:r.customAccents.filter(c=>c!==s),customAccentNames:i,accent:o}}),renameCustomAccent:(n,r)=>e(s=>{const o=ht(n);return!o||!s.customAccents.includes(o)?{}:{customAccentNames:co({...s.customAccentNames,[o]:r},s.customAccents)}}),replaceCustomAccent:(n,r)=>e(s=>{const o=ht(n),i=ht(r);if(!o||!i||o===i)return{};if(s.customAccents.indexOf(o)<0)return{};const l=s.customAccents.filter(h=>h!==i);l.splice(l.indexOf(o),1,i);const d=Ar(l),u={...s.customAccentNames};u[o]!==void 0&&u[i]===void 0&&(u[i]=u[o]),delete u[o];const f={...s.accent};for(const h of Pu){const g=f[h];g.kind==="custom"&&g.hex===o&&(f[h]={kind:"custom",hex:i})}return{customAccents:d,customAccentNames:co(u,d),accent:f}}),rightSlotWidth:0,chatSidebarWidth:Lu,chatSidebarRegions:eI,chatSidebarView:cr,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:cm,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:KT,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:ex,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?{..._n("isCanvasOpen"),...Mn(r,"canvas")}:{isCanvasOpen:!1,...Br(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{..._n("isRunPanelOpen"),...Mn(r,"run")}:{isRunPanelOpen:!1,...Br(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{..._n("isBrowserPaneOpen"),...Mn(r,"browser")}:{isBrowserPaneOpen:!1,...Br(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{..._n("isConsolePaneOpen"),...Mn(r,"console")}:{isConsolePaneOpen:!1,...Br(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{..._n("isCodeReviewPaneOpen"),...Mn(r,"code")}:{isCodeReviewPaneOpen:!1,...Br(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({..._n("isCodeReviewPaneOpen"),...Mn(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,s)=>{e(o=>{const i=typeof o.rightSlotKey=="string";if(n)return{..._n("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:i?null:GT(o),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return i?s?.dismissSlot?{...c,...zT(o)}:{...c,...Du(o.rightSlotMemory,o.rightSlotKey,!1)}:o.rightSlotKey===null?s?.dismissSlot?{...c,rightSlotLegacySeed:null}:c:s?.dismissSlot?{...c,rightSlotLegacySeed:null}:{...c,...o.askDrawerEvictedPane===null?null:{[o.askDrawerEvictedPane]:!0}}})},requestAskOpen:(n,r="menu")=>{e({askOpenIntent:{scope:n,via:r}})},clearAskOpenIntent:n=>{e(r=>r.askOpenIntent?.scope===n?{askOpenIntent:null}:{})},setConsoleActiveSurface:n=>{e({consoleActiveSurface:n})},requestConsoleOpen:n=>{e({consoleOpenIntent:n})},clearConsoleOpenIntent:n=>{e(r=>r.consoleOpenIntent===n?{consoleOpenIntent:null}:{})},setConsoleLiveSurface:(n,r)=>{e(s=>{if(n===null||r<=0)return s.consoleLiveSurface===null?{}:{consoleLiveSurface:null};const o=s.consoleLiveSurface;return o?.sessionId===n&&o.count===r?{}:{consoleLiveSurface:{sessionId:n,count:r}}})},markConsoleUnseen:(n,r)=>{e(s=>s.consoleUnseen.some(o=>o.surface===r)?{}:{consoleUnseen:[...s.consoleUnseen,{sessionId:n,surface:r,at:Date.now()}]})},clearConsoleUnseen:n=>{const r=Array.isArray(n)?n:[n];e(s=>{const o=s.consoleUnseen.filter(i=>!r.includes(i.surface));return o.length===s.consoleUnseen.length?{}:{consoleUnseen:o}})},setRightSlotWidth:n=>{e({rightSlotWidth:n})},restoreDefaultRightSlotWidth:()=>{e({rightSlotWidth:0})},bindRightSlotKey:(n,r)=>{e(s=>{let o=s.rightSlotMemory,i=s.rightSlotLegacySeed;const c=r?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(o=BT(o,c,n)),n===null||(Vc(n)?i=null:i!==null&&Cs(o,n)===void 0&&(o=am(o,n,i),i=null)),{rightSlotKey:n,rightSlotMemory:o,rightSlotLegacySeed:i,...Du(o,n,s.isAskDrawerOpen)}})},setRightSlotRoute:n=>{const r=t().rightSlotRoute;r.mounted===n.mounted&&r.session===n.session||e({rightSlotRoute:{...n}})},setShortcutBinding:(n,r,s)=>{if(r===null){e(i=>{const c={...i.shortcutBindings};return delete c[n],{shortcutBindings:c}});return}const o=Bc(r);o!==null&&hI(o,n,t().shortcutBindings,"linux",s)===null&&e(i=>({shortcutBindings:{...i.shortcutBindings,[n]:o}}))},clearShortcutBinding:n=>{e(r=>({shortcutBindings:{...r.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(r=>({..._n("isRunPanelOpen"),...Mn(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(Pc,Math.max(Oc,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:Lu})},rememberMention:(n,r)=>{e(s=>{const o=s.mentionRecents,i=o?.cwd===n?o.paths:[],c=[r,...i.filter(l=>l!==r)].slice(0,ZT);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(s=>({profileRecents:{...s.profileRecents,[n]:rx(s.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const s=ix(r.conversationRecents),o=sx(s,n);return o.length===s.length&&o.every((i,c)=>i===s[c])?r:{conversationRecents:o}})}}),{name:"ui-preferences-storage",version:tx,migrate:dx,partialize:ax,merge:lx}));function rx(e,t){return[t,...e.filter(n=>n!==t)].slice(0,YT)}function sx(e,t){return[t,...e.filter(n=>n!==t)].slice(0,QT)}const ox=[];function ix(e){return Array.isArray(e)?e:ox}function ax(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:r,consoleLiveSurface:s,askOpenIntent:o,isAskDrawerOpen:i,askDrawerScope:c,askDrawerEvictedPane:l,rightSlotRoute:d,isCanvasOpen:u,isRunPanelOpen:f,isBrowserPaneOpen:h,isConsolePaneOpen:g,isCodeReviewPaneOpen:y,rightSlotKey:b,..._}=e;return{..._,rightSlotMemory:cx(e.rightSlotMemory)}}function cx(e){return(e??cm).filter(([t])=>!Vc(t))}function lx(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:s,isBrowserPaneOpen:o,isConsolePaneOpen:i,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:Uc(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:HT(n.rightSlotMemory),rightSlotLegacySeed:im(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:mI(n.shortcutBindings),contrast:sm(n.contrast),accent:om(n.accent,Ba),customAccents:Ar(n.customAccents),customAccentNames:co(n.customAccentNames,Ar(n.customAccents)),customThemeId:Gc(n.customThemeId)}}function dx(e,t){const n={...e??{}};if(t<1&&ux(n),t<2)for(const r of nx)delete n[r];if(t<3){let r=null;for(const s of La)if(n[Nu(s)]===!0){r=s;break}r!==null&&(n.rightSlotLegacySeed=r);for(const s of La)delete n[Nu(s)]}return t<4&&(n.finderFiles=Uc(n.finderFiles)),t<5&&(n.contrast=sm(n.contrast),n.accent=om(n.accent,Ba),n.customAccents=Ar(n.customAccents),n.customThemeId=Gc(n.customThemeId)),n}function ux(e){const t=[["canvasWidth",800],["runPanelWidth",420],["browserPanelWidth",640],["consolePanelWidth",796]];let n=0;for(const[r,s]of t){const o=e[r];if(typeof o=="number"&&o>0&&o!==s){n=o;break}}for(const[r]of t)delete e[r];e.rightSlotWidth=n}const Ua=e=>e.replace(/\\/g,"/"),xM=()=>window.location.hash?Ua(window.location.hash.substring(1)):Ua(window.location.pathname),CM=(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,"/")},OM=(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 s=n[0]==="~"||n[0]==="",o=s?n.slice(0,2):n.slice(0,1),i=n.slice(o.length),c=y=>{const b=t-y.length-(y?3:2);let _=[];for(let p=i.length-1;p>=0;p-=1){const R=[i[p],..._];if(R.join("/").length>b)break;_=R}return _},l=(y,b)=>y?`${y}/…/${b.join("/")}`:`…/${b.join("/")}`,d=o.join("/"),u=c(d);if(u.length>0)return u.length===i.length?e:l(d,u);const f=s?n[0]:"",h=c(f);if(h.length>0)return l(f,h);const g=t-(f?`${f}/…/`.length:2);return g>0?l(f,[r.slice(-g)]):"…"},PM=(e,t)=>Ua(e).includes(t),Fa=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)},fx=(e,{contrast:t=0,accent:n={kind:"theme"},id:r,paletteAccent:s,preserveSecondary:o=!1}={})=>{const i=!n||n.kind==="theme";if(t===0&&i)return{identity:!0,palette:e,id:r,effectiveContrast:0,requestedContrast:0,accentApplied:!0,accentAdjusted:0};const c=yT(e,t,{id:r});let l=c.palette,d=!0,u=0;if(!i){const f=IT(l,n,{authored:e,id:r,paletteAccent:s,preserveSecondary:o});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-${Fa(l)}`,effectiveContrast:c.effectiveContrast,requestedContrast:t,accentApplied:d,accentAdjusted:u}},Fu="lo-composed-theme",px=4,jn=new Map,hx=(e,t)=>{const n=jn.get(e);if(n)return jn.delete(e),jn.set(e,n),n;const r=bm(t);if(jn.set(e,r),jn.size>px){const s=jn.keys().next().value;s!==void 0&&jn.delete(s)}return r},mx=e=>Ha(e)?.palette.accent,gx=16,or=new Map,_x=(e,t,n)=>{const r=Bu(e.themeName),s=Ha(r.id);if(!s)throw new Error(`no palette for theme ${r.id}`);const o=t??s.palette,i=o.mode,c=n??r.id,l=e.contrast[i]??0,d=e.accent[i],u=JSON.stringify([r.id,n??null,t?Fa(t):null,l,d??null]);let f=or.get(u);if(f?or.delete(u):f=fx(o,{contrast:l,accent:d,id:c,preserveSecondary:t!==void 0,paletteAccent:mx}),or.set(u,f),or.size>gx){const g=or.keys().next().value;g!==void 0&&or.delete(g)}if(f.identity&&!n)return{...f,id:r.id,muiTheme:r.theme};const h=`lo-${Fa(f.palette)}`;return{...f,id:h,identity:!1,muiTheme:hx(h,f.palette)}},bx=(e,t)=>Wa(e)&&Object.entries(t).every(([n,r])=>n==="mode"||Ga(r))&&(t.mode==="dark"||t.mode==="light"),MM=(e,t=document,n,r,s=o=>_x(o,n,r))=>{let o=s(e);if(!o.identity&&!bx(o.id,o.palette)){console.error(`[theme] refused to publish composed theme ${JSON.stringify(o.id).slice(0,60)}: an id or value is outside the CSS grammar; showing the built-in theme`);const l=Bu(e.themeName),d=Ha(l.id);if(!d)throw new Error(`no palette for theme ${l.id}`);o={identity:!0,palette:d.palette,id:l.id,effectiveContrast:0,requestedContrast:o.requestedContrast,accentApplied:!1,accentAdjusted:0,muiTheme:l.theme}}const i=t.documentElement,c=t.getElementById(Fu);if(o.identity)c?.remove();else{const l=c??t.createElement("style");l.id=Fu,l.textContent=Hu(o.id,o.palette),c||t.head.appendChild(l)}return AA(t,o.identity?null:o.palette),i.dataset.theme=o.id,i.classList.toggle("dark",o.palette.mode==="dark"),o},jM=e=>({themeName:e.themeName,customThemeId:e.customThemeId??null,contrast:e.contrast,accent:e.accent}),$M=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{oP as $,zE as A,MM as B,jM as C,eM as D,TM as E,it as F,sI as G,$M as H,_x as I,a as J,Tf as K,Oe as L,jE as M,$E as N,xO as O,Fl as P,ch as Q,EO as R,pt as S,RO as T,uh as U,lh as V,AO as W,wO as X,TO as Y,SO as Z,IO as _,fC as a,fx as a$,xM as a0,_h as a1,GO as a2,zO as a3,Ko as a4,hP as a5,ix as a6,yv as a7,pO as a8,Rs as a9,Jp as aA,_P as aB,SR as aC,gP as aD,ER as aE,AR as aF,ht as aG,xT as aH,fM as aI,vM as aJ,NT as aK,$T as aL,lM as aM,Vt as aN,mM as aO,Mu as aP,cM as aQ,dM as aR,uM as aS,pM as aT,hM as aU,gM as aV,yM as aW,A0 as aX,rA as aY,uC as aZ,Zh as a_,rO as aa,Lx as ab,Tt as ac,ea as ad,Uo as ae,q_ as af,dC as ag,rC as ah,lb as ai,db as aj,Kl as ak,Nx as al,Dx as am,Sf as an,Ua as ao,gy as ap,Ox as aq,Vu as ar,ti as as,g_ as at,m_ as au,$1 as av,kE as aw,x1 as ax,O1 as ay,P1 as az,iC as b,Jx as b$,_M as b0,sM as b1,Ca as b2,JP as b3,Es as b4,nt as b5,Gu as b6,Lm as b7,Hm as b8,zm as b9,In as bA,kl as bB,Xa as bC,_b as bD,No as bE,gf as bF,PE as bG,kO as bH,ae as bI,yO as bJ,ar as bK,ya as bL,wa as bM,bO as bN,vO as bO,hO as bP,mO as bQ,gO as bR,rM as bS,IM as bT,qT as bU,RM as bV,Sv as bW,lC as bX,cC as bY,aC as bZ,Ef as b_,Qm as ba,Vm as bb,Zm as bc,pl as bd,Jm as be,hl as bf,Xm as bg,Ym as bh,qO as bi,uA as bj,WO as bk,MO as bl,PM as bm,Cx as bn,xx as bo,Tx as bp,Ix as bq,Mx as br,E_ as bs,$t as bt,Jr as bu,Rf as bv,F_ as bw,EM as bx,nM as by,eO as bz,pC as c,CM as c$,zx as c0,Af as c1,_v as c2,x_ as c3,Sm as c4,C_ as c5,Nc as c6,Zx as c7,Yd as c8,qx as c9,Jd as cA,xP as cB,TP as cC,CP as cD,DR as cE,OP as cF,AP as cG,DP as cH,NP as cI,wP as cJ,OO as cK,Zo as cL,kP as cM,KO as cN,RP as cO,vP as cP,zP as cQ,KP as cR,YP as cS,QP as cT,qR as cU,VP as cV,ks as cW,ZP as cX,XP as cY,jx as cZ,mP as c_,nA as ca,KR as cb,cu as cc,EP as cd,BP as ce,HP as cf,WP as cg,SP as ch,PO as ci,CO as cj,bh as ck,JO as cl,GP as cm,jP as cn,$P as co,vr as cp,cr as cq,yP as cr,Bh as cs,IP as ct,UP as cu,ws as cv,LP as cw,FP as cx,PP as cy,MP as cz,Ze as d,Fc as d$,OM as d0,qP as d1,Rx as d2,gS as d3,mC as d4,SM as d5,Ta as d6,KT as d7,Hr as d8,kM as d9,D1 as dA,lO as dB,dO as dC,mh as dD,QE as dE,Go as dF,FO as dG,BO as dH,Sy as dI,nO as dJ,U1 as dK,pE as dL,WE as dM,hh as dN,BE as dO,Vd as dP,jO as dQ,wR as dR,UO as dS,_O as dT,Bx as dU,Hx as dV,nC as dW,Yo as dX,Qo as dY,Vh as dZ,hI as d_,lP as da,dP as db,cP as dc,$c as dd,Dc as de,Xx as df,Qx as dg,XT as dh,$h as di,JT as dj,Uu as dk,Mc as dl,R1 as dm,I1 as dn,ZO as dp,VO as dq,YO as dr,XO as ds,QO as dt,Lv as du,xs as dv,oC as dw,ef as dx,Rc as dy,tO as dz,hC as e,nv as e$,sO as e0,El as e1,xn as e2,Gn as e3,I_ as e4,tM as e5,Xi as e6,pP as e7,aP as e8,hR as e9,sC as eA,Lo as eB,kt as eC,Nm as eD,eA as eE,AM as eF,fP as eG,jc as eH,uP as eI,jh as eJ,bR as eK,Oc as eL,Wx as eM,Il as eN,Jb as eO,Gx as eP,j_ as eQ,K1 as eR,V1 as eS,Ux as eT,Fx as eU,z1 as eV,qp as eW,fS as eX,Ip as eY,zh as eZ,cp as e_,Dh as ea,Om as eb,rI as ec,Ex as ed,Vc as ee,wM as ef,dl as eg,Sx as eh,kx as ei,Bi as ej,es as ek,$m as el,Km as em,qm as en,pw as eo,pe as ep,eP as eq,Jn as er,Ih as es,nP as et,eR as eu,Eh as ev,tP as ew,sP as ex,iP as ey,tC as ez,wv as f,o1 as f$,Kx as f0,T1 as f1,C1 as f2,L1 as f3,N1 as f4,M1 as f5,fr as f6,Yx as f7,eC as f8,Vx as f9,Ty as fA,E1 as fB,zy as fC,YC as fD,Uw as fE,_1 as fF,wp as fG,v1 as fH,h1 as fI,m1 as fJ,b1 as fK,Dw as fL,vi as fM,g1 as fN,Fw as fO,u1 as fP,n1 as fQ,l1 as fR,w1 as fS,t1 as fT,d1 as fU,p1 as fV,S1 as fW,k1 as fX,f1 as fY,r1 as fZ,s1 as f_,EC as fa,ac as fb,rc as fc,Tn as fd,Yt as fe,Mo as ff,oM as fg,aM as fh,bM as fi,Wc as fj,zI as fk,KI as fl,tm as fm,iM as fn,Gc as fo,qC as fp,e1 as fq,XC as fr,QC as fs,GC as ft,LC as fu,UC as fv,BC as fw,FC as fx,lp as fy,ZC as fz,qa as g,Wv as g$,i1 as g0,a1 as g1,c1 as g2,y1 as g3,O_ as g4,P_ as g5,M_ as g6,ad as g7,TC as g8,KC as g9,Z1 as gA,AS as gB,J1 as gC,Y1 as gD,X1 as gE,q1 as gF,xC as gG,OC as gH,Ja as gI,j1 as gJ,oO as gK,iO as gL,Ei as gM,cO as gN,aO as gO,uO as gP,wE as gQ,fO as gR,B1 as gS,Ff as gT,ms as gU,RC as gV,ny as gW,Bf as gX,sc as gY,Nf as gZ,Hv as g_,V0 as ga,ap as gb,Qf as gc,PC as gd,Ya as ge,xl as gf,Bc as gg,nI as gh,dy as gi,WC as gj,G0 as gk,VC as gl,JC as gm,zC as gn,Wy as go,CC as gp,$y as gq,MC as gr,jC as gs,DC as gt,$C as gu,NC as gv,HC as gw,A1 as gx,bP as gy,Q1 as gz,qu as h,SC as h0,R_ as h1,kC as h2,bC as h3,yC as h4,nd as h5,_C as h6,gC as h7,wC as h8,rd as h9,vC as ha,yf as hb,IC as hc,AC as hd,NO as he,F1 as hf,G1 as hg,H1 as hh,W1 as hi,$O as hj,DO as hk,__ as hl,Tl as hm,Y_ as i,Q_ as j,X_ as k,J_ as l,eg as m,rP as n,JA as o,$x as p,xv as q,Ev as r,Px as s,Ax as t,Bm as u,cA as v,yt as w,LO as x,HO as y,VE as z};