local-operator-ui 0.48.13 → 0.48.14

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 (99) hide show
  1. package/out/main/index.js +64 -8
  2. package/out/renderer/assets/{_basePickBy-CKmx30yF.js → _basePickBy-CqjnHpsV.js} +1 -1
  3. package/out/renderer/assets/{_baseUniq-Bpi6IoVg.js → _baseUniq-CULkxOs9.js} +1 -1
  4. package/out/renderer/assets/{agent-details-page-DO7d_ih5.js → agent-details-page-lJZmiKX2.js} +1 -1
  5. package/out/renderer/assets/{agent-hub-page-DqIdGNHj.js → agent-hub-page-CXOuZ3yB.js} +1 -1
  6. package/out/renderer/assets/{agents-page-DMudbdAq.js → agents-page-CnFoBt7k.js} +3 -3
  7. package/out/renderer/assets/{approvalsOverlay-Bnfsw8L9.js → approvalsOverlay-GNG8MQGq.js} +1 -1
  8. package/out/renderer/assets/{arc-OIEGuBTn.js → arc-oG0NKaKg.js} +1 -1
  9. package/out/renderer/assets/{architectureDiagram-IEHRJDOE-CzKyJ4cr.js → architectureDiagram-IEHRJDOE-aCa20cAA.js} +1 -1
  10. package/out/renderer/assets/{avatar-cropper-DXYS7VvI.js → avatar-cropper-BKB4pmro.js} +1 -1
  11. package/out/renderer/assets/{blockDiagram-JOT3LUYC-ChQDHo8e.js → blockDiagram-JOT3LUYC-DoWnJlfb.js} +1 -1
  12. package/out/renderer/assets/{book-open-BAlAnYWc.js → book-open-_QnLjbGc.js} +1 -1
  13. package/out/renderer/assets/browser-page-n0j1N7Ab.js +1 -0
  14. package/out/renderer/assets/{browser-webauthn-prompt-C7dwOBvW.js → browser-webauthn-prompt-2wnyPWXR.js} +1 -1
  15. package/out/renderer/assets/{building-2-B4SNlD8W.js → building-2-CuIMWuHp.js} +1 -1
  16. package/out/renderer/assets/{c4Diagram-VJAJSXHY-DP6s4-gF.js → c4Diagram-VJAJSXHY-NhmXu-dk.js} +1 -1
  17. package/out/renderer/assets/channel-CiyaEias.js +1 -0
  18. package/out/renderer/assets/{chunk-4BMEZGHF-CfMGVgaT.js → chunk-4BMEZGHF-WKw6LM2E.js} +1 -1
  19. package/out/renderer/assets/{chunk-A2AXSNBT-C7LLSPSK.js → chunk-A2AXSNBT-VREyhp5G.js} +1 -1
  20. package/out/renderer/assets/{chunk-AEK57VVT-ssRgcUgK.js → chunk-AEK57VVT-Dcq313P6.js} +1 -1
  21. package/out/renderer/assets/{chunk-D6G4REZN-w9sKgwLw.js → chunk-D6G4REZN-BwmfGuQ0.js} +1 -1
  22. package/out/renderer/assets/{chunk-RZ5BOZE2-C3JZadRL.js → chunk-RZ5BOZE2-B0i9CUvw.js} +1 -1
  23. package/out/renderer/assets/{chunk-XZIHB7SX-A81zsT6l.js → chunk-XZIHB7SX-Bb55_5Sx.js} +1 -1
  24. package/out/renderer/assets/classDiagram-GIVACNV2-D0er2Ls8.js +1 -0
  25. package/out/renderer/assets/classDiagram-v2-COTLJTTW-D0er2Ls8.js +1 -0
  26. package/out/renderer/assets/clone-CMoDXzY3.js +1 -0
  27. package/out/renderer/assets/{console-mirror-Bd9Lx41W.js → console-mirror-wmAJUEAs.js} +1 -1
  28. package/out/renderer/assets/{consoleCapture-TtI3yw3S.js → consoleCapture-DkdTJX2Q.js} +1 -1
  29. package/out/renderer/assets/{conversation-input-sync-B0udOX2P.js → conversation-input-sync-Ljt2C84E.js} +258 -257
  30. package/out/renderer/assets/{dagre-OKDRZEBW-futvc0Ip.js → dagre-OKDRZEBW-u2i5WhoT.js} +1 -1
  31. package/out/renderer/assets/{diagram-SSKATNLV-DRqJ6jPO.js → diagram-SSKATNLV-CujjPcjH.js} +1 -1
  32. package/out/renderer/assets/{diagram-VNBRO52H-CoXmeLca.js → diagram-VNBRO52H-2G42wb4l.js} +1 -1
  33. package/out/renderer/assets/{erDiagram-Q7BY3M3F-DamfzVbu.js → erDiagram-Q7BY3M3F-Bu73stew.js} +1 -1
  34. package/out/renderer/assets/{error-boundary-DQKaFMb3.js → error-boundary-iAAsdMV6.js} +1 -1
  35. package/out/renderer/assets/{flowDiagram-4HSFHLVR-D_JracNp.js → flowDiagram-4HSFHLVR-BSjvh_jr.js} +1 -1
  36. package/out/renderer/assets/{ganttDiagram-APWFNJXF-DxkMvvzu.js → ganttDiagram-APWFNJXF-EJycAePi.js} +1 -1
  37. package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-Ch2WfuGl.js → gitGraphDiagram-7IBYFJ6S-PB_m6UAq.js} +1 -1
  38. package/out/renderer/assets/{graph-E23dAXFZ.js → graph-BxZlYsmw.js} +1 -1
  39. package/out/renderer/assets/{hash-Ccn2EAfy.js → hash-K40hVccW.js} +1 -1
  40. package/out/renderer/assets/{heart-DRuR5lyD.js → heart-DzefdwPO.js} +1 -1
  41. package/out/renderer/assets/{image-plus-CO38-orC.js → image-plus-DVE8D9f4.js} +1 -1
  42. package/out/renderer/assets/{index-DszIY8oB.js → index-BA3RZ8Br.js} +1 -1
  43. package/out/renderer/assets/{index-871YiMwJ.js → index-CxREIho-.js} +1 -1
  44. package/out/renderer/assets/{index-D8bU6n8S.js → index-DbWHoxKa.js} +3 -3
  45. package/out/renderer/assets/index-LE17ehWa.css +1 -0
  46. package/out/renderer/assets/{index-Cvms1u2n.js → index-oOJJkr9e.js} +1 -1
  47. package/out/renderer/assets/infoDiagram-PH2N3AL5-DXQeWslF.js +2 -0
  48. package/out/renderer/assets/{installer-BsEQzRI7.js → installer-B-eY61tX.js} +1 -1
  49. package/out/renderer/assets/{journeyDiagram-U35MCT3I-7o71pCw6.js → journeyDiagram-U35MCT3I-CyQtY9wm.js} +1 -1
  50. package/out/renderer/assets/{kanban-definition-NDS4AKOZ-Ba2fKg5g.js → kanban-definition-NDS4AKOZ-tFIMwUpw.js} +1 -1
  51. package/out/renderer/assets/{layout-u9aNonBe.js → layout-CTmVT6af.js} +1 -1
  52. package/out/renderer/assets/{legacy-agents-page-BUZN75el.js → legacy-agents-page--Rair6vP.js} +1 -1
  53. package/out/renderer/assets/{library-page-CnofZnaB.js → library-page-uYpy37ZN.js} +3 -3
  54. package/out/renderer/assets/{mermaid.core-BO7pGBkG.js → mermaid.core-BvXogV1Z.js} +5 -5
  55. package/out/renderer/assets/{mesh-page-BCIVB0Hi.js → mesh-page-DoFh0sb0.js} +1 -1
  56. package/out/renderer/assets/{messages-BZscpRIC.js → messages-th0c6S1e.js} +8 -8
  57. package/out/renderer/assets/{mindmap-definition-ALO5MXBD--7E9KpWa.js → mindmap-definition-ALO5MXBD-DZVFZ38w.js} +1 -1
  58. package/out/renderer/assets/{mini-CdnwZ2z8.js → mini-1kvE_2tK.js} +1 -1
  59. package/out/renderer/assets/{notebook-pen-Dtk48ynr.js → notebook-pen-DjPosiuD.js} +1 -1
  60. package/out/renderer/assets/{notifications-page-DVFMPXXe.js → notifications-page-C6w6nMjb.js} +1 -1
  61. package/out/renderer/assets/{org-access-HM79rP3f.js → org-access-rMoT0u2l.js} +1 -1
  62. package/out/renderer/assets/{org-surface-gate-DKBYiK5D.js → org-surface-gate-B0nNR3Dz.js} +1 -1
  63. package/out/renderer/assets/{page-header-Y2McYPDx.js → page-header-DUmUT_Ad.js} +1 -1
  64. package/out/renderer/assets/{path-utils-BrLZulPz.js → path-utils-2YI9PZ0N.js} +32 -32
  65. package/out/renderer/assets/{pieDiagram-IB7DONF6-D5TiBcOS.js → pieDiagram-IB7DONF6-BAs1yZaq.js} +1 -1
  66. package/out/renderer/assets/{project-markdown-DM2zz9cY.js → project-markdown-C8Uo14Aq.js} +1 -1
  67. package/out/renderer/assets/{projects-page-DQW7vu5M.js → projects-page-D_7oIEvX.js} +1 -1
  68. package/out/renderer/assets/{publication-validation-CjUR3KXX.js → publication-validation-DmYPLvRC.js} +1 -1
  69. package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-BxqgjzcX.js → quadrantDiagram-7GDLP6J5-DG-wsRad.js} +1 -1
  70. package/out/renderer/assets/{radar-MK3ICKWK-RhGIy4cy.js → radar-MK3ICKWK-NF-imI4f.js} +1 -1
  71. package/out/renderer/assets/{radient-auth-buttons-CjcIy4Ra.js → radient-auth-buttons-nhpIQ5IS.js} +1 -1
  72. package/out/renderer/assets/{requirementDiagram-KVF5MWMF-BbMnuHR5.js → requirementDiagram-KVF5MWMF-DtKpbYlY.js} +1 -1
  73. package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-B5rU7VZ5.js → sankeyDiagram-QLVOVGJD-D16V3y8g.js} +1 -1
  74. package/out/renderer/assets/{schedules-page-D_c2nY3o.js → schedules-page-Cj3Uekqu.js} +1 -1
  75. package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-B3c6QPin.js → sequenceDiagram-X6HHIX6F-CdouRiAc.js} +1 -1
  76. package/out/renderer/assets/{settings-page-AbHZDN8P.js → settings-page-CLkD2Y91.js} +1 -1
  77. package/out/renderer/assets/{smartart-K65nA3xt.js → smartart-BJMtaIOY.js} +1 -1
  78. package/out/renderer/assets/{stateDiagram-DGXRK772-BaaeHACk.js → stateDiagram-DGXRK772-BqF42ITE.js} +1 -1
  79. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-nsHrbQkw.js +1 -0
  80. package/out/renderer/assets/{team-bridge-page-Cgvoi96Y.js → team-bridge-page-BcWOzonp.js} +1 -1
  81. package/out/renderer/assets/{team-bridge-scope-preference-CgR9TBFd.js → team-bridge-scope-preference-BelhGFfv.js} +1 -1
  82. package/out/renderer/assets/{timeline-definition-BDJGKUSR-DazTtN2a.js → timeline-definition-BDJGKUSR-BjKsGQ4N.js} +1 -1
  83. package/out/renderer/assets/{use-download-agent-mutation-DB5SyNA0.js → use-download-agent-mutation-CiwSVQa5.js} +1 -1
  84. package/out/renderer/assets/{use-session-snapshot-DbuqOFVq.js → use-session-snapshot-De0MaqPb.js} +1 -1
  85. package/out/renderer/assets/{xychartDiagram-VJFVF3MP-7wZpEaYI.js → xychartDiagram-VJFVF3MP-DBg47u_T.js} +1 -1
  86. package/out/renderer/browser-approvals-overlay.html +2 -2
  87. package/out/renderer/console-capture.html +6 -6
  88. package/out/renderer/index.html +8 -8
  89. package/out/renderer/installer.html +5 -5
  90. package/out/renderer/mini.html +8 -8
  91. package/package.json +1 -1
  92. package/out/renderer/assets/browser-page-DKyFBSCV.js +0 -1
  93. package/out/renderer/assets/channel-DXyM-LNQ.js +0 -1
  94. package/out/renderer/assets/classDiagram-GIVACNV2-BouPcaGl.js +0 -1
  95. package/out/renderer/assets/classDiagram-v2-COTLJTTW-BouPcaGl.js +0 -1
  96. package/out/renderer/assets/clone-BWgv46LY.js +0 -1
  97. package/out/renderer/assets/index-dyl6bCMv.css +0 -1
  98. package/out/renderer/assets/infoDiagram-PH2N3AL5-BzxTTi16.js +0 -2
  99. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-B8p6qkit.js +0 -1
@@ -1,49 +1,49 @@
1
- import{r as S,j as lp,b as Fa,D as dp}from"./index-DszIY8oB.js";import{t as h,a as up}from"./messages-BZscpRIC.js";var Tr=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(){}},on=typeof window>"u"||"Deno"in globalThis;function Xe(){}function fp(e,t){return typeof e=="function"?e(t):e}function Ps(e){return typeof e=="number"&&e>=0&&e!==1/0}function Vl(e,t){return Math.max(e+(t||0)-Date.now(),0)}function kn(e,t){return typeof e=="function"?e(t):e}function ot(e,t){return typeof e=="function"?e(t):e}function Ba(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:s,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==Io(a,t.options))return!1}else if(!or(t.queryKey,a))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||i&&i!==t.state.fetchStatus||s&&!s(t))}function Ga(e,t){const{exact:n,status:r,predicate:i,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(sr(t.options.mutationKey)!==sr(s))return!1}else if(!or(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Io(e,t){return(t?.queryKeyHashFn||sr)(e)}function sr(e){return JSON.stringify(e,(t,n)=>Ms(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function or(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>or(e[n],t[n])):!1}function Yl(e,t){if(e===t)return e;const n=Ha(e)&&Ha(t);if(n||Ms(e)&&Ms(t)){const r=n?e:Object.keys(e),i=r.length,s=n?t:Object.keys(t),a=s.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:s[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=Yl(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return i===a&&l===i?e:c}return t}function js(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 Ha(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ms(e){if(!za(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!za(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function za(e){return Object.prototype.toString.call(e)==="[object Object]"}function pp(e){return new Promise(t=>{setTimeout(t,e)})}function Ds(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Yl(e,t):t}function hp(e){return e}function mp(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function gp(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var xo=Symbol();function Ql(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===xo?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var _p=class extends Tr{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!on&&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"}},Ro=new _p,yp=class extends Tr{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!on&&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}},oi=new yp;function Ns(){let e,t;const n=new Promise((i,s)=>{e=i,t=s});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}function bp(e){return Math.min(1e3*2**e,3e4)}function Jl(e){return(e??"online")==="online"?oi.isOnline():!0}var Xl=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Qi(e){return e instanceof Xl}function ql(e){let t=!1,n=0,r=!1,i;const s=Ns(),a=m=>{r||(p(new Xl(m)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>Ro.isFocused()&&(e.networkMode==="always"||oi.isOnline())&&e.canRun(),u=()=>Jl(e.networkMode)&&e.canRun(),f=m=>{r||(r=!0,e.onSuccess?.(m),i?.(),s.resolve(m))},p=m=>{r||(r=!0,e.onError?.(m),i?.(),s.reject(m))},g=()=>new Promise(m=>{i=b=>{(r||d())&&m(b)},e.onPause?.()}).then(()=>{i=void 0,r||e.onContinue?.()}),y=()=>{if(r)return;let m;const b=n===0?e.initialPromise:void 0;try{m=b??e.fn()}catch(_){m=Promise.reject(_)}Promise.resolve(m).then(f).catch(_=>{if(r)return;const k=e.retry??(on?0:3),E=e.retryDelay??bp,A=typeof E=="function"?E(n,_):E,$=k===!0||typeof k=="number"&&n<k||typeof k=="function"&&k(n,_);if(t||!$){p(_);return}n++,e.onFail?.(n,_),pp(A).then(()=>d()?void 0:g()).then(()=>{t?p(_):y()})})};return{promise:s,cancel:a,continue:()=>(i?.(),s),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?y():g().then(y),s)}}var vp=e=>setTimeout(e,0);function wp(){let e=[],t=0,n=c=>{c()},r=c=>{c()},i=vp;const s=c=>{t?e.push(c):i(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&i(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{s(()=>{c(...l)})},schedule:s,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{i=c}}}var De=wp(),ed=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ps(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(on?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},Sp=class extends ed{#t;#e;#n;#r;#i;#a;#o;constructor(e){super(),this.#o=!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=kp(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#i?.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=Ds(this.state.data,e,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#s({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#i?.promise;return this.#i?.cancel(e),t?t.then(Xe).catch(Xe):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>ot(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===xo||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||!Vl(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.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.#i&&(this.#o?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.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.#o=!0,n.signal)})},i=()=>{const c=Ql(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(l),this.#o=!1,this.options.persister?this.options.persister(c,l,this):c(l)},s={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:i};r(s),this.options.behavior?.onFetch(s,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#s({type:"fetch",meta:s.fetchOptions?.meta});const a=c=>{Qi(c)&&c.silent||this.#s({type:"error",error:c}),Qi(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#i=ql({initialPromise:t?.initialPromise,fn:s.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){a(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){a(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:a,onFail:(c,l)=>{this.#s({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0}),this.#i.start()}#s(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...td(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 Qi(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),De.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function td(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Jl(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function kp(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 Ep=class extends Tr{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,i=t.queryHash??Io(r,t);let s=this.get(i);return s||(s=new Sp({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(s)),s}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){De.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=>Ba(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Ba(e,n)):t}notify(e){De.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){De.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){De.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Ip=class extends ed{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||xp(),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=ql({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(r,i)=>{this.#r({type:"failed",failureCount:r,error:i})},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 i=await this.options.onMutate?.(e);i!==this.state.context&&this.#r({type:"pending",context:i,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),De.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#e.notify({mutation:this,type:"updated",action:e})})}};function xp(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Rp=class extends Tr{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 Ip({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=Fr(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=Fr(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=Fr(e);if(typeof t=="string"){const r=this.#e.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Fr(e);return typeof t=="string"?this.#e.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){De.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=>Ga(t,n))}findAll(e={}){return this.getAll().filter(t=>Ga(e,t))}notify(e){De.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return De.batch(()=>Promise.all(e.map(t=>t.continue().catch(Xe))))}};function Fr(e){return e.options.scope?.id}function Wa(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},p=Ql(t.options,t.fetchOptions),g=async(y,m,b)=>{if(u)return Promise.reject();if(m==null&&y.pages.length)return Promise.resolve(y);const _={client:t.client,queryKey:t.queryKey,pageParam:m,direction:b?"backward":"forward",meta:t.options.meta};f(_);const k=await p(_),{maxPages:E}=t.options,A=b?gp:mp;return{pages:A(y.pages,k,E),pageParams:A(y.pageParams,m,E)}};if(i&&s.length){const y=i==="backward",m=y?nd:Ls,b={pages:s,pageParams:a},_=m(r,b);c=await g(b,_,y)}else{const y=e??s.length;do{const m=l===0?a[0]??r.initialPageParam:Ls(r,c);if(l>0&&m==null)break;c=await g(c,m),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 Ls(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 nd(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function PI(e,t){return t?Ls(e,t)!=null:!1}function jI(e,t){return!t||!e.getPreviousPageParam?!1:nd(e,t)!=null}var Tp=class{#t;#e;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#t=e.queryCache||new Ep,this.#e=e.mutationCache||new Rp,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=Ro.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#s=oi.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#t.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(kn(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=this.#t.get(r.queryHash)?.state.data,a=fp(t,s);if(a!==void 0)return this.#t.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return De.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;De.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return De.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=De.batch(()=>this.#t.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then(Xe).catch(Xe)}invalidateQueries(e,t={}){return De.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=De.batch(()=>this.#t.findAll(e).filter(i=>!i.isDisabled()).map(i=>{let s=i.fetch(void 0,n);return n.throwOnError||(s=s.catch(Xe)),i.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(Xe)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(kn(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Xe).catch(Xe)}fetchInfiniteQuery(e){return e.behavior=Wa(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Xe).catch(Xe)}ensureInfiniteQueryData(e){return e.behavior=Wa(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return oi.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(sr(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{or(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(sr(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#i.values()],n={};return t.forEach(r=>{or(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=Io(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===xo&&(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()}},Cp=class extends Tr{constructor(e,t){super(),this.options=t,this.#t=e,this.#s=null,this.#o=Ns(),this.options.experimental_prefetchInRender||this.#o.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;#i;#a;#o;#s;#m;#f;#p;#l;#d;#c;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),Za(this.#e,this.options)?this.#u():this.updateResult(),this.#b())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return $s(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return $s(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#v(),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 ot(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#e.setOptions(this.options),t._defaulted&&!js(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&Ka(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||ot(this.options.enabled,this.#e)!==ot(t.enabled,this.#e)||kn(this.options.staleTime,this.#e)!==kn(t.staleTime,this.#e))&&this.#g();const i=this.#_();r&&(this.#e!==n||ot(this.options.enabled,this.#e)!==ot(t.enabled,this.#e)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return Op(this,n)&&(this.#r=n,this.#a=this.options,this.#i=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.#S();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Xe)),t}#g(){this.#v();const e=kn(this.options.staleTime,this.#e);if(on||this.#r.isStale||!Ps(e))return;const n=Vl(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}#y(e){this.#w(),this.#c=e,!(on||ot(this.options.enabled,this.#e)===!1||!Ps(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||Ro.isFocused())&&this.#u()},this.#c))}#b(){this.#g(),this.#y(this.#_())}#v(){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,i=this.#r,s=this.#i,a=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,p;if(t._optimisticResults){const I=this.hasListeners(),N=!I&&Za(e,t),F=I&&Ka(e,n,t,r);(N||F)&&(u={...u,...td(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:g,errorUpdatedAt:y,status:m}=u;p=u.data;let b=!1;if(t.placeholderData!==void 0&&p===void 0&&m==="pending"){let I;i?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(I=i.data,b=!0):I=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,I!==void 0&&(m="success",p=Ds(i?.data,I,t),f=!0)}if(t.select&&p!==void 0&&!b)if(i&&p===s?.data&&t.select===this.#m)p=this.#f;else try{this.#m=t.select,p=t.select(p),p=Ds(i?.data,p,t),this.#f=p,this.#s=null}catch(I){this.#s=I}this.#s&&(g=this.#s,p=this.#f,y=Date.now(),m="error");const _=u.fetchStatus==="fetching",k=m==="pending",E=m==="error",A=k&&_,$=p!==void 0,C={status:m,fetchStatus:u.fetchStatus,isPending:k,isSuccess:m==="success",isError:E,isInitialLoading:A,isLoading:A,data:p,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:_,isRefetching:_&&!k,isLoadingError:E&&!$,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:E&&$,isStale:To(e,t),refetch:this.refetch,promise:this.#o};if(this.options.experimental_prefetchInRender){const I=se=>{C.status==="error"?se.reject(C.error):C.data!==void 0&&se.resolve(C.data)},N=()=>{const se=this.#o=C.promise=Ns();I(se)},F=this.#o;switch(F.status){case"pending":e.queryHash===n.queryHash&&I(F);break;case"fulfilled":(C.status==="error"||C.data!==F.value)&&N();break;case"rejected":(C.status!=="error"||C.error!==F.reason)&&N();break}}return C}updateResult(){const e=this.#r,t=this.createResult(this.#e,this.options);if(this.#i=this.#e.state,this.#a=this.options,this.#i.data!==void 0&&(this.#p=this.#e),js(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#h.size)return!0;const s=new Set(i??this.#h);return this.options.throwOnError&&s.add("error"),Object.keys(this.#r).some(a=>{const c=a;return this.#r[c]!==e[c]&&s.has(c)})};this.#k({listeners:n()})}#S(){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.#b()}#k(e){De.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function Ap(e,t){return ot(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Za(e,t){return Ap(e,t)||e.state.data!==void 0&&$s(e,t,t.refetchOnMount)}function $s(e,t,n){if(ot(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&To(e,t)}return!1}function Ka(e,t,n,r){return(e!==t||ot(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&To(e,n)}function To(e,t){return ot(t.enabled,e)!==!1&&e.isStaleByTime(kn(t.staleTime,e))}function Op(e,t){return!js(e.getCurrentResult(),t)}var Co=S.createContext(void 0),Pp=e=>{const t=S.useContext(Co);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},MI=({client:e,children:t})=>(S.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),lp.jsx(Co.Provider,{value:e,children:t})),rd=S.createContext(!1),jp=()=>S.useContext(rd);rd.Provider;function Mp(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Dp=S.createContext(Mp()),Np=()=>S.useContext(Dp);function Lp(e,t){return typeof e=="function"?e(...t):!!e}function Va(){}var $p=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},Up=e=>{S.useEffect(()=>{e.clearReset()},[e])},Fp=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Lp(n,[e.error,r])),Bp=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)))},Gp=(e,t)=>e.isLoading&&e.isFetching&&!t,Hp=(e,t)=>e?.suspense&&t.isPending,Ya=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function zp(e,t,n){const r=Pp(n),i=jp(),s=Np(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=i?"isRestoring":"optimistic",Bp(a),$p(a,s),Up(s);const c=!r.getQueryCache().get(a.queryHash),[l]=S.useState(()=>new t(r,a)),d=l.getOptimisticResult(a),u=!i&&e.subscribed!==!1;if(S.useSyncExternalStore(S.useCallback(f=>{const p=u?l.subscribe(De.batchCalls(f)):Va;return l.updateResult(),p},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),S.useEffect(()=>{l.setOptions(a)},[a,l]),Hp(a,d))throw Ya(a,l,s);if(Fp({result:d,errorResetBoundary:s,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw d.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!on&&Gp(d,i)&&(c?Ya(a,l,s):r.getQueryCache().get(a.queryHash)?.promise)?.catch(Va).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function id(e,t){return zp(e,Cp,t)}const Wp=()=>{const e=S.useContext(Co)??null,t=S.useMemo(()=>new Tp({defaultOptions:{queries:{enabled:!1,retry:!1,gcTime:0}}}),[]);return S.useEffect(()=>{if(!e)return()=>t.clear()},[e,t]),S.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function DI(e){return e!=="detached"&&e!=="wedged"}function sd(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function NI(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=sd(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 re;(function(e){e.assertEqual=i=>i;function t(i){}e.assertIs=t;function n(i){throw new Error}e.assertNever=n,e.arrayToEnum=i=>{const s={};for(const a of i)s[a]=a;return s},e.getValidEnumValues=i=>{const s=e.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),a={};for(const c of s)a[c]=i[c];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const s=[];for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},e.find=(i,s)=>{for(const a of i)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(re||(re={}));var Us;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Us||(Us={}));const M=re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kt=e=>{switch(typeof e){case"undefined":return M.undefined;case"string":return M.string;case"number":return isNaN(e)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(e)?M.array:e===null?M.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?M.promise:typeof Map<"u"&&e instanceof Map?M.map:typeof Set<"u"&&e instanceof Set?M.set:typeof Date<"u"&&e instanceof Date?M.date:M.object;default:return M.unknown}},R=re.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"]),Zp=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Ye extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(s){return s.message},r={_errors:[]},i=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){const d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return i(this),r}static assert(t){if(!(t instanceof Ye))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,re.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const i of this.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Ye.create=e=>new Ye(e);const Tn=(e,t)=>{let n;switch(e.code){case R.invalid_type:e.received===M.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case R.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,re.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:n=`Unrecognized key(s) in object: ${re.joinValues(e.keys,", ")}`;break;case R.invalid_union:n="Invalid input";break;case R.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${re.joinValues(e.options)}`;break;case R.invalid_enum_value:n=`Invalid enum value. Expected ${re.joinValues(e.options)}, received '${e.received}'`;break;case R.invalid_arguments:n="Invalid function arguments";break;case R.invalid_return_type:n="Invalid function return type";break;case R.invalid_date:n="Invalid date";break;case R.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}"`:re.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case R.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 R.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 R.custom:n="Invalid input";break;case R.invalid_intersection_types:n="Intersection results could not be merged";break;case R.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case R.not_finite:n="Number must be finite";break;default:n=t.defaultError,re.assertNever(e)}return{message:n}};let od=Tn;function Kp(e){od=e}function ai(){return od}const ci=e=>{const{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let c="";const l=r.filter(d=>!!d).slice().reverse();for(const d of l)c=d(a,{data:t,defaultError:c}).message;return{...i,path:s,message:c}},Vp=[];function j(e,t){const n=ai(),r=ci({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Tn?void 0:Tn].filter(i=>!!i)});e.common.issues.push(r)}class $e{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 i of n){if(i.status==="aborted")return W;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const i of n){const s=await i.key,a=await i.value;r.push({key:s,value:a})}return $e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const i of n){const{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return W;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}}const W=Object.freeze({status:"aborted"}),vn=e=>({status:"dirty",value:e}),Ue=e=>({status:"valid",value:e}),Fs=e=>e.status==="aborted",Bs=e=>e.status==="dirty",an=e=>e.status==="valid",ar=e=>typeof Promise<"u"&&e instanceof Promise;function li(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 ad(e,t,n,r,i){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 U;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(U||(U={}));var Yn,Qn;class gt{constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}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 Qa=(e,t)=>{if(an(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 Ye(e.common.issues);return this._error=n,this._error}}};function J(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:i}=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:i}:{errorMap:(a,c)=>{var l,d;const{message:u}=e;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??r)!==null&&l!==void 0?l:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??n)!==null&&d!==void 0?d:c.defaultError}},description:i}}class X{get description(){return this._def.description}_getType(t){return kt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:kt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new $e,ctx:{common:t.parent.common,data:t.data,parsedType:kt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(ar(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 i={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:kt(t)},s=this._parseSync({data:t,path:i.path,parent:i});return Qa(i,s)}"~validate"(t){var n,r;const i={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:kt(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:i});return an(s)?{value:s.value}:{issues:i.common.issues}}catch(s){!((r=(n=s?.message)===null||n===void 0?void 0:n.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),i.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:i}).then(s=>an(s)?{value:s.value}:{issues:i.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:kt(t)},i=this._parse({data:t,path:r.path,parent:r}),s=await(ar(i)?i:Promise.resolve(i));return Qa(r,s)}refine(t,n){const r=i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,s)=>{const a=t(i),c=()=>s.addIssue({code:R.custom,...r(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(t){return new lt({schema:this,typeName:H.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 ht.create(this,this._def)}nullable(){return Gt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ct.create(this)}promise(){return An.create(this,this._def)}or(t){return ur.create([this,t],this._def)}and(t){return fr.create(this,t,this._def)}transform(t){return new lt({...J(this._def),schema:this,typeName:H.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new _r({...J(this._def),innerType:this,defaultValue:n,typeName:H.ZodDefault})}brand(){return new Ao({typeName:H.ZodBranded,type:this,...J(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new yr({...J(this._def),innerType:this,catchValue:n,typeName:H.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Cr.create(this,t)}readonly(){return br.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Yp=/^c[^\s-]{8,}$/i,Qp=/^[0-9a-z]+$/,Jp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Xp=/^[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,qp=/^[a-z0-9_-]{21}$/i,eh=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,th=/^[-+]?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)?)??$/,nh=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,rh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ji;const ih=/^(?:(?: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])$/,sh=/^(?:(?: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])$/,oh=/^(([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]))$/,ah=/^(([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])$/,ch=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,lh=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,cd="((\\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])))",dh=new RegExp(`^${cd}$`);function ld(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 uh(e){return new RegExp(`^${ld(e)}$`)}function dd(e){let t=`${cd}T${ld(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 fh(e,t){return!!((t==="v4"||!t)&&ih.test(e)||(t==="v6"||!t)&&oh.test(e))}function ph(e,t){if(!eh.test(e))return!1;try{const[n]=e.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||!i.typ||!i.alg||t&&i.alg!==t)}catch{return!1}}function hh(e,t){return!!((t==="v4"||!t)&&sh.test(e)||(t==="v6"||!t)&&ah.test(e))}class at extends X{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==M.string){const s=this._getOrReturnCtx(t);return j(s,{code:R.invalid_type,expected:M.string,received:s.parsedType}),W}const r=new $e;let i;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(i=this._getOrReturnCtx(t,i),j(i,{code:R.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(i=this._getOrReturnCtx(t,i),j(i,{code:R.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,c=t.data.length<s.value;(a||c)&&(i=this._getOrReturnCtx(t,i),a?j(i,{code:R.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&j(i,{code:R.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")nh.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"email",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Ji||(Ji=new RegExp(rh,"u")),Ji.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"emoji",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")Xp.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"uuid",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")qp.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"nanoid",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Yp.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"cuid",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Qp.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"cuid2",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Jp.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"ulid",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),j(i,{validation:"url",code:R.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"regex",code:R.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(t,i),j(i,{code:R.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(i=this._getOrReturnCtx(t,i),j(i,{code:R.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(i=this._getOrReturnCtx(t,i),j(i,{code:R.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?dd(s).test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{code:R.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?dh.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{code:R.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?uh(s).test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{code:R.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?th.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"duration",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?fh(t.data,s.version)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"ip",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?ph(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"jwt",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?hh(t.data,s.version)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"cidr",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?ch.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"base64",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?lh.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"base64url",code:R.invalid_string,message:s.message}),r.dirty()):re.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:R.invalid_string,...U.errToObj(r)})}_addCheck(t){return new at({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...U.errToObj(t)})}url(t){return this._addCheck({kind:"url",...U.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...U.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...U.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...U.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...U.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...U.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...U.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...U.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...U.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...U.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...U.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...U.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,...U.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,...U.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...U.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...U.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...U.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...U.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...U.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...U.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...U.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...U.errToObj(n)})}nonempty(t){return this.min(1,U.errToObj(t))}trim(){return new at({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new at({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new at({...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}}at.create=e=>{var t;return new at({checks:[],typeName:H.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...J(e)})};function mh(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,s=parseInt(e.toFixed(i).replace(".","")),a=parseInt(t.toFixed(i).replace(".",""));return s%a/Math.pow(10,i)}class Ut extends X{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)!==M.number){const s=this._getOrReturnCtx(t);return j(s,{code:R.invalid_type,expected:M.number,received:s.parsedType}),W}let r;const i=new $e;for(const s of this._def.checks)s.kind==="int"?re.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),j(r,{code:R.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:R.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:R.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?mh(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),j(r,{code:R.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),j(r,{code:R.not_finite,message:s.message}),i.dirty()):re.assertNever(s);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,U.toString(n))}gt(t,n){return this.setLimit("min",t,!1,U.toString(n))}lte(t,n){return this.setLimit("max",t,!0,U.toString(n))}lt(t,n){return this.setLimit("max",t,!1,U.toString(n))}setLimit(t,n,r,i){return new Ut({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:U.toString(i)}]})}_addCheck(t){return new Ut({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:U.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:U.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:U.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.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"&&re.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)}}Ut.create=e=>new Ut({checks:[],typeName:H.ZodNumber,coerce:e?.coerce||!1,...J(e)});class Ft extends X{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)!==M.bigint)return this._getInvalidInput(t);let r;const i=new $e;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:R.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:R.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),j(r,{code:R.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):re.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return j(n,{code:R.invalid_type,expected:M.bigint,received:n.parsedType}),W}gte(t,n){return this.setLimit("min",t,!0,U.toString(n))}gt(t,n){return this.setLimit("min",t,!1,U.toString(n))}lte(t,n){return this.setLimit("max",t,!0,U.toString(n))}lt(t,n){return this.setLimit("max",t,!1,U.toString(n))}setLimit(t,n,r,i){return new Ft({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:U.toString(i)}]})}_addCheck(t){return new Ft({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:U.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}}Ft.create=e=>{var t;return new Ft({checks:[],typeName:H.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...J(e)})};class cr extends X{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==M.boolean){const r=this._getOrReturnCtx(t);return j(r,{code:R.invalid_type,expected:M.boolean,received:r.parsedType}),W}return Ue(t.data)}}cr.create=e=>new cr({typeName:H.ZodBoolean,coerce:e?.coerce||!1,...J(e)});class cn extends X{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==M.date){const s=this._getOrReturnCtx(t);return j(s,{code:R.invalid_type,expected:M.date,received:s.parsedType}),W}if(isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return j(s,{code:R.invalid_date}),W}const r=new $e;let i;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),j(i,{code:R.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(i=this._getOrReturnCtx(t,i),j(i,{code:R.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):re.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new cn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:U.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:U.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}}cn.create=e=>new cn({checks:[],coerce:e?.coerce||!1,typeName:H.ZodDate,...J(e)});class di extends X{_parse(t){if(this._getType(t)!==M.symbol){const r=this._getOrReturnCtx(t);return j(r,{code:R.invalid_type,expected:M.symbol,received:r.parsedType}),W}return Ue(t.data)}}di.create=e=>new di({typeName:H.ZodSymbol,...J(e)});class lr extends X{_parse(t){if(this._getType(t)!==M.undefined){const r=this._getOrReturnCtx(t);return j(r,{code:R.invalid_type,expected:M.undefined,received:r.parsedType}),W}return Ue(t.data)}}lr.create=e=>new lr({typeName:H.ZodUndefined,...J(e)});class dr extends X{_parse(t){if(this._getType(t)!==M.null){const r=this._getOrReturnCtx(t);return j(r,{code:R.invalid_type,expected:M.null,received:r.parsedType}),W}return Ue(t.data)}}dr.create=e=>new dr({typeName:H.ZodNull,...J(e)});class Cn extends X{constructor(){super(...arguments),this._any=!0}_parse(t){return Ue(t.data)}}Cn.create=e=>new Cn({typeName:H.ZodAny,...J(e)});class tn extends X{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ue(t.data)}}tn.create=e=>new tn({typeName:H.ZodUnknown,...J(e)});class It extends X{_parse(t){const n=this._getOrReturnCtx(t);return j(n,{code:R.invalid_type,expected:M.never,received:n.parsedType}),W}}It.create=e=>new It({typeName:H.ZodNever,...J(e)});class ui extends X{_parse(t){if(this._getType(t)!==M.undefined){const r=this._getOrReturnCtx(t);return j(r,{code:R.invalid_type,expected:M.void,received:r.parsedType}),W}return Ue(t.data)}}ui.create=e=>new ui({typeName:H.ZodVoid,...J(e)});class ct extends X{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==M.array)return j(n,{code:R.invalid_type,expected:M.array,received:n.parsedType}),W;if(i.exactLength!==null){const a=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(a||c)&&(j(n,{code:a?R.too_big:R.too_small,minimum:c?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(j(n,{code:R.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(j(n,{code:R.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>i.type._parseAsync(new gt(n,a,n.path,c)))).then(a=>$e.mergeArray(r,a));const s=[...n.data].map((a,c)=>i.type._parseSync(new gt(n,a,n.path,c)));return $e.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new ct({...this._def,minLength:{value:t,message:U.toString(n)}})}max(t,n){return new ct({...this._def,maxLength:{value:t,message:U.toString(n)}})}length(t,n){return new ct({...this._def,exactLength:{value:t,message:U.toString(n)}})}nonempty(t){return this.min(1,t)}}ct.create=(e,t)=>new ct({type:e,minLength:null,maxLength:null,exactLength:null,typeName:H.ZodArray,...J(t)});function _n(e){if(e instanceof we){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=ht.create(_n(r))}return new we({...e._def,shape:()=>t})}else return e instanceof ct?new ct({...e._def,type:_n(e.element)}):e instanceof ht?ht.create(_n(e.unwrap())):e instanceof Gt?Gt.create(_n(e.unwrap())):e instanceof _t?_t.create(e.items.map(t=>_n(t))):e}class we extends X{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=re.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==M.object){const d=this._getOrReturnCtx(t);return j(d,{code:R.invalid_type,expected:M.object,received:d.parsedType}),W}const{status:r,ctx:i}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof It&&this._def.unknownKeys==="strip"))for(const d in i.data)a.includes(d)||c.push(d);const l=[];for(const d of a){const u=s[d],f=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new gt(i,f,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof It){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")c.length>0&&(j(i,{code:R.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=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new gt(i,f,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of l){const f=await u.key,p=await u.value;d.push({key:f,value:p,alwaysSet:u.alwaysSet})}return d}).then(d=>$e.mergeObjectSync(r,d)):$e.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return U.errToObj,new we({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var i,s,a,c;const l=(a=(s=(i=this._def).errorMap)===null||s===void 0?void 0:s.call(i,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=U.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new we({...this._def,unknownKeys:"strip"})}passthrough(){return new we({...this._def,unknownKeys:"passthrough"})}extend(t){return new we({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new we({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:H.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new we({...this._def,catchall:t})}pick(t){const n={};return re.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new we({...this._def,shape:()=>n})}omit(t){const n={};return re.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new we({...this._def,shape:()=>n})}deepPartial(){return _n(this)}partial(t){const n={};return re.objectKeys(this.shape).forEach(r=>{const i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}),new we({...this._def,shape:()=>n})}required(t){const n={};return re.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof ht;)s=s._def.innerType;n[r]=s}}),new we({...this._def,shape:()=>n})}keyof(){return ud(re.objectKeys(this.shape))}}we.create=(e,t)=>new we({shape:()=>e,unknownKeys:"strip",catchall:It.create(),typeName:H.ZodObject,...J(t)});we.strictCreate=(e,t)=>new we({shape:()=>e,unknownKeys:"strict",catchall:It.create(),typeName:H.ZodObject,...J(t)});we.lazycreate=(e,t)=>new we({shape:e,unknownKeys:"strip",catchall:It.create(),typeName:H.ZodObject,...J(t)});class ur extends X{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function i(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const a=s.map(c=>new Ye(c.ctx.common.issues));return j(n,{code:R.invalid_union,unionErrors:a}),W}if(n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(i);{let s;const a=[];for(const l of r){const d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const c=a.map(l=>new Ye(l));return j(n,{code:R.invalid_union,unionErrors:c}),W}}get options(){return this._def.options}}ur.create=(e,t)=>new ur({options:e,typeName:H.ZodUnion,...J(t)});const wt=e=>e instanceof hr?wt(e.schema):e instanceof lt?wt(e.innerType()):e instanceof mr?[e.value]:e instanceof Bt?e.options:e instanceof gr?re.objectValues(e.enum):e instanceof _r?wt(e._def.innerType):e instanceof lr?[void 0]:e instanceof dr?[null]:e instanceof ht?[void 0,...wt(e.unwrap())]:e instanceof Gt?[null,...wt(e.unwrap())]:e instanceof Ao||e instanceof br?wt(e.unwrap()):e instanceof yr?wt(e._def.innerType):[];class Ei extends X{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==M.object)return j(n,{code:R.invalid_type,expected:M.object,received:n.parsedType}),W;const r=this.discriminator,i=n.data[r],s=this.optionsMap.get(i);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(j(n,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),W)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const i=new Map;for(const s of n){const a=wt(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of a){if(i.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);i.set(c,s)}}return new Ei({typeName:H.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...J(r)})}}function Gs(e,t){const n=kt(e),r=kt(t);if(e===t)return{valid:!0,data:e};if(n===M.object&&r===M.object){const i=re.objectKeys(t),s=re.objectKeys(e).filter(c=>i.indexOf(c)!==-1),a={...e,...t};for(const c of s){const l=Gs(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===M.array&&r===M.array){if(e.length!==t.length)return{valid:!1};const i=[];for(let s=0;s<e.length;s++){const a=e[s],c=t[s],l=Gs(a,c);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===M.date&&r===M.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class fr extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),i=(s,a)=>{if(Fs(s)||Fs(a))return W;const c=Gs(s.value,a.value);return c.valid?((Bs(s)||Bs(a))&&n.dirty(),{status:n.value,value:c.data}):(j(r,{code:R.invalid_intersection_types}),W)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>i(s,a)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}fr.create=(e,t,n)=>new fr({left:e,right:t,typeName:H.ZodIntersection,...J(n)});class _t extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==M.array)return j(r,{code:R.invalid_type,expected:M.array,received:r.parsedType}),W;if(r.data.length<this._def.items.length)return j(r,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&r.data.length>this._def.items.length&&(j(r,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new gt(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>$e.mergeArray(n,a)):$e.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new _t({...this._def,rest:t})}}_t.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _t({items:e,typeName:H.ZodTuple,rest:null,...J(t)})};class pr extends X{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!==M.object)return j(r,{code:R.invalid_type,expected:M.object,received:r.parsedType}),W;const i=[],s=this._def.keyType,a=this._def.valueType;for(const c in r.data)i.push({key:s._parse(new gt(r,c,r.path,c)),value:a._parse(new gt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?$e.mergeObjectAsync(n,i):$e.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof X?new pr({keyType:t,valueType:n,typeName:H.ZodRecord,...J(r)}):new pr({keyType:at.create(),valueType:t,typeName:H.ZodRecord,...J(n)})}}class fi extends X{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!==M.map)return j(r,{code:R.invalid_type,expected:M.map,received:r.parsedType}),W;const i=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:i._parse(new gt(r,c,r.path,[d,"key"])),value:s._parse(new gt(r,l,r.path,[d,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of a){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return W;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const l of a){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return W;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}fi.create=(e,t,n)=>new fi({valueType:t,keyType:e,typeName:H.ZodMap,...J(n)});class ln extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==M.set)return j(r,{code:R.invalid_type,expected:M.set,received:r.parsedType}),W;const i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(j(r,{code:R.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(j(r,{code:R.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());const s=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return W;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>s._parse(new gt(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new ln({...this._def,minSize:{value:t,message:U.toString(n)}})}max(t,n){return new ln({...this._def,maxSize:{value:t,message:U.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}ln.create=(e,t)=>new ln({valueType:e,minSize:null,maxSize:null,typeName:H.ZodSet,...J(t)});class En extends X{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==M.function)return j(n,{code:R.invalid_type,expected:M.function,received:n.parsedType}),W;function r(c,l){return ci({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ai(),Tn].filter(d=>!!d),issueData:{code:R.invalid_arguments,argumentsError:l}})}function i(c,l){return ci({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ai(),Tn].filter(d=>!!d),issueData:{code:R.invalid_return_type,returnTypeError:l}})}const s={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof An){const c=this;return Ue(async function(...l){const d=new Ye([]),u=await c._def.args.parseAsync(l,s).catch(g=>{throw d.addIssue(r(l,g)),d}),f=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(f,s).catch(g=>{throw d.addIssue(i(f,g)),d})})}else{const c=this;return Ue(function(...l){const d=c._def.args.safeParse(l,s);if(!d.success)throw new Ye([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,s);if(!f.success)throw new Ye([i(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new En({...this._def,args:_t.create(t).rest(tn.create())})}returns(t){return new En({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new En({args:t||_t.create([]).rest(tn.create()),returns:n||tn.create(),typeName:H.ZodFunction,...J(r)})}}class hr extends X{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})}}hr.create=(e,t)=>new hr({getter:e,typeName:H.ZodLazy,...J(t)});class mr extends X{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return j(n,{received:n.data,code:R.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:t.data}}get value(){return this._def.value}}mr.create=(e,t)=>new mr({value:e,typeName:H.ZodLiteral,...J(t)});function ud(e,t){return new Bt({values:e,typeName:H.ZodEnum,...J(t)})}class Bt extends X{constructor(){super(...arguments),Yn.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return j(n,{expected:re.joinValues(r),received:n.parsedType,code:R.invalid_type}),W}if(li(this,Yn)||ad(this,Yn,new Set(this._def.values)),!li(this,Yn).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return j(n,{received:n.data,code:R.invalid_enum_value,options:r}),W}return Ue(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 Bt.create(t,{...this._def,...n})}exclude(t,n=this._def){return Bt.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Yn=new WeakMap;Bt.create=ud;class gr extends X{constructor(){super(...arguments),Qn.set(this,void 0)}_parse(t){const n=re.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==M.string&&r.parsedType!==M.number){const i=re.objectValues(n);return j(r,{expected:re.joinValues(i),received:r.parsedType,code:R.invalid_type}),W}if(li(this,Qn)||ad(this,Qn,new Set(re.getValidEnumValues(this._def.values))),!li(this,Qn).has(t.data)){const i=re.objectValues(n);return j(r,{received:r.data,code:R.invalid_enum_value,options:i}),W}return Ue(t.data)}get enum(){return this._def.values}}Qn=new WeakMap;gr.create=(e,t)=>new gr({values:e,typeName:H.ZodNativeEnum,...J(t)});class An extends X{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==M.promise&&n.common.async===!1)return j(n,{code:R.invalid_type,expected:M.promise,received:n.parsedType}),W;const r=n.parsedType===M.promise?n.data:Promise.resolve(n.data);return Ue(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}}An.create=(e,t)=>new An({type:e,typeName:H.ZodPromise,...J(t)});class lt extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===H.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,s={addIssue:a=>{j(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){const a=i.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return W;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?W:l.status==="dirty"||n.value==="dirty"?vn(l.value):l});{if(n.value==="aborted")return W;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?W:c.status==="dirty"||n.value==="dirty"?vn(c.value):c}}if(i.type==="refinement"){const a=c=>{const l=i.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?W:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?W:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(i.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!an(a))return a;const c=i.transform(a.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>an(a)?Promise.resolve(i.transform(a.value,s)).then(c=>({status:n.value,value:c})):a);re.assertNever(i)}}lt.create=(e,t,n)=>new lt({schema:e,typeName:H.ZodEffects,effect:t,...J(n)});lt.createWithPreprocess=(e,t,n)=>new lt({schema:t,effect:{type:"preprocess",transform:e},typeName:H.ZodEffects,...J(n)});class ht extends X{_parse(t){return this._getType(t)===M.undefined?Ue(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ht.create=(e,t)=>new ht({innerType:e,typeName:H.ZodOptional,...J(t)});class Gt extends X{_parse(t){return this._getType(t)===M.null?Ue(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Gt.create=(e,t)=>new Gt({innerType:e,typeName:H.ZodNullable,...J(t)});class _r extends X{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===M.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}_r.create=(e,t)=>new _r({innerType:e,typeName:H.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...J(t)});class yr extends X{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ar(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ye(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ye(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}yr.create=(e,t)=>new yr({innerType:e,typeName:H.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...J(t)});class pi extends X{_parse(t){if(this._getType(t)!==M.nan){const r=this._getOrReturnCtx(t);return j(r,{code:R.invalid_type,expected:M.nan,received:r.parsedType}),W}return{status:"valid",value:t.data}}}pi.create=e=>new pi({typeName:H.ZodNaN,...J(e)});const gh=Symbol("zod_brand");class Ao extends X{_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 Cr extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?W:s.status==="dirty"?(n.dirty(),vn(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?W:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new Cr({in:t,out:n,typeName:H.ZodPipeline})}}class br extends X{_parse(t){const n=this._def.innerType._parse(t),r=i=>(an(i)&&(i.value=Object.freeze(i.value)),i);return ar(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}}br.create=(e,t)=>new br({innerType:e,typeName:H.ZodReadonly,...J(t)});function Ja(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function fd(e,t={},n){return e?Cn.create().superRefine((r,i)=>{var s,a;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=Ja(t,r),p=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;i.addIssue({code:"custom",...f,fatal:p})}});if(!c){const l=Ja(t,r),d=(a=(s=l.fatal)!==null&&s!==void 0?s:n)!==null&&a!==void 0?a:!0;i.addIssue({code:"custom",...l,fatal:d})}}):Cn.create()}const _h={object:we.lazycreate};var H;(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"})(H||(H={}));const yh=(e,t={message:`Input not instance of ${e.name}`})=>fd(n=>n instanceof e,t),pd=at.create,hd=Ut.create,bh=pi.create,vh=Ft.create,md=cr.create,wh=cn.create,Sh=di.create,kh=lr.create,Eh=dr.create,Ih=Cn.create,xh=tn.create,Rh=It.create,Th=ui.create,Ch=ct.create,Ah=we.create,Oh=we.strictCreate,Ph=ur.create,jh=Ei.create,Mh=fr.create,Dh=_t.create,Nh=pr.create,Lh=fi.create,$h=ln.create,Uh=En.create,Fh=hr.create,Bh=mr.create,Gh=Bt.create,Hh=gr.create,zh=An.create,Xa=lt.create,Wh=ht.create,Zh=Gt.create,Kh=lt.createWithPreprocess,Vh=Cr.create,Yh=()=>pd().optional(),Qh=()=>hd().optional(),Jh=()=>md().optional(),Xh={string:e=>at.create({...e,coerce:!0}),number:e=>Ut.create({...e,coerce:!0}),boolean:e=>cr.create({...e,coerce:!0}),bigint:e=>Ft.create({...e,coerce:!0}),date:e=>cn.create({...e,coerce:!0})},qh=W;var o=Object.freeze({__proto__:null,defaultErrorMap:Tn,setErrorMap:Kp,getErrorMap:ai,makeIssue:ci,EMPTY_PATH:Vp,addIssueToContext:j,ParseStatus:$e,INVALID:W,DIRTY:vn,OK:Ue,isAborted:Fs,isDirty:Bs,isValid:an,isAsync:ar,get util(){return re},get objectUtil(){return Us},ZodParsedType:M,getParsedType:kt,ZodType:X,datetimeRegex:dd,ZodString:at,ZodNumber:Ut,ZodBigInt:Ft,ZodBoolean:cr,ZodDate:cn,ZodSymbol:di,ZodUndefined:lr,ZodNull:dr,ZodAny:Cn,ZodUnknown:tn,ZodNever:It,ZodVoid:ui,ZodArray:ct,ZodObject:we,ZodUnion:ur,ZodDiscriminatedUnion:Ei,ZodIntersection:fr,ZodTuple:_t,ZodRecord:pr,ZodMap:fi,ZodSet:ln,ZodFunction:En,ZodLazy:hr,ZodLiteral:mr,ZodEnum:Bt,ZodNativeEnum:gr,ZodPromise:An,ZodEffects:lt,ZodTransformer:lt,ZodOptional:ht,ZodNullable:Gt,ZodDefault:_r,ZodCatch:yr,ZodNaN:pi,BRAND:gh,ZodBranded:Ao,ZodPipeline:Cr,ZodReadonly:br,custom:fd,Schema:X,ZodSchema:X,late:_h,get ZodFirstPartyTypeKind(){return H},coerce:Xh,any:Ih,array:Ch,bigint:vh,boolean:md,date:wh,discriminatedUnion:jh,effect:Xa,enum:Gh,function:Uh,instanceof:yh,intersection:Mh,lazy:Fh,literal:Bh,map:Lh,nan:bh,nativeEnum:Hh,never:Rh,null:Eh,nullable:Zh,number:hd,object:Ah,oboolean:Jh,onumber:Qh,optional:Wh,ostring:Yh,pipeline:Vh,preprocess:Kh,promise:zh,record:Nh,set:$h,strictObject:Oh,string:pd,symbol:Sh,transformer:Xa,tuple:Dh,undefined:kh,union:Ph,unknown:xh,void:Th,NEVER:qh,ZodIssueCode:R,quotelessJson:Zp,ZodError:Ye});const qa=o.enum(["app_start","sign_in","window_focus","surface_open"]),gd=o.object({id:o.string().min(1),state:o.enum(["active","paused","disabled"])}).passthrough(),em=o.object({tenant_id:o.string().min(1),tenant_name:o.string().optional(),eligible:o.boolean(),endpoint:gd.nullable()}).passthrough(),tm=o.object({code:o.string(),message:o.string(),details:o.record(o.unknown()).optional(),retry_after_seconds:o.number().optional()}).passthrough(),nm=o.object({code:o.string().min(1),count:o.number().int().nonnegative(),session:o.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),rm=o.object({in_force:o.boolean(),notice_pending:o.boolean().catch(!1)}).passthrough().optional().catch(void 0),LI=o.object({capability:o.number(),consent_account_guard:o.boolean().optional(),state:o.enum(["ready","signed_out","unavailable","update_required"]),account_id:o.string().nullable(),tenant_id:o.string().nullable(),surface_state:o.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:o.object({settings:o.boolean(),inbox:o.boolean(),account_door:o.boolean(),onboarding:o.boolean()}),update_required:o.boolean(),local:o.object({enabled:o.boolean(),onboarding:o.string(),session:o.string()}),status:o.object({tenants:o.array(em)}).passthrough().nullable(),consent:o.object({version:o.string().min(1).max(128),text:o.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:o.enum(["served","cached","embedded"])}).nullable(),error:tm.nullable(),state_note:o.string().nullable().optional(),read_only:o.boolean().optional(),delivery_hold:nm,default_on:rm}).passthrough(),im=o.object({version:o.string().min(1),consented_at:o.string().min(1),consented_via:o.string().min(1),current:o.boolean()}).passthrough(),$I=o.object({endpoint:gd.extend({tenant_id:o.string().min(1),label:o.string().optional(),consent:im.nullable().optional(),created_at:o.string().optional(),updated_at:o.string().optional()}).nullable(),settings:o.object({tenant_id:o.string().min(1),eligible:o.boolean(),consent_version:o.string().optional(),consent_required:o.boolean()}).passthrough(),default_on:o.boolean().optional().catch(void 0)}).passthrough(),sm=o.object({kind:o.enum(["endpoint","account"]).optional(),endpoint_id:o.string().min(1).optional(),account_id:o.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"),ec=o.object({direction:o.enum(["send","receive"]),effect:o.enum(["allow","deny"]),target:sm,id:o.string().optional()}).passthrough(),tc=o.object({mode:o.enum(["class_default","listed_only"]),allow:o.number(),deny:o.number()}).passthrough(),UI=o.object({allowlist:o.object({tenant_id:o.string().min(1),entries:o.array(ec)}).passthrough(),view:o.object({tenant_id:o.string().nullable(),entries:o.array(ec),directions:o.object({send:tc,receive:tc}),class_default:o.literal("cos_cos"),cues:o.object({allow_entry_switches_direction_to_listed_only:o.boolean(),listed_only_affects:o.string(),removing_allow_does_not_stop_open_thread:o.boolean(),deny_stops_pair_both_directions:o.boolean()}).passthrough()}).passthrough()}).passthrough(),FI=o.object({onboarding:o.literal("seen")}).passthrough();function om(e){return e?.default_on?.in_force===!0}function BI(e,t){const n=am(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function GI(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function HI(e,t){if(!e||!t||om(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 am(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const cm=8,Hs=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],lm=6*1024,dm=512;function hi(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const i=[];for(const s of n){if(i.length===dm)break;const c=new URLSearchParams({order_ids:s}).toString().length+1;if(r+c>lm)break;e.append("order_ids",s),i.push(s),r+=c}return i}function um(e,t,n){return hi(new URLSearchParams(n),t,e)}const fm=/^\.+$/,pm=new RegExp("\\p{Cf}","u"),hm=/[/\\:]/,v=o.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),Br=o.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),Gr=o.string().min(1).max(32768),mm=/^[a-f0-9]{12}$/,L=o.string().regex(mm),Xi=o.string().regex(/^[a-f0-9]{12}$/),qi=o.string().min(1).max(128),gm=o.string().min(1).max(4096),Fn=o.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),es=o.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),Hr=o.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),nc=o.string().regex(/^[a-f0-9]{32}$/),_m=/^(\/|[A-Za-z]:[\\/])/,ts=o.string().min(1).max(4096).regex(_m),rc=/^[a-f0-9]{32}$/,te=o.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),ic=o.string().min(1).max(512).nullish(),mn=o.string().regex(/^[A-Za-z0-9_-]{1,128}$/),zr=o.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),ym=["credential_finite_share","credential_inheritance"],sc=/^sha256:[0-9a-f]{64}$/,oc={operation:o.enum(ym),requestDigest:o.string().regex(sc),disclosureDigest:o.string().regex(sc)},Bn=o.string().regex(/^la_[0-9a-f]{16}$/),Gn=o.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),ac=o.object({data_b64:o.string().min(1).max(1e6),mime_type:o.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:o.string().max(4096).optional()}).strict(),bm=o.object({digest:o.string().regex(/^[0-9a-f]{32}$/),name:o.string().max(1024).optional(),mime_type:o.string().max(255).optional(),bytes:o.number().int().min(0).optional(),path:o.string().max(4096).optional()}).strict(),cc=2e5,lc=8,vm=256,wm=100,dc=16,Sm=256,km=100,Em=200,Im=1e6,xm=o.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),Me=o.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),Wr=o.object({kind:o.enum(["agent","team"]),name:Me}).strict(),_d=o.enum(["claude","codex","omp"]),Rm=o.record(o.string(),o.array(o.string().min(1).max(512)).max(5e3)),uc={sources:o.array(_d).max(3).optional(),sessionIds:Rm.optional(),all:o.boolean().optional(),includeSubagents:o.boolean().optional(),includeClearedSegments:o.boolean().optional(),includeMemory:o.boolean().optional(),includeInstructions:o.boolean().optional(),maxSessions:o.number().int().min(1).max(5e3).optional()},ns=o.object({provider:o.string().min(1).max(128),model_id:o.string().min(1).max(512),reasoning_effort:o.string().min(1).max(64).nullable(),fast_mode:o.boolean().nullable().optional()}).strict(),fc=o.object({kind:o.enum(["role","specialist"]).optional(),description:o.string().max(8e3).optional(),instructions:o.string().max(8e3).optional(),tools:o.array(o.string().min(1).max(128)).max(256).optional(),effort:o.string().max(64).optional(),delegate:o.boolean().optional(),action_class:o.enum(["reactive","proactive"]).optional()}).strict(),pc=o.object({name:o.string().min(1).max(64).optional(),description:o.string().max(8e3).optional(),manager:Me.optional(),members:o.array(o.object({role:Me,count:o.number().int().min(1).max(16),kind:o.enum(["agent","team"]),tier:o.enum(["lo","med","hi"]).nullable().optional(),effort:xm.nullable().optional()}).strict()).max(128).optional(),instructions:o.string().max(8e3).optional(),project:o.string().max(8e3).optional()}).strict(),Tm=o.record(o.array(o.string().max(1024)).max(100)),rs=o.array(v).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),Cm=o.array(o.object({kind:o.enum(["human","agent"]),account_id:v,endpoint_id:v.optional()}).strict()).max(50).refine(e=>new Set(e.map(t=>`${t.kind}:${t.account_id}:${t.endpoint_id??""}`)).size===e.length,"Duplicate mention"),hc=o.enum(["minutes","hours","days"]);function Am(e){return!fm.test(e)}const zI=e=>ni.safeParse(e).success,ni=o.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(Am),mc=o.enum(["str","int","float","bool","list","dict"]),gc=o.string().max(16384),Om=2e3,_c=o.string().min(1).max(Om),yc=o.string().min(1).max(64),Pm=o.string().min(1).max(64),jm=o.string().min(1).max(64),bc=o.object({is_active:o.boolean().nullish(),one_time:o.boolean().nullish(),start_time_utc:o.string().max(64).nullish(),end_time_utc:o.string().max(64).nullish()}).strict(),Mm=o.object({conversation_length:o.number().int().optional(),detail_length:o.number().int().optional(),max_learnings_history:o.number().int().optional(),hosting:o.string().max(256).optional(),model_name:o.string().max(1024).optional(),auto_save_conversation:o.boolean().optional()}).strict(),zs=128,vc=2e3,wc=8e3,Sc=64,kc=64,Ii=e=>[...e].length,Ws=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,Dm=e=>e===9||e===10||e===11||e===12||e===13||e===133,Nm=e=>e<=31||e>=127&&e<=159,Lm=e=>pm.test(String.fromCodePoint(e)),$m=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,Zr=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},yd=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&Ws(t[n].codePointAt(0)??0);)n++;for(;r>n&&Ws(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},Um=e=>{let t="",n=!1;for(const r of e){if(Ws(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function Fm(e){const t=yd(e);if(!t)return"must not be empty";if(Ii(t)>zs)return`must be at most ${zs} characters`;if(hm.test(t))return'must not contain "/", "\\" or ":"';if(Zr(t,$m))return"must not contain Unicode bidirectional override characters";if(Zr(t,Dm))return"must not contain whitespace";if(Zr(t,Nm))return"must not contain control characters";if(Zr(t,Lm))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 WI(e){return Um(yd(e).normalize("NFKC").toLowerCase())}function Bm(e){return e.trim()?Ii(e)>vc?`must be at most ${vc} characters`:null:"must not be empty"}function Gm(e){return e.trim()?Ii(e)>wc?`must be at most ${wc} characters`:null:"must not be empty"}function Hm(e){if(e.length>kc)return`must hold at most ${kc} items`;for(const t of e)if(!t.trim()||Ii(t)>Sc)return`must hold items of 1 to ${Sc} characters`;return null}const zm=e=>Fm(e)===null,Wm=o.string().refine(zm,{message:"That is not a name the hub can publish."}),Zm=o.string().refine(e=>Gm(e)===null,{message:"That instruction body cannot be published."}),Km=o.string().refine(e=>Bm(e)===null,{message:"That description cannot be published."}),Vm=o.array(o.string()).refine(e=>Hm(e)===null,{message:"That tool list cannot be published."}),is={requestId:te.optional(),subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()},Ec=o.object({name:Wm,description:Km,instructions:Zm,kind:o.enum(["role","specialist"]),when_to_use:o.string(),tools:Vm,effort:o.string(),delegate:o.boolean(),version:o.string(),categories:o.array(o.string()),tags:o.array(o.string())}).partial().strict(),Ym=o.enum(["team","agent"]),Qm=o.string().min(1).max(64),Jm=o.string().min(1).max(256),bd=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ss=o.string().regex(bd,{message:"Letters, digits, dot, underscore and dash; no spaces."}),Xm=["planning","active","qa","validation","done","paused","archived"],Ic=o.enum(Xm),Kr=o.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),xc=o.array(o.string().min(1).max(24)).max(8),Mt=o.string().min(1).max(64),qm=1e3,Rc=240,Tc=80,eg=256,tg=100,ng=200,rg=/^[a-z0-9][a-z0-9_-]{0,23}$/;function ZI(e){return e?bd.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 KI(e){return rg.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const Vr=o.enum(["agent","team","skill"]),os=o.string().min(1).max(128).regex(/\S/),Cc=o.enum(Hs),ig=o.object({visible:o.array(Cc).max(Hs.length),more:o.array(Cc).max(Hs.length)}).strict(),Et=o.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),Ac=o.object({selectionToken:o.string().min(1).max(512),reconcileIds:o.array(Et).max(500).optional(),excludedIds:o.array(Et).max(500).optional()}).strict(),sg=o.object({operationToken:o.string().min(1).max(512),reconcileIds:o.array(Et).max(500).optional()}).strict(),Oc=o.union([o.object({throughSeq:o.number().int().min(0).optional(),receipt:o.literal(!0).optional(),reconcileIds:o.array(Et).max(500).optional(),items:o.array(o.object({id:Et,revision:o.number().int().min(1)}).strict()).min(1).max(500)}).strict(),o.object({sessionId:L,throughSeq:o.number().int().min(0),observed:o.array(o.object({id:Et,revision:o.number().int().min(1)}).strict()).max(500)}).strict(),o.object({all:o.literal(!0),throughSeq:o.number().int().min(0),observed:o.array(o.object({id:Et,revision:o.number().int().min(1)}).strict()).max(500)}).strict()]),og={pointer:"pointerdown",key:"keydown",wheel:"wheel"},ag=o.discriminatedUnion("op",[o.object({op:o.literal("capabilities")}).strict(),o.object({op:o.literal("runtimes.list")}).strict(),o.object({op:o.literal("profiles.list")}).strict(),o.object({op:o.literal("profiles.get"),name:Me}).strict(),o.object({op:o.literal("imports.sources")}).strict(),o.object({op:o.literal("imports.sessions"),source:_d,includeSubagents:o.boolean().optional()}).strict(),o.object({op:o.literal("imports.preview"),...uc}).strict(),o.object({op:o.literal("imports.start"),...uc}).strict(),o.object({op:o.literal("imports.status"),jobId:o.string().min(1).max(128)}).strict(),o.object({op:o.literal("imports.cancel"),jobId:o.string().min(1).max(128)}).strict(),o.object({op:o.literal("profiles.update"),name:Me,requestId:te,fields:fc,expectedDefinitionRevision:ic.optional()}).strict(),o.object({op:o.literal("profiles.install"),name:Me,requestId:te}).strict(),o.object({op:o.literal("profiles.create"),name:Me,requestId:te,fields:fc.extend({description:o.string().max(8e3),instructions:o.string().min(1).max(8e3)})}).strict(),o.object({op:o.literal("hub.updates")}).strict(),o.object({op:o.literal("hub.skillPull"),requestId:te,hubId:v,hubSource:o.string().min(1).max(2048),visibility:o.enum(["public","org"]),tenantId:v.nullable(),localAlias:Me,subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional(),dryRun:o.boolean().optional(),adoptionStrategy:o.enum(["merge","keep-local","take-hub"]).optional(),allowLlm:o.boolean().optional(),confirm:o.boolean().optional(),adoptionReceipt:o.string().min(16).max(128).optional()}).strict(),o.object({op:o.literal("hub.skillSubscribe"),requestId:te,hubId:v,hubSource:o.string().min(1).max(2048),visibility:o.enum(["public","org"]),tenantId:v.nullable(),localAlias:Me}).strict(),o.object({op:o.literal("hub.skillUnpull"),requestId:te,linkId:o.string().min(1).max(256)}).strict(),o.object({op:o.literal("hub.skillPublish"),requestId:te,dryRun:o.boolean(),sourceSkill:Me,localAlias:Me,visibility:o.enum(["public","org"]),tenantId:v.nullable(),subscribe:o.boolean(),autoPush:o.boolean(),confirmPublicEgress:o.boolean(),previewReceipt:o.string().min(1).max(4096).optional(),confirmPublish:o.literal(!0).optional()}).strict(),o.object({op:o.literal("hub.links"),kind:o.enum(["agent","team","skill"]).optional()}).strict(),o.object({op:o.literal("hub.policy"),requestId:te,linkId:o.string().min(1).max(256),expectedPolicyRevision:o.string().min(1).max(256),subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()}).strict(),o.object({op:o.literal("hub.check"),requestId:te,kind:Vr.optional(),name:Me.optional(),localId:os.optional()}).strict(),o.object({op:o.literal("hub.apply"),requestId:te,kind:Vr.optional(),name:Me.optional(),localId:os.optional(),prefer:o.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:o.boolean().optional(),dryRun:o.boolean().optional(),resolveSource:o.literal(!0).optional(),hubSource:o.string().min(1).max(2048).optional(),visibility:o.enum(["public","org"]).optional(),tenantId:o.string().min(1).max(128).nullable().optional()}).strict(),o.object({op:o.literal("hub.applyAll"),requestId:te,kind:Vr.optional()}).strict(),o.object({op:o.literal("hub.retry"),requestId:te,kind:Vr.optional(),name:Me.optional(),localId:os.optional()}).strict(),o.object({op:o.literal("hub.push"),requestId:te,linkId:o.string().min(1).max(256),direction:o.literal("push"),dryRun:o.boolean(),previewReceipt:o.string().min(1).max(4096).optional(),confirmPublish:o.literal(!0).optional()}).strict(),o.object({op:o.literal("teams.list")}).strict(),o.object({op:o.literal("teams.get"),name:Me}).strict(),o.object({op:o.literal("teams.effective"),name:Me}).strict(),o.object({op:o.literal("teams.update"),name:Me,requestId:te,fields:pc,expectedDefinitionRevision:ic.optional()}).strict(),o.object({op:o.literal("teams.create"),requestId:te,fields:pc.extend({name:o.string().min(1).max(64)})}).strict(),o.object({op:o.literal("sessions.list"),limit:o.number().int().min(1).max(500).optional(),include_archived:o.boolean().optional(),include_peers:o.boolean().optional(),scope_kind:Ym.optional(),scope_name:Qm.optional(),cursor:Jm.optional(),with_counts:o.boolean().optional(),sort:o.literal("activity").optional()}).strict(),o.object({op:o.literal("delegated_cleanup_notice.ack")}).strict(),o.object({op:o.literal("sessions.search"),q:o.string().min(1).max(vm),limit:o.number().int().min(1).max(500).optional(),include_archived:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.archive"),sessionId:L,archived:o.boolean()}).strict(),o.object({op:o.literal("sessions.delete"),sessionId:L,confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.create"),requestId:te,cwd:o.string().min(1).max(4096).optional(),target:Wr.optional(),purpose:o.literal("agents-config").optional(),model:ns.optional(),draftId:L.optional(),peer:mn.optional()}).strict(),o.object({op:o.literal("sessions.preview"),requestId:te,cwd:o.string().min(1).max(4096),target:Wr.optional(),model:ns.optional()}).strict(),o.object({op:o.literal("sessions.draft"),requestId:te,cwd:o.string().min(1).max(4096),target:Wr.optional(),model:ns.optional()}).strict(),o.object({op:o.literal("sessions.get"),sessionId:L,journalOrder:o.boolean().optional(),orderIds:o.array(o.string().min(1).max(128)).max(512).optional(),peerJournalSource:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.files"),sessionId:L,scope:o.enum(["family","self"]).optional(),kind:o.string().max(256).optional(),q:o.string().max(256).optional(),sort:o.enum(["recent","name","kind","modified","created","size"]).optional(),order:o.enum(["asc","desc"]).optional(),limit:o.number().int().min(1).max(200).optional(),cursor:o.string().max(8192).optional()}).strict(),o.object({op:o.literal("sessions.files.materialise"),sessionId:L,fileId:o.string().regex(/^[a-f0-9]{16}$/)}).strict(),o.object({op:o.literal("sessions.userAttachments"),sessionId:L}).strict(),o.object({op:o.literal("sessions.userAttachments.materialise"),sessionId:L,digest:o.string().regex(/^[a-f0-9]{32}$/)}).strict(),o.object({op:o.literal("sessions.history"),sessionId:L,beforeId:v.optional(),limit:o.number().int().min(1).max(500).optional(),openFrame:o.boolean().optional(),journalOrder:o.boolean().optional(),orderIds:o.array(o.string().min(1).max(128)).max(512).optional(),peerJournalSource:o.boolean().optional(),sourceRead:o.enum(["metadata","payload"]).optional(),expectedJournalGeneration:o.string().min(1).max(128).optional()}).strict(),o.object({op:o.literal("sessions.checkpoints"),sessionId:L}).strict(),o.object({op:o.literal("sessions.checkpoints.warm"),sessionId:L,ids:o.array(v).max(dc).optional(),limit:o.number().int().min(1).max(dc).optional()}).strict(),o.object({op:o.literal("sessions.find"),sessionId:L,q:o.string().min(1).max(Sm),limit:o.number().int().min(1).max(Em).optional()}).strict(),o.object({op:o.literal("subagents.transcript"),sessionId:L,childId:L,beforeId:v.optional(),limit:o.number().int().min(1).max(500).optional()}).strict(),o.object({op:o.literal("sessions.message"),sessionId:L,requestId:te,text:o.string().max(cc),images:o.array(ac).max(lc).optional(),files:o.array(bm).max(cm).optional(),mode:o.enum(["prompt","steer"]).optional(),inputMode:o.enum(["typed","dictated","mixed"]).optional(),inputPath:o.string().max(1024).optional()}).strict(),o.object({op:o.literal("sessions.command"),sessionId:L,requestId:te,command:o.string().regex(/^\/?[A-Za-z]+$/).max(64),args:o.string().max(cc).optional(),images:o.array(ac).max(lc).optional()}).strict(),o.object({op:o.literal("sessions.move"),sessionId:L,requestId:te,cwd:o.string().min(1).max(4096)}).strict(),o.object({op:o.literal("sessions.answer"),sessionId:L,epoch:v.optional(),requestId:v.optional(),value:o.string().max(32768).optional(),approved:o.boolean().optional(),questionIndex:o.number().int().min(0).optional(),askId:v.optional(),answers:o.record(o.string(),o.array(o.string().max(32768))).optional(),decline:o.boolean().optional(),revise:o.boolean().optional(),dismiss:o.boolean().optional(),reason:o.enum(["answered_in_chat","moot"]).optional()}).strict(),o.object({op:o.literal("sessions.seen"),sessionId:L,completionToken:o.string().uuid()}).strict(),o.object({op:o.literal("attention.seen"),items:o.array(o.object({sessionId:L,completionToken:o.string().uuid()}).strict()).min(1).max(500)}).strict(),o.object({op:o.literal("sessions.notified"),sessionId:L,completionToken:o.string().uuid()}).strict(),o.object({op:o.literal("tags.list")}).strict(),o.object({op:o.literal("tags.replace"),tags:o.array(o.object({id:o.string().optional(),name:o.string()}).strict())}).strict(),o.object({op:o.literal("sessions.tags"),expected_revision:o.string().optional(),sessionId:L,tags:o.array(o.string()),primary:o.string().nullable()}).strict(),o.object({op:o.literal("sessions.pin"),sessionId:L,pinned:o.boolean()}).strict(),o.object({op:o.literal("sessions.watch"),sessionId:L,subscriptionId:o.string().regex(rc),visible:o.boolean(),canNotify:o.boolean()}).strict(),o.object({op:o.literal("sessions.warm"),sessionId:L}).strict(),o.object({op:o.literal("sessions.interrupt"),sessionId:L,requestId:te}).strict(),o.object({op:o.literal("supplements.cancel"),sessionId:L,job:Xi,anchor:qi}).strict(),o.object({op:o.literal("supplements.restart"),sessionId:L,job:Xi,anchor:qi}).strict(),o.object({op:o.literal("supplements.steer"),sessionId:L,job:Xi,anchor:qi,text:o.string().min(1).max(500)}).strict(),o.object({op:o.literal("sessions.variables.list"),sessionId:L}).strict(),o.object({op:o.literal("sessions.variables.create"),sessionId:L,key:ni,value:gc,type:mc}).strict(),o.object({op:o.literal("sessions.variables.update"),sessionId:L,key:ni,value:gc,type:mc}).strict(),o.object({op:o.literal("sessions.variables.delete"),sessionId:L,key:ni}).strict(),o.object({op:o.literal("sessions.presence"),subscriptionId:o.string().regex(/^[a-f0-9]{1,64}$/),canNotify:o.boolean(),canNotifyKinds:o.array(o.enum(["complete","error"])).max(4),sessionId:o.string().regex(/^([a-f0-9]{12})?$/),window:o.object({exists:o.boolean(),focused:o.boolean(),visible:o.boolean(),minimized:o.boolean()}).strict()}).strict(),o.object({op:o.literal("legacy.models"),provider:o.string().max(128).optional(),sort:o.enum(["id","name","provider","recommended"]).optional(),direction:o.enum(["ascending","descending"]).optional()}).strict(),o.object({op:o.literal("legacy.models.providers")}).strict(),o.object({op:o.literal("auth.probe"),provider:v}).strict(),o.object({op:o.literal("legacy.agent.upload"),agentId:v}).strict(),o.object({op:o.literal("agent.publish"),agentId:v,document:Ec.optional(),...is,visibility:o.literal("org").optional(),tenantId:v.optional()}).strict(),o.object({op:o.literal("agent.republish"),agentId:v,hubAgentId:v,expectedRemoteRevision:o.string().min(1).max(512).optional(),document:Ec.optional(),...is,visibility:o.literal("org").optional(),tenantId:v.optional()}).strict(),o.object({op:o.literal("team.publish"),teamId:v,...is,visibility:o.literal("org").optional(),tenantId:v.optional()}).strict(),o.object({op:o.literal("team.pull"),teamId:v,tenantId:v.optional()}).strict(),o.object({op:o.literal("agent.nameAvailability"),name:o.string().min(1).max(zs)}).strict(),o.object({op:o.literal("legacy.agents.list"),page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(500).optional(),name:o.string().max(256).optional(),sort:o.string().max(64).optional(),direction:o.enum(["asc","desc"]).optional()}).strict(),o.object({op:o.literal("legacy.agent.get"),agentId:v}).strict(),o.object({op:o.literal("legacy.agent.history"),agentId:v,page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(500).optional()}).strict(),o.object({op:o.literal("legacy.jobs.list"),agentId:v.optional(),status:o.string().max(64).optional()}).strict(),o.object({op:o.literal("legacy.job.get"),jobId:v}).strict(),o.object({op:o.literal("legacy.schedules.list"),page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("legacy.agent.schedules.list"),agentId:v,page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("legacy.agent.schedule.create"),agentId:v,schedule:bc.extend({prompt:o.string().max(64e3),interval:o.number().int().min(1),unit:hc})}).strict(),o.object({op:o.literal("legacy.schedule.get"),scheduleId:v}).strict(),o.object({op:o.literal("legacy.schedule.edit"),scheduleId:v,schedule:bc.extend({prompt:o.string().max(64e3).nullish(),interval:o.number().int().min(1).nullish(),unit:hc.nullish()})}).strict(),o.object({op:o.literal("legacy.schedule.remove"),scheduleId:v}).strict(),o.object({op:o.literal("legacy.agent.create"),agent:o.record(o.unknown())}).strict(),o.object({op:o.literal("legacy.agent.update"),agentId:v,update:o.record(o.unknown())}).strict(),o.object({op:o.literal("legacy.agent.delete"),agentId:v}).strict(),o.object({op:o.literal("legacy.agent.conversation.clear"),agentId:v}).strict(),o.object({op:o.literal("legacy.agent.systemPrompt.get"),agentId:v}).strict(),o.object({op:o.literal("legacy.agent.systemPrompt.update"),agentId:v,systemPrompt:o.string().max(Im)}).strict(),o.object({op:o.literal("legacy.agent.download"),agentId:v}).strict(),o.object({op:o.literal("legacy.job.cancel"),jobId:v}).strict(),o.object({op:o.literal("commands.list")}).strict(),o.object({op:o.literal("commands.entities"),sessionId:L,command:v,name:o.string().max(128).optional()}).strict(),o.object({op:o.literal("models.catalogue"),live:o.boolean().optional(),scope:o.enum(["usable","all"]).optional()}).strict(),o.object({op:o.literal("usage.get"),provider:v.optional(),live:o.boolean().optional(),refresh:o.boolean().optional()}).strict(),o.object({op:o.literal("quota.notice"),provider:v.optional(),model:o.string().min(1).max(200).optional(),refresh:o.boolean().optional()}).strict(),o.object({op:o.literal("analytics.get"),sessionId:L.optional(),sinceMs:o.number().int().nonnegative().optional(),untilMs:o.number().int().nonnegative().optional(),days:o.number().int().min(1).max(366).optional()}).strict(),o.object({op:o.literal("analytics.models"),sessionId:L.optional(),sinceMs:o.number().int().nonnegative().optional(),untilMs:o.number().int().nonnegative().optional(),days:o.number().int().min(1).max(366).optional()}).strict(),o.object({op:o.literal("info.get")}).strict(),o.object({op:o.literal("sessions.report"),sessionId:L,recentLimit:o.number().int().min(0).max(50).optional()}).strict(),o.object({op:o.literal("skills.list"),sessionId:L.optional(),cwd:gm.optional(),name:Fn.optional()}).strict(),o.object({op:o.literal("skills.create"),requestId:te,name:Fn,copyFrom:Fn}).strict(),o.object({op:o.literal("skills.update"),requestId:te,name:Fn,expectedFingerprint:o.string().regex(/^[a-f0-9]{64}$/),files:o.array(o.object({path:o.string().min(1).max(240),content:o.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),o.object({op:o.literal("skills.remove"),requestId:te,name:Fn,discardLocalChanges:o.boolean()}).strict(),o.object({op:o.literal("sessions.failovers"),sessionId:L}).strict(),o.object({op:o.literal("sessions.credential"),sessionId:L,action:o.enum(["list","store","forget"]),key:Br.optional(),value:Gr.optional(),confirmed:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.fork"),sessionId:L,requestId:te,message:o.string().max(2e5).optional(),boundary:o.enum(["next_safe","at_entry"]).optional(),entryId:o.string().max(128).optional(),autoTag:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.stop"),requestId:te,targets:o.array(L).min(1).max(100),confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.aside"),sessionId:L,requestId:te,text:o.string().min(1).max(32768),asideId:te.optional(),subscriptionId:o.string().regex(rc).optional()}).strict(),o.object({op:o.literal("sessions.adopt"),sessionId:L,requestId:te,asideId:te,confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.aside.get"),sessionId:L,asideId:te}).strict(),o.object({op:o.literal("sessions.aside.close"),sessionId:L,asideId:te}).strict(),o.object({op:o.literal("wakes.list"),limit:o.number().int().min(1).max(500).optional(),includeDormant:o.boolean().optional()}).strict(),o.object({op:o.literal("wakes.create"),requestId:te,sessionId:L.optional(),cwd:o.string().min(1).max(4096).optional(),target:Wr.optional(),message:_c,in:o.string().min(1).max(64).optional(),at:o.string().min(1).max(64).optional(),every:o.string().min(1).max(64).optional(),until:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).optional(),title:o.string().min(1).max(200).optional()}).strict(),o.object({op:o.literal("wakes.edit"),sessionId:L,wakeId:yc,message:_c.optional(),in:o.string().min(1).max(64).optional(),at:o.string().min(1).max(64).optional(),every:o.string().min(1).max(64).optional(),until:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).optional()}).strict(),o.object({op:o.literal("wakes.remove"),sessionId:L,wakeId:yc}).strict(),o.object({op:o.literal("monitors.cancel"),sessionId:L,monitorId:Pm}).strict(),o.object({op:o.literal("jobs.cancel"),sessionId:L,jobId:jm}).strict(),o.object({op:o.literal("mcp.list"),sessionId:L}).strict(),o.object({op:o.literal("mcp.credentials.store"),sessionId:L,name:o.string().min(1).max(256),values:o.record(o.string().min(1).max(128),o.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:o.array(o.string().min(1).max(128)).max(32)}).strict(),o.object({op:o.literal("mcp.control"),sessionId:L,control:o.object({action:o.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:es.optional(),scope:o.enum(["global","project"]).optional(),command:o.string().min(1).max(4096).optional(),args:o.array(o.string().max(8192)).max(128).optional(),env:o.record(Hr).optional(),url:o.string().max(4096).optional(),headers:o.record(Hr).optional(),oauth:o.boolean().optional(),confirmed:o.boolean().optional(),operation_id:nc.optional()}).strict()}).strict(),o.object({op:o.literal("mcp.catalog"),cwd:ts.optional(),sessionId:L.optional()}).strict(),o.object({op:o.literal("mcp.catalog.control"),cwd:ts.optional(),control:o.object({action:o.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:es.optional(),scope:o.enum(["global","project"]).optional(),command:o.string().min(1).max(4096).optional(),args:o.array(o.string().max(8192)).max(128).optional(),env:o.record(Hr).optional(),url:o.string().max(4096).optional(),headers:o.record(Hr).optional(),confirmed:o.boolean().optional(),operation_id:nc.optional()}).strict()}).strict(),o.object({op:o.literal("mcp.catalog.credentials"),header:o.string().min(1).max(128).optional(),cwd:ts.optional(),name:es,values:o.record(o.string().min(1).max(128),o.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:o.array(o.string().min(1).max(128)).max(32)}).strict(),o.object({op:o.literal("radient.request"),control:o.object({operation:o.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"]),request_id:te.optional(),tenant_id:v.optional(),account_id:v.optional(),agent_id:v.optional(),comment_id:v.optional(),team_id:v.optional(),skill_id:v.optional(),query:o.record(o.union([o.string().max(1024),o.number().int()])).optional(),payload:o.record(o.unknown()).optional(),confirmed:o.boolean().optional()}).strict()}).strict(),o.object({op:o.literal("providers.list")}).strict(),o.object({op:o.literal("accounts.list")}).strict(),o.object({op:o.literal("accounts.remove"),accountId:o.number().int().positive(),confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("tunnel.setup.read"),credentialId:o.number().int().positive().optional()}).strict(),o.object({op:o.literal("tunnel.setup.plan"),credentialId:o.number().int().positive().optional()}).strict(),o.object({op:o.literal("tunnel.setup.run"),credentialId:o.number().int().positive(),acceptMonthlyPrice:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("auth.start"),provider:v}).strict(),o.object({op:o.literal("auth.status"),id:v}).strict(),o.object({op:o.literal("auth.input"),id:v,promptId:v,value:Gr}).strict(),o.object({op:o.literal("auth.cancel"),id:v}).strict(),o.object({op:o.literal("auth.key"),provider:v,value:Gr}).strict(),o.object({op:o.literal("auth.logout"),provider:v}).strict(),o.object({op:o.literal("agent_messages.status"),boundary:qa}).strict(),o.object({op:o.literal("agent_messages.enable"),expected_account_id:v,tenant_id:v,state:o.literal("active"),consent_version:o.string().min(1).max(128),consented_via:o.literal("dialog")}).strict(),o.object({op:o.literal("agent_messages.settings"),tenant_id:v.optional()}).strict(),o.object({op:o.literal("agent_messages.settings.put"),expected_account_id:v,tenant_id:v.optional(),consent_version:o.string().min(1).max(128).optional(),consented_via:o.enum(["dialog","settings"]).optional(),label:o.string().min(1).max(128).optional(),state:o.enum(["active","paused","disabled"])}).strict(),o.object({op:o.literal("agent_messages.onboarding.dismiss")}).strict(),o.object({op:o.literal("agent_messages.allowlist.get"),tenant_id:v.optional()}).strict(),o.object({op:o.literal("agent_messages.allowlist.put"),expected_account_id:v,tenant_id:v.optional(),entries:o.array(o.object({direction:o.enum(["send","receive"]),effect:o.enum(["allow","deny"]),target:o.object({endpoint_id:v.optional(),account_id:v.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(),o.object({op:o.literal("team_bridge.conversations.list"),scope:o.literal("account").optional(),tenant_id:v.optional(),limit:o.number().int().min(1).max(100).optional(),cursor:o.string().min(1).max(512).optional(),before:o.string().min(1).max(64).optional(),status:o.enum(["open","archived"]).optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.get"),conversation_id:v,tenant_id:v.optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.create"),expected_account_id:v.optional(),tenant_id:v.optional(),kind:o.enum(["dm","group","channel"]),name:o.string().min(1).max(128).optional(),topic:o.string().min(1).max(512).optional(),visibility:o.enum(["private","tenant"]).optional(),agent_capable:o.boolean().optional(),members:o.array(o.object({account_id:v,kind:o.enum(["human","agent"]),endpoint_id:v.optional(),display_label:o.string().min(1).max(64)}).strict()).max(500)}).strict(),o.object({op:o.literal("team_bridge.conversations.lifecycle"),expected_account_id:v.optional(),tenant_id:v.optional(),conversation_id:v,action:o.enum(["archive","unarchive","join","leave"])}).strict(),o.object({op:o.literal("team_bridge.conversations.join"),expected_account_id:v.optional(),conversation_id:v,tenant_id:v.optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.notify"),expected_account_id:v.optional(),conversation_id:v,tenant_id:v.optional(),notify:o.enum(["all","mention","mute"])}).strict(),o.object({op:o.literal("team_bridge.conversations.agent_notify"),expected_account_id:v.optional(),conversation_id:v,tenant_id:v.optional(),notify:o.enum(["all","mention","mute"])}).strict(),o.object({op:o.literal("team_bridge.conversations.members.add"),expected_account_id:v.optional(),conversation_id:v,tenant_id:v.optional(),members:o.array(o.object({account_id:v,kind:o.enum(["human","agent"]),endpoint_id:v.optional(),display_label:o.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),o.object({op:o.literal("team_bridge.conversations.members.remove"),expected_account_id:v.optional(),tenant_id:v.optional(),conversation_id:v,account_id:v}).strict(),o.object({op:o.literal("team_bridge.conversations.delete"),expected_account_id:v.optional(),tenant_id:v.optional(),conversation_id:v}).strict(),o.object({op:o.literal("team_bridge.conversations.consent"),expected_account_id:v.optional(),conversation_id:v,account_id:v,decision:o.enum(["accept","decline"]),consent_version:o.string().min(1).max(128),tenant_id:v.optional()}).strict(),o.object({op:o.literal("team_bridge.owner_audit.conversations"),expected_account_id:v,tenant_id:v,limit:o.number().int().min(1).max(100).optional(),cursor:o.string().min(1).optional()}).strict(),o.object({op:o.literal("team_bridge.owner_audit.messages"),expected_account_id:v,tenant_id:v,conversation_id:v,limit:o.number().int().min(1).max(100).optional(),before_seq:o.number().int().nonnegative().optional()}).strict(),o.object({op:o.literal("team_bridge.owner_audit.replies"),expected_account_id:v,tenant_id:v,conversation_id:v,message_id:v,limit:o.number().int().min(1).max(100).optional(),after_seq:o.number().int().nonnegative().optional(),before_seq:o.number().int().positive().optional(),order:o.enum(["asc","desc"]).optional()}).strict(),o.object({op:o.literal("team_bridge.messages.list"),conversation_id:v,tenant_id:v.optional(),limit:o.number().int().min(1).max(100).optional(),before_seq:o.number().int().nonnegative().optional(),endpoint_id:v.optional()}).strict(),o.object({op:o.literal("team_bridge.reactions.toggle"),conversation_id:v,message_id:v,expected_account_id:v,tenant_id:v,emoji:o.string().min(1),active:o.boolean()}).strict(),o.object({op:o.literal("team_bridge.messages.send"),expected_account_id:v.optional(),conversation_id:v,tenant_id:v.optional(),client_ref:v,body:o.string(),agent_label:o.string().min(1).max(64).optional(),thread_root_id:v.optional(),attachment_ids:rs.optional(),mentions:Cm.optional()}).strict(),o.object({op:o.literal("team_bridge.messages.replies"),conversation_id:v,message_id:v,expected_account_id:v,tenant_id:v,limit:o.number().int().min(1).max(100).optional(),after_seq:o.number().int().nonnegative().optional(),before_seq:o.number().int().positive().optional(),order:o.enum(["asc","desc"]).optional()}).strict(),o.object({op:o.literal("team_bridge.scheduled.list"),tenant_id:v}).strict(),o.object({op:o.literal("team_bridge.scheduled.create"),tenant_id:v,conversation_id:v,client_ref:v,body:o.string(),send_at:o.string().datetime({offset:!0}),attachment_ids:rs.optional(),thread_root_id:v.optional()}).strict(),o.object({op:o.literal("team_bridge.scheduled.update"),tenant_id:v,scheduled_id:v,body:o.string().optional(),send_at:o.string().datetime({offset:!0}).optional(),attachment_ids:rs.optional(),expected_version:o.number().int().nonnegative().optional()}).strict(),o.object({op:o.literal("team_bridge.attachments.delete"),tenant_id:v,conversation_id:v,attachment_id:v,expected_account_id:v}).strict(),o.object({op:o.literal("team_bridge.scheduled.cancel"),tenant_id:v,scheduled_id:v}).strict(),o.object({op:o.literal("team_bridge.read"),expected_account_id:v.optional(),conversation_id:v,tenant_id:v.optional(),seq:o.number().int().nonnegative().optional(),muted:o.boolean().optional()}).strict(),o.object({op:o.literal("team_bridge.unread"),scope:o.literal("account").optional(),tenant_id:v.optional()}).strict(),o.object({op:o.literal("team_bridge.directory"),tenant_id:v}).strict(),o.object({op:o.literal("team_bridge.status"),boundary:qa.optional()}).strict(),o.object({op:o.literal("settings.list")}).strict(),o.object({op:o.literal("settings.edit"),key:Br,value:o.unknown().refine(e=>e!==void 0,"A setting value is required."),base:Tm.optional()}).strict(),o.object({op:o.literal("settings.reset"),key:Br}).strict(),o.object({op:o.literal("tts.paths")}).strict(),o.object({op:o.literal("config.get")}).strict(),o.object({op:o.literal("config.update"),value:Mm}).strict(),o.object({op:o.literal("instructions.get")}).strict(),o.object({op:o.literal("instructions.update"),content:o.string().max(64e3)}).strict(),o.object({op:o.literal("credentials.list")}).strict(),o.object({op:o.literal("credentials.update"),key:Br,value:Gr}).strict(),o.object({op:o.literal("peers.list")}).strict(),o.object({op:o.literal("networks.list")}).strict(),o.object({op:o.literal("networks.invite"),networkId:mn,role:o.enum(["read","drive","admin"]),deviceId:mn.optional()}).strict(),o.object({op:o.literal("networks.member.remove"),networkId:mn,deviceId:mn,confirm:o.string().min(1).max(256)}).strict(),o.object({op:o.literal("sessions.transfer"),sessionId:L,to:o.union([o.literal("local"),mn]),keep:o.boolean().optional(),waitS:o.number().min(0).max(300).optional(),requestId:te.optional()}).strict(),o.object({op:o.literal("approvals.list")}).strict(),o.object({op:o.literal("approvals.approve"),approvalId:zr}).strict(),o.object({op:o.literal("approvals.deny"),approvalId:zr}).strict(),o.object({op:o.literal("approvals.approveCredential"),approvalId:zr,...oc}).strict(),o.object({op:o.literal("approvals.applyCredential"),approvalId:zr,...oc}).strict(),o.object({op:o.literal("asks.list")}).strict(),o.object({op:o.literal("projects.list")}).strict(),o.object({op:o.literal("projects.get"),key:Mt}).strict(),o.object({op:o.literal("projects.create"),name:ss,description:o.string().max(Rc).optional(),status:Ic.optional(),tags:xc.optional()}).strict(),o.object({op:o.literal("projects.update"),key:Mt,fields:o.object({name:ss.optional(),title:o.string().max(80).optional(),owner:o.string().max(80).optional(),team:o.string().max(80).optional(),description:o.string().max(Rc).optional(),status:Ic.optional(),progress:o.string().max(qm).optional(),tags:xc.optional(),start_date:Kr.optional(),target_date:Kr.optional(),completed_at:Kr.optional(),estimate:o.number().positive().max(1e3).optional(),estimate_unit:o.enum(["points","days"]).optional()}).strict(),force_done:o.boolean().optional()}).strict(),o.object({op:o.literal("projects.delete"),key:Mt,confirmed_name:ss}).strict(),o.object({op:o.literal("projects.link"),key:Mt,sessionId:L}).strict(),o.object({op:o.literal("projects.unlink"),key:Mt,sessionId:L}).strict(),o.object({op:o.literal("projects.milestone"),key:Mt,name:o.string().min(1).max(Tc),targetDate:Kr.optional(),completed:o.boolean().optional()}).strict(),o.object({op:o.literal("projects.milestone.remove"),key:Mt,name:o.string().min(1).max(Tc)}).strict(),o.object({op:o.literal("projects.request_update"),key:Mt}).strict(),o.object({op:o.literal("projects.search"),q:o.string().min(1).max(eg),limit:o.number().int().min(1).max(ng).optional()}).strict(),o.object({op:o.literal("aida.status")}).strict(),o.object({op:o.literal("aida.control"),action:o.enum(["open","pause","resume","greet","status"])}).strict(),o.object({op:o.literal("code_requests.list"),sessionId:L}).strict(),o.object({op:o.literal("code_requests.refresh"),sessionId:L,keys:o.array(o.string().min(1).max(512)).max(256).optional(),force:o.boolean().optional()}).strict(),o.object({op:o.literal("static.sign"),route:o.enum(["images","videos","audio","html"]),path:o.string().min(1),ttlS:o.number().int().min(1).max(3600).optional()}).strict(),o.object({op:o.literal("library.list"),scope:o.enum(["final","all"]).optional(),q:o.string().max(512).optional(),category:o.string().min(1).max(64).optional(),kind:o.string().min(1).max(64).optional(),origin_group:o.enum(["generated","created","mentioned"]).optional(),origin:o.string().min(1).max(64).optional(),tag:o.string().min(1).max(128).optional(),tag_mode:o.enum(["all","any"]).optional(),highlighted:o.boolean().optional(),organized:o.boolean().optional(),favorite:o.boolean().optional(),session:o.string().min(1).max(12).optional(),session_id:o.string().min(1).max(512).optional(),sort:o.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:o.enum(["asc","desc"]).optional(),limit:o.number().int().min(1).max(200).optional(),cursor:o.string().max(512).optional()}).strict(),o.object({op:o.literal("library.get"),id:Bn}).strict(),o.object({op:o.literal("library.update"),id:Bn,fields:o.object({name:o.string().max(200).optional(),description:o.string().max(2e3).optional(),favorite:o.boolean().optional(),locked:o.boolean().optional(),archived:o.boolean().optional()}).strict()}).strict(),o.object({op:o.literal("library.tags")}).strict(),o.object({op:o.literal("library.tags.create"),name:o.string().trim().min(1).max(24),category:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("library.tags.update"),id:Gn,name:o.string().trim().min(1).max(24).optional(),category:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("library.tags.delete"),id:Gn}).strict(),o.object({op:o.literal("library.tags.merge"),id:Gn,into:Gn}).strict(),o.object({op:o.literal("library.tags.assign"),id:Bn,tags:o.array(Gn).max(64),primary:o.string().max(128).optional()}).strict(),o.object({op:o.literal("library.chat.link"),id:Bn,sessionId:L}).strict(),o.object({op:o.literal("library.chat.clear"),id:Bn}).strict(),o.object({op:o.literal("library.librarian"),action:o.enum(["status","open","pause","resume","run"]).optional()}).strict(),o.object({op:o.literal("sidebar_layout.get")}).strict(),o.object({op:o.literal("sidebar_layout.set"),layout:ig}).strict(),o.object({op:o.literal("notifications.list"),preview:o.literal(!0).optional(),includeAskReads:o.boolean().optional(),countSessionIds:o.array(L).max(50).optional(),kind:o.enum(["all","asks","updates"]).optional(),bulkPriority:o.enum(["any","high","normal_up"]).optional(),state:o.enum(["unread","all","dismissed"]).optional(),source:o.enum(["notify","ask"]).optional(),priority:o.enum(["high","normal","low"]).optional(),sessionId:L.optional(),throughSeq:o.number().int().min(0).optional(),cursor:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("notifications.get"),id:Et}).strict(),o.object({op:o.literal("notifications.count")}).strict(),o.object({op:o.literal("notifications.read"),verb:o.enum(["read","unread","undo"]),target:o.union([Oc,Ac,sg])}).strict(),o.object({op:o.literal("notifications.dismiss"),verb:o.enum(["dismiss","undismiss"]),target:o.union([Oc,Ac])}).strict(),o.object({op:o.literal("notifications.seen"),items:o.array(o.object({id:Et,revision:o.number().int().min(1),anchorId:o.string().min(1).max(256),visibleSinceMs:o.number().int().min(0)}).strict()).min(1).max(50),evidence:o.object({sessionId:L,inputKind:o.enum(["pointer","key","wheel"]),inputAtMs:o.number().int().min(0),visibleSinceMs:o.number().int().min(0)}).strict()}).strict()]);ag.superRefine((e,t)=>{if((e.op==="notifications.read"||e.op==="notifications.dismiss")&&"items"in e.target&&!!e.target.receipt!=(e.target.throughSeq!==void 0)&&t.addIssue({code:o.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:o.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:o.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:o.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:o.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:o.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:o.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,i=e.op!=="hub.check";if(n&&r||i&&!n&&!r||r&&e.kind===void 0){t.addIssue({code:o.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:o.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:o.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:o.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:o.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:o.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:o.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:o.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:o.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:o.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:o.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:o.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:o.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:o.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:o.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:o.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:o.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:o.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:o.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:o.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:o.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:o.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const qe={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},cg={runtimeUnreachable:"runtime_unreachable"},xi="runtime_busy",vd="runtime_retiring";o.object({data:o.object({aside_id:o.string().optional(),status:o.union([o.enum(["adopted","queued"]),o.string()]).optional()}).passthrough()}).passthrough();const wd=o.object({name:o.string(),description:o.string().nullish(),source:o.string().nullish(),link_id:o.string().nullish(),editable:o.boolean().nullish(),installed:o.boolean().nullish(),fingerprint:o.string().nullish(),form:o.string().nullish()}).passthrough(),lg=o.object({path:o.string(),size:o.number().nullish(),preview:o.string().nullish(),preview_truncated:o.boolean().nullish()}).passthrough(),dg=wd.extend({body:o.string().nullish(),body_in_detail:o.boolean().nullish(),body_length:o.number().nullish(),body_bytes:o.number().nullish(),body_truncated:o.boolean().nullish(),files:o.array(lg).nullish(),files_total:o.number().nullish(),files_truncated:o.boolean().nullish(),publish_budget:o.object({limit:o.number(),total:o.number()}).passthrough().nullish()}).passthrough(),VI=o.object({skills:o.array(wd),scope:o.string().nullish(),detail:o.string().nullish(),skill_detail:dg.nullish(),warning_count:o.number().nullish(),version:o.string().nullish()}).passthrough(),YI="aside_adopt_refused",ug=["session_closed","open_tool_batch","turn_running"];function QI(e){if(typeof e!="object"||e===null)return;const t=e.reason;return ug.find(n=>n===t)}const fg={[qe.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[qe.refused]:"ui.common.errors.desktop_refusal.refused",[qe.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[qe.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed"},Zs={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 Ri(e){return e!==void 0&&Object.values(qe).includes(e)}function pg(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return qe.refused;if(t===503)return qe.planeClosed}}const JI=o.object({step:o.string(),blocked_on:o.string(),configured:o.boolean(),ready:o.boolean(),verified:o.boolean(),url:o.string().nullable(),credential_id:o.number().int().positive().nullable(),identity_label:o.string().nullable(),credential_choices:o.array(o.object({id:o.number().int().positive(),identity_label:o.string().nullable().optional()}).passthrough()).default([]),quote:o.object({monthly_price_usd:o.string().nullable(),positive_balance:o.boolean(),eligible:o.boolean(),account_valid:o.boolean()}).passthrough().nullable(),receipts:o.array(o.object({step:o.string(),ok:o.boolean(),text:o.string()})).default([]),remedy:o.object({kind:o.string(),text:o.string(),command:o.string().nullable().optional(),url:o.string().nullable().optional()}).nullable(),source:o.string(),in_progress:o.boolean().default(!1),progress:o.array(o.string()).default([]),active_credential_id:o.number().int().positive().nullable().default(null),billing_outcome:o.string().optional(),reservation_outcome:o.string().optional(),failure_stage:o.string().optional()}).passthrough(),XI=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),hg=88e4,mg=11e5,gg=2e4,_g=9e4,yg=new Set(["analytics.get","analytics.models","sessions.report"]),bg=new Set(["usage.get"]),vg=new Set(["networks.list","peers.list"]),wg=new Set([...yg,...bg,...vg]),Sg=90,kg=30,Eg=300,Ig=10,Sd=15,xg=1e4;function Rg(e){const n=e.to==="local"||e.keep?Eg:kg,r=Math.max(0,e.waitS??0);return(Sg+n+Ig+Sd)*1e3+r*1e3}const Tg=18e4,Cg=Tg+15e3,Ag=120,Og=135e3,Pg=93e4,kd=(Ag+30+Sd)*1e3,jg=6e4,Mg=5*kd,Dg=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function Ng(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 kd;case"hub.check":return jg;case"hub.applyAll":return Mg;default:return null}}function Lg(e){if(typeof e!="string"&&e.op==="sessions.transfer")return Rg(e)+xg;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return Cg;if(t==="tunnel.setup.run")return Pg;if(t==="tunnel.setup.plan")return Og;const n=Ng(t);return n!==null?n:wg.has(t)?_g:gg}const $g=5e3;function Ed(e){return Lg(e)+$g}const Oo="deadline_exceeded",Id="foreground_required",xd="View these completions in the foreground before marking them read.",Ug=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"]),Fg=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Bg(e,t){const n=Math.round(t/1e3),r=Oo;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.`}:Dg.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:Ug.has(e)?{code:r,message:Fg.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 qI=hg,ex=mg;o.object({state:o.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:o.string(),kind:o.enum(["balance","subscription","radient","none"]),model_free:o.boolean(),title:o.string(),body:o.string(),actions:o.array(o.object({id:o.enum(["open_url","resend_verification","refresh"]),label:o.string(),url:o.string().nullable().optional()})),resets_at_ms:o.number().int().nullable().optional(),checked_at_ms:o.number().int(),age_ms:o.number().int().nullable().optional(),source:o.enum(["cached","live"])});function Gg(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function Pc(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 as(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 cs(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 jc(e){return{sources:e.sources??null,session_ids:e.sessionIds??{},all:e.all??!1,include_subagents:e.includeSubagents??!1,include_cleared_segments:e.includeClearedSegments??!1,include_memory:e.includeMemory??!0,include_instructions:e.includeInstructions??!0,...e.maxSessions===void 0?{}:{max_sessions:e.maxSessions}}}function Yr(e){const t=new URLSearchParams;return e.tenant_id&&t.set("tenant_id",e.tenant_id),e.expected_account_id&&t.set("expected_account_id",e.expected_account_id),t.size?`?${t.toString()}`:""}function ls(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function Hg(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:jc(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:jc(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??wm)});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"),hi(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),hi(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??km)});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":{cs(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??{},...as(e)}}}case"agent.republish":{cs(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??{},...as(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{cs(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:as(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,...Gg(e),message:e.message,...Pc(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...Pc(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${ls(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${ls(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)}${ls(e.tenant_id)}`,method:"GET"};case"team_bridge.conversations.create":return{path:"/v1/desktop/team-bridge/conversations",method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},kind:e.kind,...e.name?{name:e.name}:{},...e.topic?{topic:e.topic}:{},...e.visibility?{visibility:e.visibility}:{},...e.agent_capable===void 0?{}:{agent_capable:e.agent_capable},members:e.members}};case"team_bridge.conversations.lifecycle":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/${e.action}${e.action==="join"?"":Yr(e)}`,method:"POST",...e.action==="join"&&(e.tenant_id||e.expected_account_id)?{body:{...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.expected_account_id?{expected_account_id:e.expected_account_id}:{}}}:{}};case"team_bridge.conversations.join":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/join`,method:"POST",...e.tenant_id||e.expected_account_id?{body:{...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.expected_account_id?{expected_account_id:e.expected_account_id}:{}}}:{}};case"team_bridge.conversations.notify":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},notify:e.notify}};case"team_bridge.conversations.agent_notify":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/agent-notify`,method:"PUT",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},notify:e.notify}};case"team_bridge.conversations.members.add":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.expected_account_id&&t.set("expected_account_id",e.expected_account_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members${n}`,method:"POST",body:e.members}}case"team_bridge.conversations.delete":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}${Yr(e)}`,method:"DELETE"};case"team_bridge.conversations.members.remove":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}${Yr(e)}`,method:"DELETE"};case"team_bridge.conversations.consent":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}/consent`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},decision:e.decision,consent_version:e.consent_version}};case"team_bridge.owner_audit.conversations":case"team_bridge.owner_audit.messages":case"team_bridge.owner_audit.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit));let n="/v1/desktop/team-bridge/owner-audit/conversations";return e.op==="team_bridge.owner_audit.conversations"?e.cursor!==void 0&&t.set("cursor",e.cursor):(n+=`/${encodeURIComponent(e.conversation_id)}/messages`,e.op==="team_bridge.owner_audit.messages"?e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)):(n+=`/${encodeURIComponent(e.message_id)}/replies`,e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order))),{path:`${n}?${t}`,method:"GET"}}case"team_bridge.messages.list":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.endpoint_id&&t.set("endpoint_id",e.endpoint_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages${n}`,method:"GET"}}case"team_bridge.reactions.toggle":{const t=`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/reactions/${encodeURIComponent(e.emoji)}`;return e.active?{path:t,method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id}}:{path:`${t}${Yr(e)}`,method:"DELETE"}}case"team_bridge.messages.send":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},client_ref:e.client_ref,body:e.body,...e.agent_label?{agent_label:e.agent_label}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{},...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.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.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??tg)})}`,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,...zg(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:og[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function zg(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 tx=64,nx=64*1024*1024,rx="superseded_completion_token",ix="store_busy",Wg="session_is_remote",Zg="owner_build_behind";function sx(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 wn(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 Kg(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const ox=e=>typeof e?.goal_status=="string",ax=e=>(e?.goal??"").trim().length>0;function Vg(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function Yg(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 tr={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 Qg(e){return e?e===tr.notPaired?"notPaired":e===tr.serverDown?"serverDown":e===tr.frameBudget?"frameTooLarge":"lost":"lost"}const Mc=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const p=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(g=>g(t,p))}},i=()=>t,c={setState:r,getState:i,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d))},l=t=e(r,i,c);return c},Jg=e=>e?Mc(e):Mc,Xg=e=>e;function qg(e,t=Xg){const n=Fa.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return Fa.useDebugValue(n),n}const Dc=e=>{const t=Jg(e),n=r=>qg(t,r);return Object.assign(n,t),n},Ar=e=>e?Dc(e):Dc;function Rd(e,t){let n;try{n=e()}catch{return}return{getItem:i=>{var s;const a=l=>l===null?null:JSON.parse(l,void 0),c=(s=n.getItem(i))!=null?s:null;return c instanceof Promise?c.then(a):a(c)},setItem:(i,s)=>n.setItem(i,JSON.stringify(s,void 0)),removeItem:i=>n.removeItem(i)}}const Ks=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Ks(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Ks(r)(n)}}}},e_=(e,t)=>(n,r,i)=>{let s={storage:Rd(()=>localStorage),partialize:m=>m,version:0,merge:(m,b)=>({...b,...m}),...t},a=!1;const c=new Set,l=new Set;let d=s.storage;if(!d)return e((...m)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),n(...m)},r,i);const u=()=>{const m=s.partialize({...r()});return d.setItem(s.name,{state:m,version:s.version})},f=i.setState;i.setState=(m,b)=>{f(m,b),u()};const p=e((...m)=>{n(...m),u()},r,i);i.getInitialState=()=>p;let g;const y=()=>{var m,b;if(!d)return;a=!1,c.forEach(k=>{var E;return k((E=r())!=null?E:p)});const _=((b=s.onRehydrateStorage)==null?void 0:b.call(s,(m=r())!=null?m:p))||void 0;return Ks(d.getItem.bind(d))(s.name).then(k=>{if(k)if(typeof k.version=="number"&&k.version!==s.version){if(s.migrate){const E=s.migrate(k.state,k.version);return E instanceof Promise?E.then(A=>[!0,A]):[!0,E]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,k.state];return[!1,void 0]}).then(k=>{var E;const[A,$]=k;if(g=s.merge($,(E=r())!=null?E:p),n(g,!0),A)return u()}).then(()=>{_?.(g,void 0),g=r(),a=!0,l.forEach(k=>k(g))}).catch(k=>{_?.(void 0,k)})};return i.persist={setOptions:m=>{s={...s,...m},m.storage&&(d=m.storage)},clearStorage:()=>{d?.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>y(),hasHydrated:()=>a,onHydrate:m=>(c.add(m),()=>{c.delete(m)}),onFinishHydration:m=>(l.add(m),()=>{l.delete(m)})},s.skipHydration||y(),g||p},Ti=e_,t_=(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 n_(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,i)=>typeof r=="number"&&Number.isFinite(r)?r:i;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 Td=Ar()(Ti(e=>({notice:null,receive:t=>e(n=>t_(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:Rd(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function Po(e){return h(fg[e])}async function Cd(e){if(window.api?.desktop)try{return await r_(window.api.desktop.request(e),e)}catch(n){throw n instanceof ye?n:l_(n)?new Ht(xd,Id):new ye(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 ye(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new ye(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function r_(e,t){const n=Ed(t);let r;return Promise.race([e,new Promise((i,s)=>{r=setTimeout(()=>{const a=Bg(t.op,n);s(new ye(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const Ad="This server did not answer the request for its desktop controls.",i_=()=>h("ui.common.errors.desktop_refusal_placeholder");class ye extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,i,s,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=i,this.retryAfterMs=s,this.detail=a}}class Ht extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function jo(e,t){return e instanceof ye||e instanceof Ht?Ri(e.code)?Po(e.code):e.message===Ad?i_():e.message:t}function s_(e,t,n,r){return typeof r=="string"?r:n===Zs.noCredential?qe.noCredential:n===Zs.transportFailed?qe.transportFailed:pg(Hg(e).path,t)}async function Re(e){const t=await Cd(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 ye(t.status,r??Ad,void 0,s_(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"&&o_(n?.result),n?.result}function o_(e){if(typeof e!="object"||e===null)return;const t=n_(e.delegated_cleanup_notice);t&&Td.getState().receive(t)}async function a_(){try{await Re({op:"delegated_cleanup_notice.ack"})}catch{}}async function cx(){Td.getState().dismiss(),await a_()}function c_(e){return e instanceof ye&&e.code===Oo}function lx(e){if(!(e instanceof ye))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===Zg:e.code===Wg}function dx(e){return e instanceof Ht&&e.code===Id}function l_(e){return e instanceof Error&&e.message.includes(xd)}async function ux(e){const t=await Cd(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function fx(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await Re({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 d_(e,t){const n=window.api?.desktop?.stream;if(n){const s=n.subscribe(e,t);return()=>s.dispose()}const r=new URLSearchParams({session:e.sessionId});e.epoch&&r.set("epoch",e.epoch),e.afterSeq!==void 0&&r.set("after_seq",String(e.afterSeq)),r.set("frontend_replace","1"),e.openFrame===!0&&r.set("open_frame","1"),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),hi(r,"/__desktop/stream",e.orderIds??[]));const i=new EventSource(`/__desktop/stream?${r}`);return i.onmessage=s=>{t({kind:"data",data:s.data})},i.onerror=()=>{i.readyState===EventSource.CLOSED&&(t({kind:"error",detail:tr.ended}),i.close())},()=>{i.close(),t({kind:"end"})}}async function px(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}),i=r.headers.get("content-type")??"";if(!r.ok){let s="The media request failed.",a;if(i.includes("application/json"))try{const l=(await r.json())?.detail;if(typeof l=="string")s=l;else if(typeof l=="object"&&l!==null){const d=l;typeof d.text=="string"&&d.text.trim()?s=d.text:typeof d.message=="string"&&d.message.trim()&&(s=d.message),typeof d.code=="string"&&(a=d.code)}}catch{}return{status:r.status,kind:"error",detail:s,code:a!==void 0&&Ri(a)?a:s===Zs.noCredential?qe.noCredential:void 0}}return i.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:i||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function hx(e){return e.kind==="error"?Ri(e.code)?new Ht(Po(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function u_(e){if(c_(e))return"deadline";const t=e instanceof ye?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const Od={unreachable:"",deadline:"",unauthorized:"",get outdated(){return h("ui.common.connection.backend.remedy_outdated")},unknown:""},Vs={get unreachable(){return h("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return h("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return h("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return h("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function f_(e,t){const n=u_(t);return[e,Vs[n],Od[n]].filter(Boolean).join(" ")}const Ys={get successor(){return h("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return h("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return h("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return h("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return h("ui.common.connection.backend.pairing_unpaired")}},p_={get successor(){return h("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return h("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return h("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return h("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return h("ui.common.connection.backend.pane_unpaired")}};function mx(e,t){return e!=="unpaired"?null:p_[t??"unpaired"]}function gx(e,t){return e!=="unpaired"?null:Ys[t??"unpaired"]}function _x(e){const{kind:t,unpaired:n,answered:r,cause:i=null,servedByThisApp:s=!1}=e;return i==="pre-handshake"?s:i!==null||n?!1:r?s:t==="outdated"}function yx(e){const{kind:t,unpaired:n,missing:r,answered:i,cause:s=null}=e;if(s!==null)return Ys[s];if(!i){if(t==="unreachable")return h("ui.common.connection.backend.compatibility_unreachable",{diagnosis:Vs.unreachable});if(t==="unauthorized")return h("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return h("ui.common.connection.backend.compatibility_deadline",{diagnosis:Vs.deadline});if(t==="outdated")return h("ui.common.connection.backend.compatibility_outdated",{remedy:Od.outdated})}return n?Ys.unpaired:i?h("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):h("ui.common.connection.backend.compatibility_unknown")}const h_=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function bx(e,t=null){return t!==null||!e?!0:h_.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function m_(e,t){return t instanceof ye&&t.status===null?!1:e<1}function vx(e,t){return t instanceof ye&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const g_={get successor(){return h("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return h("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return h("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return h("ui.common.connection.backend.card_credential_refused")},get unpaired(){return h("ui.common.connection.backend.card_unpaired")}};function wx(e,t,n){return e===null?{sentence:f_(t,n),remedy:!0}:{sentence:g_[e],remedy:sd(e)}}const Pd={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]},__=3e4,y_=15e3;function b_(e){return e?.desktop_available===!0}function Sx(){const{client:e,provided:t}=Wp();return id({enabled:t,queryKey:Pd.capabilities,queryFn:async()=>{try{return await Re({op:"capabilities"})}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>b_(n.state.data)?__:y_,refetchIntervalInBackground:!0},e)}function v_(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function kx(e,t,n=1){return v_(e,t,n)==="enabled"}function Ex(e){return id({queryKey:Pd.providers,queryFn:()=>Re({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:m_})}const Hn=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function w_(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=Hn(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=Hn(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>Hn(d)===c);l===-1?r.push(a):r[l]=a}if(!t.order)return r;const i=new Map;for(const a of r){const c=Hn(a);c!==null&&i.set(c,a)}const s=[];for(const a of t.order){const c=String(a),l=i.get(c);l&&(s.push(l),i.delete(c))}for(const a of r){const c=Hn(a);c!==null&&i.has(c)?(s.push(a),i.delete(c)):c===null&&s.push(a)}return s}const Qs=e=>({revision:Je(e),demand:e.orderDemand}),nn=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function On(e,t,n,r,i,s={}){let a=e;const c=t.journal_generation;if(t.reconcile===!0){const p=typeof c=="string"&&c.length>0?c:void 0;return a.orderNeedsReconcile&&a.orderWantedGeneration===p?a.journalMode?a:{...a,journalMode:!0}:{...a,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:p,orderDemand:p!==void 0?{generation:p}:{}}}if(typeof c!="string"||c.length===0)return t.journal_order_state&&t.journal_order_state!=="unsupported"&&!a.journalMode?{...a,journalMode:!0}:a;if(r&&t.journal_order_state==="ready"&&i&&a.orderNeedsReconcile&&a.orderDemand===i.demand&&(a={...a,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),c!==a.journalGeneration&&!r)return a.orderNeedsReconcile&&a.orderWantedGeneration===c?a:{...a,orderNeedsReconcile:!0,orderWantedGeneration:c,orderDemand:{generation:c}};let l=a.journalMode?a:{...a,journalMode:!0};if(c!==a.journalGeneration&&(l={...a,journalMode:!0,journalGeneration:c,orderRevision:(a.orderRevision??0)+1,journalPositions:new Map,orderNeedsReconcile:a.orderNeedsReconcile,orderWantedGeneration:a.orderWantedGeneration,orderDemand:a.orderDemand},s.peer===!0)){const p=(a.orderRevision??0)+1,g=new Map;for(const y of a.records){const m=y.sourceEntryId??(y.kind==="tool"||y.kind==="supplement"?null:y.id);typeof m=="string"&&m.length>0&&m.length<=128&&g.set(m,p)}l={...l,...g.size>0?{journalBodyOwed:g}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(p,g,y)=>{if(!nn(y))return;const m=d.get(p);m&&m.seq>=y||(d===u&&(d=new Map(d)),d.set(p,{entryId:g,seq:y}))};for(const[p,g]of Object.entries(t.journal_ordinals??{}))f(p,p,g);for(const p of n)typeof p.id=="string"&&(f(p.id,p.id,p.journal_seq),p.role==="tool"&&typeof p.tool_call_id=="string"&&f(`tool:${p.tool_call_id}`,p.id,p.journal_seq),typeof p.anchor=="string"&&f(`supplement:${p.anchor}`,p.id,p.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function Mo(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 i=n,s=r;return t.tool_calls.forEach((a,c)=>{!a||typeof a.id!="string"||(n.get(a.id)!==t.id&&(n===i&&(n=new Map(n)),n.set(a.id,t.id)),r.get(a.id)!==c&&(r===s&&(r=new Map(r)),r.set(a.id,c)))}),n===i&&r===s?e:{...e,journalCallOwners:n,journalCallSlots:r}}function jd(e,t){const n=new Set(e.map(s=>s.id));let r=!1,i;for(let s=0;s<e.length;s++){const a=e[s];if(a.kind==="user"&&a.provisional===!0){i=a;continue}if(a.sourcePrecedes!==void 0){if(a.sourceAdmissionAnchor!==void 0){const{sourceAdmissionAnchor:c,...l}=a;e[s]=l,r=!0}i=e[s];continue}!t(a)&&i&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[s]={...a,sourceAdmissionAnchor:i.id},r=!0),i=e[s]}return r}function Md(e,t,n,r,i){const s=[],a=new Set;let c=e,l;for(;c!==void 0;){if(i.has(c.id)){l=i.get(c.id);break}if(n(c)){l=r(c);break}if(c.kind==="user"&&c.provisional===!0||a.has(c.id))break;a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of s)i.set(d,l);return l}const S_=Number.MAX_SAFE_INTEGER;function k_(e,t){const n=new Map,r=new Map,i=new Map;for(const s of e){if(s.sourcePrecedes===void 0)continue;const a=t(s);if(a!==void 0)r.set(s.sourcePrecedes,a);else{const c=r.get(s.sourcePrecedes);c!==void 0&&n.set(s.id,{seq:c,slot:S_})}}for(let s=e.length-1;s>=0;s--){const a=e[s];if(a.sourcePrecedes===void 0)continue;const c=t(a);if(c!==void 0)i.set(a.sourcePrecedes,c);else if(!n.has(a.id)){const l=i.get(a.sourcePrecedes);l!==void 0&&n.set(a.id,{seq:l,slot:-1})}}return n}function Dd(e,t){return{floor:E_(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:k_(e,t)}}function Nd(e,t,n,r){if(r===void 0||e.sourcePrecedes===void 0)return;const i=r.page.get(e.id);if(i!==void 0)return i;const s=new Set;let a=1,c=t.get(e.sourcePrecedes);for(;c!==void 0&&!s.has(c.id);){s.add(c.id);const l=n(c);if(l!==void 0)return{seq:l,slot:-a};const d=r.page.get(c.id);if(d!==void 0)return{seq:d.seq,slot:d.slot-a};a+=1,c=c.sourcePrecedes?t.get(c.sourcePrecedes):void 0}return r.floor===void 0?void 0:{seq:r.floor,slot:-a}}function Ld(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:r}=n,i=new Set;let s=1,a=t.get(e.sourcePrecedes);for(;a!==void 0&&!i.has(a.id);){if(a.sourcePrecedes===void 0){const c=r.get(a.id);return c===void 0?void 0:{slot:c,depth:s}}i.add(a.id),s+=1,a=t.get(a.sourcePrecedes)}}function E_(e,t){let n;for(const r of e){if(r.sourcePrecedes!==void 0)continue;const i=t(r);i!==void 0&&(n===void 0||i<n)&&(n=i)}return n}function $d(e,t){const n=new Map;return r=>{if(!r)return;const i=t(r);if(i===void 0)return;const s=[],a=new Set;let c=r,l=!0;for(;c;){if(n.has(c.id)){l=n.get(c.id)===!0;break}if(a.has(c.id)||t(c)===void 0){l=!1;break}a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of s)n.set(d,l);return l?i:void 0}}function mi(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const i=new Map;t.forEach((a,c)=>{if(a.kind!=="tool")return;const l=n.get(a.toolCallId);if(l===void 0||!r.has(a.toolCallId))return;const d=i.get(l);d?d.push(c):i.set(l,[c])});let s=t;for(const a of i.values()){if(a.length<2)continue;const c=a.map(l=>t[l]).sort((l,d)=>(r.get(l.toolCallId)??0)-(r.get(d.toolCallId)??0));c.every((l,d)=>l===t[a[d]])||(s===t&&(s=t.slice()),a.forEach((l,d)=>{s[l]=c[d]}))}return s}function Ud(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return I_(e,t);const n=e.journalGeneration,r=e.journalPositions;let i=!1,s=!1;const a=t.map(m=>{m.sourcePrecedes!==void 0&&(s=!0);let _=[r?.get(m.sourceEntryId??m.id),r?.get(m.id)].filter(A=>A!==void 0).sort((A,$)=>$.seq-A.seq)[0];if(m.journalGeneration===n&&nn(m.journalSeq)&&(!_||m.journalSeq>_.seq)&&(_={entryId:m.sourceEntryId??m.id,seq:m.journalSeq}),!_||!n||!(m.kind==="user"&&(m.provisional===!0||m.local===!0))&&m.sourceEntryId===_.entryId&&m.journalSeq===_.seq&&m.journalGeneration===n)return m;i=!0;let E={...m,sourceEntryId:_.entryId,journalSeq:_.seq,journalGeneration:n};if(E.kind==="user"){const{provisional:A,local:$,...O}=E;E=O}return E});jd(a,m=>m.journalGeneration===n&&nn(m.journalSeq))&&(i=!0);const l=new Map,d=new Map(a.map(m=>[m.id,m])),u=$d(d,m=>m!==void 0&&m.journalGeneration===n&&nn(m.journalSeq)?m.journalSeq:void 0),f=m=>u(m)!==void 0,p=s?Dd(a,u):void 0,g=(m,b)=>{const _=u(m);if(m.kind==="user"&&m.provisional===!0&&_===void 0)return[1,0,0,0,b];const k=m.kind==="supplement"?m.anchor:m.kind==="tool"?e.journalCallOwners?.get(m.toolCallId)??e.argsByCall.get(m.toolCallId)?.anchorId:void 0,E=typeof k=="string"?u(d.get(k)):void 0,A=E===void 0&&_===void 0?Nd(m,d,u,p):void 0,$=_===void 0&&A===void 0?Md(m,d,f,u,l):void 0,O=E??_??A?.seq??$;if(O===void 0){const C=Ld(m,d,p);return[1,C?.slot??b,C?-C.depth:0,0,b]}return[0,O,E!==void 0?1:_!==void 0?0:A!==void 0?A.slot:2,_??Number.MAX_SAFE_INTEGER,b]},y=a.map((m,b)=>({record:m,index:b,rank:g(m,b)}));return y.sort((m,b)=>{for(let _=0;_<m.rank.length;_++){const k=m.rank[_]-b.rank[_];if(k)return k}return 0}),!i&&y.every((m,b)=>m.index===b)?mi(e,t):mi(e,y.map(m=>m.record))}function I_(e,t){const n=e.journalGeneration,r=e.journalPositions,i=new Map;let s=!1;for(const _ of t){_.sourcePrecedes!==void 0&&(s=!0);let E=[r?.get(_.sourceEntryId??_.id),r?.get(_.id)].filter(A=>A!==void 0).sort((A,$)=>$.seq-A.seq)[0];_.journalGeneration===n&&nn(_.journalSeq)&&(!E||_.journalSeq>E.seq)&&(E={entryId:_.sourceEntryId??_.id,seq:_.journalSeq}),E&&i.set(_.id,E)}const a=_=>_===void 0?void 0:i.get(_.id)??r?.get(_.sourceEntryId??_.id)??r?.get(_.id);let c=!1;const l=t.slice();jd(l,_=>_.journalGeneration===n&&nn(_.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(_=>[_.id,_])),p=$d(f,_=>a(_)?.seq),g=_=>p(_)!==void 0,y=s?Dd(l,p):void 0,m=(_,k)=>{const E=p(_);if(_.kind==="user"&&_.provisional===!0&&E===void 0)return[1,0,0,0,k];const A=_.kind==="supplement"?_.anchor:_.kind==="tool"?e.journalCallOwners?.get(_.toolCallId)??e.argsByCall.get(_.toolCallId)?.anchorId:void 0,$=typeof A=="string"?p(f.get(A)):void 0,O=$===void 0&&E===void 0?Nd(_,f,p,y):void 0,C=E===void 0&&O===void 0?Md(_,f,g,p,u):void 0,I=$??E??O?.seq??C;if(I===void 0){const N=Ld(_,f,y);return[1,N?.slot??k,N?-N.depth:0,0,k]}return[0,I,$!==void 0?1:E!==void 0?0:O!==void 0?O.slot:2,E??Number.MAX_SAFE_INTEGER,k]},b=l.map((_,k)=>({record:_,index:k,rank:m(_,k)}));return b.sort((_,k)=>{for(let E=0;E<_.rank.length;E++){const A=_.rank[E]-k.rank[E];if(A)return A}return 0}),!c&&b.every((_,k)=>_.index===k)?mi(e,t):mi(e,b.map(_=>_.record))}function ut(e){const t=e.records.filter(i=>i.kind==="user"&&i.provisional===!0),n=e.records.filter(i=>i.journalGeneration!==e.journalGeneration||!nn(i.journalSeq)),r=[...t,...n].map(i=>i.sourceEntryId??(i.kind==="tool"||i.kind==="supplement"?null:i.id));if(r.push(...Do(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let i=r.length-1;i>=0;i--){const s=r[i];typeof s=="string"&&e.journalSourceVoid.has(s)&&r.splice(i,1)}return[...new Set(r.filter(i=>typeof i=="string"&&i.length>0&&i.length<=128))]}function Do(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const i=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof i=="string"&&i.length>0&&i.length<=128&&t.add(i)}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 Fd(e,t){const n=e.journalPositions;return ut(e).filter(r=>!n?.has(r)&&!t?.has(r))}const Je=e=>e.orderRevision??0;async function x_(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"?Do(c):l==="lookup"?Fd(c):ut(c);let i=e.getTranscript().journalGeneration,s=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=Qs(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",p=um(r(c,f).filter(b=>!n(f).has(b)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),g=await e.read(p,f);if(!e.isCurrent()||Je(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(g,d,l),!e.isCurrent())return{kind:"stale"};const y=e.getTranscript(),m=e.page(g);if(m.journal_order_state==="ready"&&m.journal_generation===y.journalGeneration){m.journal_generation!==i&&(t.clear(),i=m.journal_generation);for(const k of p)n(f).add(k);if(y.orderNeedsReconcile){if(y.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear();continue}if(f==="payload"){const k=(m.source_retry_ids??[]).filter(E=>typeof E=="string"&&E.length>0&&E.length<=128);if(k.length>0&&p.length>1&&a===0){a++;for(const E of k)n("payload").delete(E);continue}}const b=e.sweep?.(y,n);if(b?.kind==="none")return{kind:"complete",transcript:y};const _=b?.kind??"authority";if(r(y,_).some(k=>!n(_).has(k)))continue;return{kind:"complete",transcript:y}}if(!y.orderNeedsReconcile||y.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear()}}function it(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const i=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof i=="string"&&i?i:e.id}function ds(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function Nc(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function Ix(e){if(!e||e.runs_state!=="ready")return null;const t=e.runs;if(!t||t.length===0)return null;const n=new Map;for(const s of t){if(!s.settled||typeof s.run_key!="string"||s.run_key.length===0)continue;const a=ds(s.action_count);if(a===null)continue;const c={actions:a,workedSeconds:Nc(s.worked_seconds),failed:ds(s.failed_count)??0,complete:s.complete!==!1,openingUserId:typeof s.opening_user_id=="string"&&s.opening_user_id.length>0?s.opening_user_id:null,closingAnswerId:typeof s.closing_answer_id=="string"&&s.closing_answer_id.length>0?s.closing_answer_id:null,crossSessionActions:ds(s.cross_session_action_count),crossSessionWorkedSeconds:Nc(s.cross_session_worked_seconds)};n.set(s.run_key,c),c.openingUserId!==null&&n.set(c.openingUserId,c),c.closingAnswerId!==null&&n.set(c.closingAnswerId,c)}if(n.size===0)return null;const r=new Set;for(const s of e.entries)r.add(it(s));const i=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:i?it(i):null}}}function R_(e){if(!e||e.runs_state!=="ready"||e.head_cut===!0)return null;const t=e.runs,n=e.entries[0];if(!n||!t||t.length===0||!t.find(s=>s.opening_user_id===n.id))return null;const i=Math.round((n.ts??0)*1e3);return i>0?{id:n.id,tsMs:i}:null}function T_(e,t,n){const r=R_(e),i=e?.entries;if(r===null||!i||i.length===0)return!1;const s=Math.round((i[i.length-1].ts??0)*1e3);if(!(s>r.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>r.tsMs)||!(c<s)))return!1;return!0}const No=new Set,zt="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Lo=new RegExp(`[${zt}]`),C_=new RegExp(`[${zt}]+`),xx=new RegExp(`[${zt}]+`,"g"),A_=new RegExp(`^[${zt}]+|[${zt}]+$`,"g"),O_=new RegExp(`^[${zt}]+`),Rx=new RegExp(`[^${zt}]`);function mt(e){return e.replace(A_,"")}function vr(e){return e.replace(O_,"")}function Bd(e,t){return t===0||Lo.test(e[t-1])}function Gd(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&Bd(e,n)&&t.push(n);return t}function $o(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
1
+ import{r as S,j as dp,b as Fa,D as up}from"./index-BA3RZ8Br.js";import{t as h,a as fp}from"./messages-th0c6S1e.js";var Tr=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(){}},on=typeof window>"u"||"Deno"in globalThis;function Je(){}function pp(e,t){return typeof e=="function"?e(t):e}function Ps(e){return typeof e=="number"&&e>=0&&e!==1/0}function Vl(e,t){return Math.max(e+(t||0)-Date.now(),0)}function kn(e,t){return typeof e=="function"?e(t):e}function ot(e,t){return typeof e=="function"?e(t):e}function Ba(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:s,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==Io(a,t.options))return!1}else if(!or(t.queryKey,a))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||i&&i!==t.state.fetchStatus||s&&!s(t))}function Ga(e,t){const{exact:n,status:r,predicate:i,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(sr(t.options.mutationKey)!==sr(s))return!1}else if(!or(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Io(e,t){return(t?.queryKeyHashFn||sr)(e)}function sr(e){return JSON.stringify(e,(t,n)=>Ms(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function or(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>or(e[n],t[n])):!1}function Yl(e,t){if(e===t)return e;const n=Ha(e)&&Ha(t);if(n||Ms(e)&&Ms(t)){const r=n?e:Object.keys(e),i=r.length,s=n?t:Object.keys(t),a=s.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:s[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=Yl(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return i===a&&l===i?e:c}return t}function js(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 Ha(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ms(e){if(!za(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!za(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function za(e){return Object.prototype.toString.call(e)==="[object Object]"}function hp(e){return new Promise(t=>{setTimeout(t,e)})}function Ds(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Yl(e,t):t}function mp(e){return e}function gp(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function _p(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var xo=Symbol();function Ql(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===xo?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var yp=class extends Tr{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!on&&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"}},Ro=new yp,bp=class extends Tr{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!on&&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}},oi=new bp;function Ns(){let e,t;const n=new Promise((i,s)=>{e=i,t=s});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}function vp(e){return Math.min(1e3*2**e,3e4)}function Xl(e){return(e??"online")==="online"?oi.isOnline():!0}var Jl=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Qi(e){return e instanceof Jl}function ql(e){let t=!1,n=0,r=!1,i;const s=Ns(),a=m=>{r||(p(new Jl(m)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>Ro.isFocused()&&(e.networkMode==="always"||oi.isOnline())&&e.canRun(),u=()=>Xl(e.networkMode)&&e.canRun(),f=m=>{r||(r=!0,e.onSuccess?.(m),i?.(),s.resolve(m))},p=m=>{r||(r=!0,e.onError?.(m),i?.(),s.reject(m))},g=()=>new Promise(m=>{i=b=>{(r||d())&&m(b)},e.onPause?.()}).then(()=>{i=void 0,r||e.onContinue?.()}),y=()=>{if(r)return;let m;const b=n===0?e.initialPromise:void 0;try{m=b??e.fn()}catch(_){m=Promise.reject(_)}Promise.resolve(m).then(f).catch(_=>{if(r)return;const k=e.retry??(on?0:3),E=e.retryDelay??vp,A=typeof E=="function"?E(n,_):E,$=k===!0||typeof k=="number"&&n<k||typeof k=="function"&&k(n,_);if(t||!$){p(_);return}n++,e.onFail?.(n,_),hp(A).then(()=>d()?void 0:g()).then(()=>{t?p(_):y()})})};return{promise:s,cancel:a,continue:()=>(i?.(),s),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?y():g().then(y),s)}}var wp=e=>setTimeout(e,0);function Sp(){let e=[],t=0,n=c=>{c()},r=c=>{c()},i=wp;const s=c=>{t?e.push(c):i(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&i(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{s(()=>{c(...l)})},schedule:s,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{i=c}}}var De=Sp(),ed=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ps(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(on?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},kp=class extends ed{#t;#e;#n;#r;#i;#a;#o;constructor(e){super(),this.#o=!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=Ep(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#i?.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=Ds(this.state.data,e,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#s({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#i?.promise;return this.#i?.cancel(e),t?t.then(Je).catch(Je):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>ot(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===xo||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||!Vl(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.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.#i&&(this.#o?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.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.#o=!0,n.signal)})},i=()=>{const c=Ql(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(l),this.#o=!1,this.options.persister?this.options.persister(c,l,this):c(l)},s={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:i};r(s),this.options.behavior?.onFetch(s,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#s({type:"fetch",meta:s.fetchOptions?.meta});const a=c=>{Qi(c)&&c.silent||this.#s({type:"error",error:c}),Qi(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#i=ql({initialPromise:t?.initialPromise,fn:s.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){a(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){a(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:a,onFail:(c,l)=>{this.#s({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0}),this.#i.start()}#s(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...td(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 Qi(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),De.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function td(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Xl(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Ep(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 Ip=class extends Tr{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,i=t.queryHash??Io(r,t);let s=this.get(i);return s||(s=new kp({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(s)),s}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){De.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=>Ba(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Ba(e,n)):t}notify(e){De.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){De.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){De.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},xp=class extends ed{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||Rp(),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=ql({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(r,i)=>{this.#r({type:"failed",failureCount:r,error:i})},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 i=await this.options.onMutate?.(e);i!==this.state.context&&this.#r({type:"pending",context:i,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),De.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#e.notify({mutation:this,type:"updated",action:e})})}};function Rp(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Tp=class extends Tr{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 xp({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=Fr(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=Fr(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=Fr(e);if(typeof t=="string"){const r=this.#e.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Fr(e);return typeof t=="string"?this.#e.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){De.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=>Ga(t,n))}findAll(e={}){return this.getAll().filter(t=>Ga(e,t))}notify(e){De.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return De.batch(()=>Promise.all(e.map(t=>t.continue().catch(Je))))}};function Fr(e){return e.options.scope?.id}function Wa(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},p=Ql(t.options,t.fetchOptions),g=async(y,m,b)=>{if(u)return Promise.reject();if(m==null&&y.pages.length)return Promise.resolve(y);const _={client:t.client,queryKey:t.queryKey,pageParam:m,direction:b?"backward":"forward",meta:t.options.meta};f(_);const k=await p(_),{maxPages:E}=t.options,A=b?_p:gp;return{pages:A(y.pages,k,E),pageParams:A(y.pageParams,m,E)}};if(i&&s.length){const y=i==="backward",m=y?nd:Ls,b={pages:s,pageParams:a},_=m(r,b);c=await g(b,_,y)}else{const y=e??s.length;do{const m=l===0?a[0]??r.initialPageParam:Ls(r,c);if(l>0&&m==null)break;c=await g(c,m),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 Ls(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 nd(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function NI(e,t){return t?Ls(e,t)!=null:!1}function LI(e,t){return!t||!e.getPreviousPageParam?!1:nd(e,t)!=null}var Cp=class{#t;#e;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#t=e.queryCache||new Ip,this.#e=e.mutationCache||new Tp,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=Ro.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#s=oi.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#t.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(kn(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=this.#t.get(r.queryHash)?.state.data,a=pp(t,s);if(a!==void 0)return this.#t.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return De.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;De.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return De.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=De.batch(()=>this.#t.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then(Je).catch(Je)}invalidateQueries(e,t={}){return De.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=De.batch(()=>this.#t.findAll(e).filter(i=>!i.isDisabled()).map(i=>{let s=i.fetch(void 0,n);return n.throwOnError||(s=s.catch(Je)),i.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(Je)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(kn(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Je).catch(Je)}fetchInfiniteQuery(e){return e.behavior=Wa(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Je).catch(Je)}ensureInfiniteQueryData(e){return e.behavior=Wa(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return oi.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(sr(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{or(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(sr(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#i.values()],n={};return t.forEach(r=>{or(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=Io(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===xo&&(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()}},Ap=class extends Tr{constructor(e,t){super(),this.options=t,this.#t=e,this.#s=null,this.#o=Ns(),this.options.experimental_prefetchInRender||this.#o.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;#i;#a;#o;#s;#m;#f;#p;#l;#d;#c;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),Za(this.#e,this.options)?this.#u():this.updateResult(),this.#b())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return $s(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return $s(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#v(),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 ot(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#e.setOptions(this.options),t._defaulted&&!js(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&Ka(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||ot(this.options.enabled,this.#e)!==ot(t.enabled,this.#e)||kn(this.options.staleTime,this.#e)!==kn(t.staleTime,this.#e))&&this.#g();const i=this.#_();r&&(this.#e!==n||ot(this.options.enabled,this.#e)!==ot(t.enabled,this.#e)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return Pp(this,n)&&(this.#r=n,this.#a=this.options,this.#i=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.#S();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Je)),t}#g(){this.#v();const e=kn(this.options.staleTime,this.#e);if(on||this.#r.isStale||!Ps(e))return;const n=Vl(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}#y(e){this.#w(),this.#c=e,!(on||ot(this.options.enabled,this.#e)===!1||!Ps(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||Ro.isFocused())&&this.#u()},this.#c))}#b(){this.#g(),this.#y(this.#_())}#v(){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,i=this.#r,s=this.#i,a=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,p;if(t._optimisticResults){const I=this.hasListeners(),N=!I&&Za(e,t),F=I&&Ka(e,n,t,r);(N||F)&&(u={...u,...td(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:g,errorUpdatedAt:y,status:m}=u;p=u.data;let b=!1;if(t.placeholderData!==void 0&&p===void 0&&m==="pending"){let I;i?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(I=i.data,b=!0):I=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,I!==void 0&&(m="success",p=Ds(i?.data,I,t),f=!0)}if(t.select&&p!==void 0&&!b)if(i&&p===s?.data&&t.select===this.#m)p=this.#f;else try{this.#m=t.select,p=t.select(p),p=Ds(i?.data,p,t),this.#f=p,this.#s=null}catch(I){this.#s=I}this.#s&&(g=this.#s,p=this.#f,y=Date.now(),m="error");const _=u.fetchStatus==="fetching",k=m==="pending",E=m==="error",A=k&&_,$=p!==void 0,C={status:m,fetchStatus:u.fetchStatus,isPending:k,isSuccess:m==="success",isError:E,isInitialLoading:A,isLoading:A,data:p,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:_,isRefetching:_&&!k,isLoadingError:E&&!$,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:E&&$,isStale:To(e,t),refetch:this.refetch,promise:this.#o};if(this.options.experimental_prefetchInRender){const I=se=>{C.status==="error"?se.reject(C.error):C.data!==void 0&&se.resolve(C.data)},N=()=>{const se=this.#o=C.promise=Ns();I(se)},F=this.#o;switch(F.status){case"pending":e.queryHash===n.queryHash&&I(F);break;case"fulfilled":(C.status==="error"||C.data!==F.value)&&N();break;case"rejected":(C.status!=="error"||C.error!==F.reason)&&N();break}}return C}updateResult(){const e=this.#r,t=this.createResult(this.#e,this.options);if(this.#i=this.#e.state,this.#a=this.options,this.#i.data!==void 0&&(this.#p=this.#e),js(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#h.size)return!0;const s=new Set(i??this.#h);return this.options.throwOnError&&s.add("error"),Object.keys(this.#r).some(a=>{const c=a;return this.#r[c]!==e[c]&&s.has(c)})};this.#k({listeners:n()})}#S(){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.#b()}#k(e){De.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function Op(e,t){return ot(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Za(e,t){return Op(e,t)||e.state.data!==void 0&&$s(e,t,t.refetchOnMount)}function $s(e,t,n){if(ot(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&To(e,t)}return!1}function Ka(e,t,n,r){return(e!==t||ot(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&To(e,n)}function To(e,t){return ot(t.enabled,e)!==!1&&e.isStaleByTime(kn(t.staleTime,e))}function Pp(e,t){return!js(e.getCurrentResult(),t)}var Co=S.createContext(void 0),jp=e=>{const t=S.useContext(Co);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},$I=({client:e,children:t})=>(S.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),dp.jsx(Co.Provider,{value:e,children:t})),rd=S.createContext(!1),Mp=()=>S.useContext(rd);rd.Provider;function Dp(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Np=S.createContext(Dp()),Lp=()=>S.useContext(Np);function $p(e,t){return typeof e=="function"?e(...t):!!e}function Va(){}var Up=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},Fp=e=>{S.useEffect(()=>{e.clearReset()},[e])},Bp=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||$p(n,[e.error,r])),Gp=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)))},Hp=(e,t)=>e.isLoading&&e.isFetching&&!t,zp=(e,t)=>e?.suspense&&t.isPending,Ya=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Wp(e,t,n){const r=jp(n),i=Mp(),s=Lp(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=i?"isRestoring":"optimistic",Gp(a),Up(a,s),Fp(s);const c=!r.getQueryCache().get(a.queryHash),[l]=S.useState(()=>new t(r,a)),d=l.getOptimisticResult(a),u=!i&&e.subscribed!==!1;if(S.useSyncExternalStore(S.useCallback(f=>{const p=u?l.subscribe(De.batchCalls(f)):Va;return l.updateResult(),p},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),S.useEffect(()=>{l.setOptions(a)},[a,l]),zp(a,d))throw Ya(a,l,s);if(Bp({result:d,errorResetBoundary:s,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw d.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!on&&Hp(d,i)&&(c?Ya(a,l,s):r.getQueryCache().get(a.queryHash)?.promise)?.catch(Va).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function id(e,t){return Wp(e,Ap,t)}const Zp=()=>{const e=S.useContext(Co)??null,t=S.useMemo(()=>new Cp({defaultOptions:{queries:{enabled:!1,retry:!1,gcTime:0}}}),[]);return S.useEffect(()=>{if(!e)return()=>t.clear()},[e,t]),S.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function UI(e){return e!=="detached"&&e!=="wedged"}function sd(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function FI(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=sd(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 re;(function(e){e.assertEqual=i=>i;function t(i){}e.assertIs=t;function n(i){throw new Error}e.assertNever=n,e.arrayToEnum=i=>{const s={};for(const a of i)s[a]=a;return s},e.getValidEnumValues=i=>{const s=e.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),a={};for(const c of s)a[c]=i[c];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const s=[];for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},e.find=(i,s)=>{for(const a of i)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(re||(re={}));var Us;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Us||(Us={}));const M=re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kt=e=>{switch(typeof e){case"undefined":return M.undefined;case"string":return M.string;case"number":return isNaN(e)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(e)?M.array:e===null?M.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?M.promise:typeof Map<"u"&&e instanceof Map?M.map:typeof Set<"u"&&e instanceof Set?M.set:typeof Date<"u"&&e instanceof Date?M.date:M.object;default:return M.unknown}},R=re.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"]),Kp=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Ye extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(s){return s.message},r={_errors:[]},i=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){const d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return i(this),r}static assert(t){if(!(t instanceof Ye))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,re.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const i of this.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Ye.create=e=>new Ye(e);const Tn=(e,t)=>{let n;switch(e.code){case R.invalid_type:e.received===M.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case R.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,re.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:n=`Unrecognized key(s) in object: ${re.joinValues(e.keys,", ")}`;break;case R.invalid_union:n="Invalid input";break;case R.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${re.joinValues(e.options)}`;break;case R.invalid_enum_value:n=`Invalid enum value. Expected ${re.joinValues(e.options)}, received '${e.received}'`;break;case R.invalid_arguments:n="Invalid function arguments";break;case R.invalid_return_type:n="Invalid function return type";break;case R.invalid_date:n="Invalid date";break;case R.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}"`:re.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case R.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 R.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 R.custom:n="Invalid input";break;case R.invalid_intersection_types:n="Intersection results could not be merged";break;case R.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case R.not_finite:n="Number must be finite";break;default:n=t.defaultError,re.assertNever(e)}return{message:n}};let od=Tn;function Vp(e){od=e}function ai(){return od}const ci=e=>{const{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let c="";const l=r.filter(d=>!!d).slice().reverse();for(const d of l)c=d(a,{data:t,defaultError:c}).message;return{...i,path:s,message:c}},Yp=[];function j(e,t){const n=ai(),r=ci({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Tn?void 0:Tn].filter(i=>!!i)});e.common.issues.push(r)}class $e{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 i of n){if(i.status==="aborted")return W;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const i of n){const s=await i.key,a=await i.value;r.push({key:s,value:a})}return $e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const i of n){const{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return W;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}}const W=Object.freeze({status:"aborted"}),vn=e=>({status:"dirty",value:e}),Ue=e=>({status:"valid",value:e}),Fs=e=>e.status==="aborted",Bs=e=>e.status==="dirty",an=e=>e.status==="valid",ar=e=>typeof Promise<"u"&&e instanceof Promise;function li(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 ad(e,t,n,r,i){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 U;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(U||(U={}));var Yn,Qn;class gt{constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}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 Qa=(e,t)=>{if(an(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 Ye(e.common.issues);return this._error=n,this._error}}};function X(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:i}=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:i}:{errorMap:(a,c)=>{var l,d;const{message:u}=e;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??r)!==null&&l!==void 0?l:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??n)!==null&&d!==void 0?d:c.defaultError}},description:i}}class J{get description(){return this._def.description}_getType(t){return kt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:kt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new $e,ctx:{common:t.parent.common,data:t.data,parsedType:kt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(ar(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 i={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:kt(t)},s=this._parseSync({data:t,path:i.path,parent:i});return Qa(i,s)}"~validate"(t){var n,r;const i={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:kt(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:i});return an(s)?{value:s.value}:{issues:i.common.issues}}catch(s){!((r=(n=s?.message)===null||n===void 0?void 0:n.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),i.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:i}).then(s=>an(s)?{value:s.value}:{issues:i.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:kt(t)},i=this._parse({data:t,path:r.path,parent:r}),s=await(ar(i)?i:Promise.resolve(i));return Qa(r,s)}refine(t,n){const r=i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,s)=>{const a=t(i),c=()=>s.addIssue({code:R.custom,...r(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(t){return new lt({schema:this,typeName:H.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 ht.create(this,this._def)}nullable(){return Gt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ct.create(this)}promise(){return An.create(this,this._def)}or(t){return ur.create([this,t],this._def)}and(t){return fr.create(this,t,this._def)}transform(t){return new lt({...X(this._def),schema:this,typeName:H.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new _r({...X(this._def),innerType:this,defaultValue:n,typeName:H.ZodDefault})}brand(){return new Ao({typeName:H.ZodBranded,type:this,...X(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new yr({...X(this._def),innerType:this,catchValue:n,typeName:H.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Cr.create(this,t)}readonly(){return br.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Qp=/^c[^\s-]{8,}$/i,Xp=/^[0-9a-z]+$/,Jp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,qp=/^[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,eh=/^[a-z0-9_-]{21}$/i,th=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nh=/^[-+]?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)?)??$/,rh=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ih="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Xi;const sh=/^(?:(?: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])$/,oh=/^(?:(?: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])$/,ah=/^(([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]))$/,ch=/^(([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])$/,lh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,dh=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,cd="((\\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])))",uh=new RegExp(`^${cd}$`);function ld(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 fh(e){return new RegExp(`^${ld(e)}$`)}function dd(e){let t=`${cd}T${ld(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 ph(e,t){return!!((t==="v4"||!t)&&sh.test(e)||(t==="v6"||!t)&&ah.test(e))}function hh(e,t){if(!th.test(e))return!1;try{const[n]=e.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||!i.typ||!i.alg||t&&i.alg!==t)}catch{return!1}}function mh(e,t){return!!((t==="v4"||!t)&&oh.test(e)||(t==="v6"||!t)&&ch.test(e))}class at extends J{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==M.string){const s=this._getOrReturnCtx(t);return j(s,{code:R.invalid_type,expected:M.string,received:s.parsedType}),W}const r=new $e;let i;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(i=this._getOrReturnCtx(t,i),j(i,{code:R.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(i=this._getOrReturnCtx(t,i),j(i,{code:R.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,c=t.data.length<s.value;(a||c)&&(i=this._getOrReturnCtx(t,i),a?j(i,{code:R.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&j(i,{code:R.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")rh.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"email",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Xi||(Xi=new RegExp(ih,"u")),Xi.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"emoji",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")qp.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"uuid",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")eh.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"nanoid",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Qp.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"cuid",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Xp.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"cuid2",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Jp.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"ulid",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),j(i,{validation:"url",code:R.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"regex",code:R.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(t,i),j(i,{code:R.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(i=this._getOrReturnCtx(t,i),j(i,{code:R.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(i=this._getOrReturnCtx(t,i),j(i,{code:R.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?dd(s).test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{code:R.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?uh.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{code:R.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?fh(s).test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{code:R.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?nh.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"duration",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?ph(t.data,s.version)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"ip",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?hh(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"jwt",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?mh(t.data,s.version)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"cidr",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?lh.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"base64",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?dh.test(t.data)||(i=this._getOrReturnCtx(t,i),j(i,{validation:"base64url",code:R.invalid_string,message:s.message}),r.dirty()):re.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:R.invalid_string,...U.errToObj(r)})}_addCheck(t){return new at({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...U.errToObj(t)})}url(t){return this._addCheck({kind:"url",...U.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...U.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...U.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...U.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...U.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...U.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...U.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...U.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...U.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...U.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...U.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...U.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,...U.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,...U.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...U.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...U.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...U.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...U.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...U.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...U.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...U.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...U.errToObj(n)})}nonempty(t){return this.min(1,U.errToObj(t))}trim(){return new at({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new at({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new at({...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}}at.create=e=>{var t;return new at({checks:[],typeName:H.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...X(e)})};function gh(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,s=parseInt(e.toFixed(i).replace(".","")),a=parseInt(t.toFixed(i).replace(".",""));return s%a/Math.pow(10,i)}class Ut extends J{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)!==M.number){const s=this._getOrReturnCtx(t);return j(s,{code:R.invalid_type,expected:M.number,received:s.parsedType}),W}let r;const i=new $e;for(const s of this._def.checks)s.kind==="int"?re.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),j(r,{code:R.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:R.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:R.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?gh(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),j(r,{code:R.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),j(r,{code:R.not_finite,message:s.message}),i.dirty()):re.assertNever(s);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,U.toString(n))}gt(t,n){return this.setLimit("min",t,!1,U.toString(n))}lte(t,n){return this.setLimit("max",t,!0,U.toString(n))}lt(t,n){return this.setLimit("max",t,!1,U.toString(n))}setLimit(t,n,r,i){return new Ut({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:U.toString(i)}]})}_addCheck(t){return new Ut({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:U.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:U.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:U.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.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"&&re.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)}}Ut.create=e=>new Ut({checks:[],typeName:H.ZodNumber,coerce:e?.coerce||!1,...X(e)});class Ft extends J{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)!==M.bigint)return this._getInvalidInput(t);let r;const i=new $e;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:R.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:R.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),j(r,{code:R.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):re.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return j(n,{code:R.invalid_type,expected:M.bigint,received:n.parsedType}),W}gte(t,n){return this.setLimit("min",t,!0,U.toString(n))}gt(t,n){return this.setLimit("min",t,!1,U.toString(n))}lte(t,n){return this.setLimit("max",t,!0,U.toString(n))}lt(t,n){return this.setLimit("max",t,!1,U.toString(n))}setLimit(t,n,r,i){return new Ft({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:U.toString(i)}]})}_addCheck(t){return new Ft({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:U.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}}Ft.create=e=>{var t;return new Ft({checks:[],typeName:H.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...X(e)})};class cr extends J{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==M.boolean){const r=this._getOrReturnCtx(t);return j(r,{code:R.invalid_type,expected:M.boolean,received:r.parsedType}),W}return Ue(t.data)}}cr.create=e=>new cr({typeName:H.ZodBoolean,coerce:e?.coerce||!1,...X(e)});class cn extends J{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==M.date){const s=this._getOrReturnCtx(t);return j(s,{code:R.invalid_type,expected:M.date,received:s.parsedType}),W}if(isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return j(s,{code:R.invalid_date}),W}const r=new $e;let i;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),j(i,{code:R.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(i=this._getOrReturnCtx(t,i),j(i,{code:R.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):re.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new cn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:U.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:U.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}}cn.create=e=>new cn({checks:[],coerce:e?.coerce||!1,typeName:H.ZodDate,...X(e)});class di extends J{_parse(t){if(this._getType(t)!==M.symbol){const r=this._getOrReturnCtx(t);return j(r,{code:R.invalid_type,expected:M.symbol,received:r.parsedType}),W}return Ue(t.data)}}di.create=e=>new di({typeName:H.ZodSymbol,...X(e)});class lr extends J{_parse(t){if(this._getType(t)!==M.undefined){const r=this._getOrReturnCtx(t);return j(r,{code:R.invalid_type,expected:M.undefined,received:r.parsedType}),W}return Ue(t.data)}}lr.create=e=>new lr({typeName:H.ZodUndefined,...X(e)});class dr extends J{_parse(t){if(this._getType(t)!==M.null){const r=this._getOrReturnCtx(t);return j(r,{code:R.invalid_type,expected:M.null,received:r.parsedType}),W}return Ue(t.data)}}dr.create=e=>new dr({typeName:H.ZodNull,...X(e)});class Cn extends J{constructor(){super(...arguments),this._any=!0}_parse(t){return Ue(t.data)}}Cn.create=e=>new Cn({typeName:H.ZodAny,...X(e)});class tn extends J{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ue(t.data)}}tn.create=e=>new tn({typeName:H.ZodUnknown,...X(e)});class It extends J{_parse(t){const n=this._getOrReturnCtx(t);return j(n,{code:R.invalid_type,expected:M.never,received:n.parsedType}),W}}It.create=e=>new It({typeName:H.ZodNever,...X(e)});class ui extends J{_parse(t){if(this._getType(t)!==M.undefined){const r=this._getOrReturnCtx(t);return j(r,{code:R.invalid_type,expected:M.void,received:r.parsedType}),W}return Ue(t.data)}}ui.create=e=>new ui({typeName:H.ZodVoid,...X(e)});class ct extends J{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==M.array)return j(n,{code:R.invalid_type,expected:M.array,received:n.parsedType}),W;if(i.exactLength!==null){const a=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(a||c)&&(j(n,{code:a?R.too_big:R.too_small,minimum:c?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(j(n,{code:R.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(j(n,{code:R.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>i.type._parseAsync(new gt(n,a,n.path,c)))).then(a=>$e.mergeArray(r,a));const s=[...n.data].map((a,c)=>i.type._parseSync(new gt(n,a,n.path,c)));return $e.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new ct({...this._def,minLength:{value:t,message:U.toString(n)}})}max(t,n){return new ct({...this._def,maxLength:{value:t,message:U.toString(n)}})}length(t,n){return new ct({...this._def,exactLength:{value:t,message:U.toString(n)}})}nonempty(t){return this.min(1,t)}}ct.create=(e,t)=>new ct({type:e,minLength:null,maxLength:null,exactLength:null,typeName:H.ZodArray,...X(t)});function _n(e){if(e instanceof we){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=ht.create(_n(r))}return new we({...e._def,shape:()=>t})}else return e instanceof ct?new ct({...e._def,type:_n(e.element)}):e instanceof ht?ht.create(_n(e.unwrap())):e instanceof Gt?Gt.create(_n(e.unwrap())):e instanceof _t?_t.create(e.items.map(t=>_n(t))):e}class we extends J{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=re.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==M.object){const d=this._getOrReturnCtx(t);return j(d,{code:R.invalid_type,expected:M.object,received:d.parsedType}),W}const{status:r,ctx:i}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof It&&this._def.unknownKeys==="strip"))for(const d in i.data)a.includes(d)||c.push(d);const l=[];for(const d of a){const u=s[d],f=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new gt(i,f,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof It){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")c.length>0&&(j(i,{code:R.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=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new gt(i,f,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of l){const f=await u.key,p=await u.value;d.push({key:f,value:p,alwaysSet:u.alwaysSet})}return d}).then(d=>$e.mergeObjectSync(r,d)):$e.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return U.errToObj,new we({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var i,s,a,c;const l=(a=(s=(i=this._def).errorMap)===null||s===void 0?void 0:s.call(i,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=U.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new we({...this._def,unknownKeys:"strip"})}passthrough(){return new we({...this._def,unknownKeys:"passthrough"})}extend(t){return new we({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new we({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:H.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new we({...this._def,catchall:t})}pick(t){const n={};return re.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new we({...this._def,shape:()=>n})}omit(t){const n={};return re.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new we({...this._def,shape:()=>n})}deepPartial(){return _n(this)}partial(t){const n={};return re.objectKeys(this.shape).forEach(r=>{const i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}),new we({...this._def,shape:()=>n})}required(t){const n={};return re.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof ht;)s=s._def.innerType;n[r]=s}}),new we({...this._def,shape:()=>n})}keyof(){return ud(re.objectKeys(this.shape))}}we.create=(e,t)=>new we({shape:()=>e,unknownKeys:"strip",catchall:It.create(),typeName:H.ZodObject,...X(t)});we.strictCreate=(e,t)=>new we({shape:()=>e,unknownKeys:"strict",catchall:It.create(),typeName:H.ZodObject,...X(t)});we.lazycreate=(e,t)=>new we({shape:e,unknownKeys:"strip",catchall:It.create(),typeName:H.ZodObject,...X(t)});class ur extends J{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function i(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const a=s.map(c=>new Ye(c.ctx.common.issues));return j(n,{code:R.invalid_union,unionErrors:a}),W}if(n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(i);{let s;const a=[];for(const l of r){const d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const c=a.map(l=>new Ye(l));return j(n,{code:R.invalid_union,unionErrors:c}),W}}get options(){return this._def.options}}ur.create=(e,t)=>new ur({options:e,typeName:H.ZodUnion,...X(t)});const wt=e=>e instanceof hr?wt(e.schema):e instanceof lt?wt(e.innerType()):e instanceof mr?[e.value]:e instanceof Bt?e.options:e instanceof gr?re.objectValues(e.enum):e instanceof _r?wt(e._def.innerType):e instanceof lr?[void 0]:e instanceof dr?[null]:e instanceof ht?[void 0,...wt(e.unwrap())]:e instanceof Gt?[null,...wt(e.unwrap())]:e instanceof Ao||e instanceof br?wt(e.unwrap()):e instanceof yr?wt(e._def.innerType):[];class Ei extends J{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==M.object)return j(n,{code:R.invalid_type,expected:M.object,received:n.parsedType}),W;const r=this.discriminator,i=n.data[r],s=this.optionsMap.get(i);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(j(n,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),W)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const i=new Map;for(const s of n){const a=wt(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of a){if(i.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);i.set(c,s)}}return new Ei({typeName:H.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...X(r)})}}function Gs(e,t){const n=kt(e),r=kt(t);if(e===t)return{valid:!0,data:e};if(n===M.object&&r===M.object){const i=re.objectKeys(t),s=re.objectKeys(e).filter(c=>i.indexOf(c)!==-1),a={...e,...t};for(const c of s){const l=Gs(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===M.array&&r===M.array){if(e.length!==t.length)return{valid:!1};const i=[];for(let s=0;s<e.length;s++){const a=e[s],c=t[s],l=Gs(a,c);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===M.date&&r===M.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class fr extends J{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),i=(s,a)=>{if(Fs(s)||Fs(a))return W;const c=Gs(s.value,a.value);return c.valid?((Bs(s)||Bs(a))&&n.dirty(),{status:n.value,value:c.data}):(j(r,{code:R.invalid_intersection_types}),W)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>i(s,a)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}fr.create=(e,t,n)=>new fr({left:e,right:t,typeName:H.ZodIntersection,...X(n)});class _t extends J{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==M.array)return j(r,{code:R.invalid_type,expected:M.array,received:r.parsedType}),W;if(r.data.length<this._def.items.length)return j(r,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&r.data.length>this._def.items.length&&(j(r,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new gt(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>$e.mergeArray(n,a)):$e.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new _t({...this._def,rest:t})}}_t.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _t({items:e,typeName:H.ZodTuple,rest:null,...X(t)})};class pr extends J{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!==M.object)return j(r,{code:R.invalid_type,expected:M.object,received:r.parsedType}),W;const i=[],s=this._def.keyType,a=this._def.valueType;for(const c in r.data)i.push({key:s._parse(new gt(r,c,r.path,c)),value:a._parse(new gt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?$e.mergeObjectAsync(n,i):$e.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof J?new pr({keyType:t,valueType:n,typeName:H.ZodRecord,...X(r)}):new pr({keyType:at.create(),valueType:t,typeName:H.ZodRecord,...X(n)})}}class fi extends J{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!==M.map)return j(r,{code:R.invalid_type,expected:M.map,received:r.parsedType}),W;const i=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:i._parse(new gt(r,c,r.path,[d,"key"])),value:s._parse(new gt(r,l,r.path,[d,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of a){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return W;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const l of a){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return W;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}fi.create=(e,t,n)=>new fi({valueType:t,keyType:e,typeName:H.ZodMap,...X(n)});class ln extends J{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==M.set)return j(r,{code:R.invalid_type,expected:M.set,received:r.parsedType}),W;const i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(j(r,{code:R.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(j(r,{code:R.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());const s=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return W;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>s._parse(new gt(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new ln({...this._def,minSize:{value:t,message:U.toString(n)}})}max(t,n){return new ln({...this._def,maxSize:{value:t,message:U.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}ln.create=(e,t)=>new ln({valueType:e,minSize:null,maxSize:null,typeName:H.ZodSet,...X(t)});class En extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==M.function)return j(n,{code:R.invalid_type,expected:M.function,received:n.parsedType}),W;function r(c,l){return ci({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ai(),Tn].filter(d=>!!d),issueData:{code:R.invalid_arguments,argumentsError:l}})}function i(c,l){return ci({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ai(),Tn].filter(d=>!!d),issueData:{code:R.invalid_return_type,returnTypeError:l}})}const s={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof An){const c=this;return Ue(async function(...l){const d=new Ye([]),u=await c._def.args.parseAsync(l,s).catch(g=>{throw d.addIssue(r(l,g)),d}),f=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(f,s).catch(g=>{throw d.addIssue(i(f,g)),d})})}else{const c=this;return Ue(function(...l){const d=c._def.args.safeParse(l,s);if(!d.success)throw new Ye([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,s);if(!f.success)throw new Ye([i(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new En({...this._def,args:_t.create(t).rest(tn.create())})}returns(t){return new En({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new En({args:t||_t.create([]).rest(tn.create()),returns:n||tn.create(),typeName:H.ZodFunction,...X(r)})}}class hr extends J{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})}}hr.create=(e,t)=>new hr({getter:e,typeName:H.ZodLazy,...X(t)});class mr extends J{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return j(n,{received:n.data,code:R.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:t.data}}get value(){return this._def.value}}mr.create=(e,t)=>new mr({value:e,typeName:H.ZodLiteral,...X(t)});function ud(e,t){return new Bt({values:e,typeName:H.ZodEnum,...X(t)})}class Bt extends J{constructor(){super(...arguments),Yn.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return j(n,{expected:re.joinValues(r),received:n.parsedType,code:R.invalid_type}),W}if(li(this,Yn)||ad(this,Yn,new Set(this._def.values)),!li(this,Yn).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return j(n,{received:n.data,code:R.invalid_enum_value,options:r}),W}return Ue(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 Bt.create(t,{...this._def,...n})}exclude(t,n=this._def){return Bt.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Yn=new WeakMap;Bt.create=ud;class gr extends J{constructor(){super(...arguments),Qn.set(this,void 0)}_parse(t){const n=re.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==M.string&&r.parsedType!==M.number){const i=re.objectValues(n);return j(r,{expected:re.joinValues(i),received:r.parsedType,code:R.invalid_type}),W}if(li(this,Qn)||ad(this,Qn,new Set(re.getValidEnumValues(this._def.values))),!li(this,Qn).has(t.data)){const i=re.objectValues(n);return j(r,{received:r.data,code:R.invalid_enum_value,options:i}),W}return Ue(t.data)}get enum(){return this._def.values}}Qn=new WeakMap;gr.create=(e,t)=>new gr({values:e,typeName:H.ZodNativeEnum,...X(t)});class An extends J{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==M.promise&&n.common.async===!1)return j(n,{code:R.invalid_type,expected:M.promise,received:n.parsedType}),W;const r=n.parsedType===M.promise?n.data:Promise.resolve(n.data);return Ue(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}}An.create=(e,t)=>new An({type:e,typeName:H.ZodPromise,...X(t)});class lt extends J{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===H.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,s={addIssue:a=>{j(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){const a=i.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return W;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?W:l.status==="dirty"||n.value==="dirty"?vn(l.value):l});{if(n.value==="aborted")return W;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?W:c.status==="dirty"||n.value==="dirty"?vn(c.value):c}}if(i.type==="refinement"){const a=c=>{const l=i.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?W:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?W:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(i.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!an(a))return a;const c=i.transform(a.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>an(a)?Promise.resolve(i.transform(a.value,s)).then(c=>({status:n.value,value:c})):a);re.assertNever(i)}}lt.create=(e,t,n)=>new lt({schema:e,typeName:H.ZodEffects,effect:t,...X(n)});lt.createWithPreprocess=(e,t,n)=>new lt({schema:t,effect:{type:"preprocess",transform:e},typeName:H.ZodEffects,...X(n)});class ht extends J{_parse(t){return this._getType(t)===M.undefined?Ue(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ht.create=(e,t)=>new ht({innerType:e,typeName:H.ZodOptional,...X(t)});class Gt extends J{_parse(t){return this._getType(t)===M.null?Ue(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Gt.create=(e,t)=>new Gt({innerType:e,typeName:H.ZodNullable,...X(t)});class _r extends J{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===M.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}_r.create=(e,t)=>new _r({innerType:e,typeName:H.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...X(t)});class yr extends J{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ar(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ye(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ye(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}yr.create=(e,t)=>new yr({innerType:e,typeName:H.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...X(t)});class pi extends J{_parse(t){if(this._getType(t)!==M.nan){const r=this._getOrReturnCtx(t);return j(r,{code:R.invalid_type,expected:M.nan,received:r.parsedType}),W}return{status:"valid",value:t.data}}}pi.create=e=>new pi({typeName:H.ZodNaN,...X(e)});const _h=Symbol("zod_brand");class Ao extends J{_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 Cr extends J{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?W:s.status==="dirty"?(n.dirty(),vn(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?W:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new Cr({in:t,out:n,typeName:H.ZodPipeline})}}class br extends J{_parse(t){const n=this._def.innerType._parse(t),r=i=>(an(i)&&(i.value=Object.freeze(i.value)),i);return ar(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}}br.create=(e,t)=>new br({innerType:e,typeName:H.ZodReadonly,...X(t)});function Xa(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function fd(e,t={},n){return e?Cn.create().superRefine((r,i)=>{var s,a;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=Xa(t,r),p=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;i.addIssue({code:"custom",...f,fatal:p})}});if(!c){const l=Xa(t,r),d=(a=(s=l.fatal)!==null&&s!==void 0?s:n)!==null&&a!==void 0?a:!0;i.addIssue({code:"custom",...l,fatal:d})}}):Cn.create()}const yh={object:we.lazycreate};var H;(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"})(H||(H={}));const bh=(e,t={message:`Input not instance of ${e.name}`})=>fd(n=>n instanceof e,t),pd=at.create,hd=Ut.create,vh=pi.create,wh=Ft.create,md=cr.create,Sh=cn.create,kh=di.create,Eh=lr.create,Ih=dr.create,xh=Cn.create,Rh=tn.create,Th=It.create,Ch=ui.create,Ah=ct.create,Oh=we.create,Ph=we.strictCreate,jh=ur.create,Mh=Ei.create,Dh=fr.create,Nh=_t.create,Lh=pr.create,$h=fi.create,Uh=ln.create,Fh=En.create,Bh=hr.create,Gh=mr.create,Hh=Bt.create,zh=gr.create,Wh=An.create,Ja=lt.create,Zh=ht.create,Kh=Gt.create,Vh=lt.createWithPreprocess,Yh=Cr.create,Qh=()=>pd().optional(),Xh=()=>hd().optional(),Jh=()=>md().optional(),qh={string:e=>at.create({...e,coerce:!0}),number:e=>Ut.create({...e,coerce:!0}),boolean:e=>cr.create({...e,coerce:!0}),bigint:e=>Ft.create({...e,coerce:!0}),date:e=>cn.create({...e,coerce:!0})},em=W;var o=Object.freeze({__proto__:null,defaultErrorMap:Tn,setErrorMap:Vp,getErrorMap:ai,makeIssue:ci,EMPTY_PATH:Yp,addIssueToContext:j,ParseStatus:$e,INVALID:W,DIRTY:vn,OK:Ue,isAborted:Fs,isDirty:Bs,isValid:an,isAsync:ar,get util(){return re},get objectUtil(){return Us},ZodParsedType:M,getParsedType:kt,ZodType:J,datetimeRegex:dd,ZodString:at,ZodNumber:Ut,ZodBigInt:Ft,ZodBoolean:cr,ZodDate:cn,ZodSymbol:di,ZodUndefined:lr,ZodNull:dr,ZodAny:Cn,ZodUnknown:tn,ZodNever:It,ZodVoid:ui,ZodArray:ct,ZodObject:we,ZodUnion:ur,ZodDiscriminatedUnion:Ei,ZodIntersection:fr,ZodTuple:_t,ZodRecord:pr,ZodMap:fi,ZodSet:ln,ZodFunction:En,ZodLazy:hr,ZodLiteral:mr,ZodEnum:Bt,ZodNativeEnum:gr,ZodPromise:An,ZodEffects:lt,ZodTransformer:lt,ZodOptional:ht,ZodNullable:Gt,ZodDefault:_r,ZodCatch:yr,ZodNaN:pi,BRAND:_h,ZodBranded:Ao,ZodPipeline:Cr,ZodReadonly:br,custom:fd,Schema:J,ZodSchema:J,late:yh,get ZodFirstPartyTypeKind(){return H},coerce:qh,any:xh,array:Ah,bigint:wh,boolean:md,date:Sh,discriminatedUnion:Mh,effect:Ja,enum:Hh,function:Fh,instanceof:bh,intersection:Dh,lazy:Bh,literal:Gh,map:$h,nan:vh,nativeEnum:zh,never:Th,null:Ih,nullable:Kh,number:hd,object:Oh,oboolean:Jh,onumber:Xh,optional:Zh,ostring:Qh,pipeline:Yh,preprocess:Vh,promise:Wh,record:Lh,set:Uh,strictObject:Ph,string:pd,symbol:kh,transformer:Ja,tuple:Nh,undefined:Eh,union:jh,unknown:Rh,void:Ch,NEVER:em,ZodIssueCode:R,quotelessJson:Kp,ZodError:Ye});const qa=o.enum(["app_start","sign_in","window_focus","surface_open"]),gd=o.object({id:o.string().min(1),state:o.enum(["active","paused","disabled"])}).passthrough(),tm=o.object({tenant_id:o.string().min(1),tenant_name:o.string().optional(),eligible:o.boolean(),endpoint:gd.nullable()}).passthrough(),nm=o.object({code:o.string(),message:o.string(),details:o.record(o.unknown()).optional(),retry_after_seconds:o.number().optional()}).passthrough(),rm=o.object({code:o.string().min(1),count:o.number().int().nonnegative(),session:o.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),im=o.object({in_force:o.boolean(),notice_pending:o.boolean().catch(!1)}).passthrough().optional().catch(void 0),BI=o.object({capability:o.number(),consent_account_guard:o.boolean().optional(),state:o.enum(["ready","signed_out","unavailable","update_required"]),account_id:o.string().nullable(),tenant_id:o.string().nullable(),surface_state:o.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:o.object({settings:o.boolean(),inbox:o.boolean(),account_door:o.boolean(),onboarding:o.boolean()}),update_required:o.boolean(),local:o.object({enabled:o.boolean(),onboarding:o.string(),session:o.string()}),status:o.object({tenants:o.array(tm)}).passthrough().nullable(),consent:o.object({version:o.string().min(1).max(128),text:o.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:o.enum(["served","cached","embedded"])}).nullable(),error:nm.nullable(),state_note:o.string().nullable().optional(),read_only:o.boolean().optional(),delivery_hold:rm,default_on:im}).passthrough(),sm=o.object({version:o.string().min(1),consented_at:o.string().min(1),consented_via:o.string().min(1),current:o.boolean()}).passthrough(),GI=o.object({endpoint:gd.extend({tenant_id:o.string().min(1),label:o.string().optional(),consent:sm.nullable().optional(),created_at:o.string().optional(),updated_at:o.string().optional()}).nullable(),settings:o.object({tenant_id:o.string().min(1),eligible:o.boolean(),consent_version:o.string().optional(),consent_required:o.boolean()}).passthrough(),default_on:o.boolean().optional().catch(void 0)}).passthrough(),om=o.object({kind:o.enum(["endpoint","account"]).optional(),endpoint_id:o.string().min(1).optional(),account_id:o.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"),ec=o.object({direction:o.enum(["send","receive"]),effect:o.enum(["allow","deny"]),target:om,id:o.string().optional()}).passthrough(),tc=o.object({mode:o.enum(["class_default","listed_only"]),allow:o.number(),deny:o.number()}).passthrough(),HI=o.object({allowlist:o.object({tenant_id:o.string().min(1),entries:o.array(ec)}).passthrough(),view:o.object({tenant_id:o.string().nullable(),entries:o.array(ec),directions:o.object({send:tc,receive:tc}),class_default:o.literal("cos_cos"),cues:o.object({allow_entry_switches_direction_to_listed_only:o.boolean(),listed_only_affects:o.string(),removing_allow_does_not_stop_open_thread:o.boolean(),deny_stops_pair_both_directions:o.boolean()}).passthrough()}).passthrough()}).passthrough(),zI=o.object({onboarding:o.literal("seen")}).passthrough();function am(e){return e?.default_on?.in_force===!0}function WI(e,t){const n=cm(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function ZI(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function KI(e,t){if(!e||!t||am(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 cm(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const lm=8,Hs=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],dm=6*1024,um=512;function hi(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const i=[];for(const s of n){if(i.length===um)break;const c=new URLSearchParams({order_ids:s}).toString().length+1;if(r+c>dm)break;e.append("order_ids",s),i.push(s),r+=c}return i}function fm(e,t,n){return hi(new URLSearchParams(n),t,e)}const pm=/^\.+$/,hm=new RegExp("\\p{Cf}","u"),mm=/[/\\:]/,v=o.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),Br=o.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),Gr=o.string().min(1).max(32768),gm=/^[a-f0-9]{12}$/,L=o.string().regex(gm),Ji=o.string().regex(/^[a-f0-9]{12}$/),qi=o.string().min(1).max(128),_m=o.string().min(1).max(4096),Fn=o.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),es=o.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),Hr=o.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),nc=o.string().regex(/^[a-f0-9]{32}$/),ym=/^(\/|[A-Za-z]:[\\/])/,ts=o.string().min(1).max(4096).regex(ym),rc=/^[a-f0-9]{32}$/,te=o.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),ic=o.string().min(1).max(512).nullish(),mn=o.string().regex(/^[A-Za-z0-9_-]{1,128}$/),zr=o.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),bm=["credential_finite_share","credential_inheritance"],sc=/^sha256:[0-9a-f]{64}$/,oc={operation:o.enum(bm),requestDigest:o.string().regex(sc),disclosureDigest:o.string().regex(sc)},Bn=o.string().regex(/^la_[0-9a-f]{16}$/),Gn=o.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),ac=o.object({data_b64:o.string().min(1).max(1e6),mime_type:o.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:o.string().max(4096).optional()}).strict(),vm=o.object({digest:o.string().regex(/^[0-9a-f]{32}$/),name:o.string().max(1024).optional(),mime_type:o.string().max(255).optional(),bytes:o.number().int().min(0).optional(),path:o.string().max(4096).optional()}).strict(),cc=2e5,lc=8,wm=256,Sm=100,dc=16,km=256,Em=100,Im=200,xm=1e6,Rm=o.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),Me=o.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),Wr=o.object({kind:o.enum(["agent","team"]),name:Me}).strict(),_d=o.enum(["claude","codex","omp"]),Tm=o.record(o.string(),o.array(o.string().min(1).max(512)).max(5e3)),uc={sources:o.array(_d).max(3).optional(),sessionIds:Tm.optional(),all:o.boolean().optional(),includeSubagents:o.boolean().optional(),includeClearedSegments:o.boolean().optional(),includeMemory:o.boolean().optional(),includeInstructions:o.boolean().optional(),maxSessions:o.number().int().min(1).max(5e3).optional()},ns=o.object({provider:o.string().min(1).max(128),model_id:o.string().min(1).max(512),reasoning_effort:o.string().min(1).max(64).nullable(),fast_mode:o.boolean().nullable().optional()}).strict(),fc=o.object({kind:o.enum(["role","specialist"]).optional(),description:o.string().max(8e3).optional(),instructions:o.string().max(8e3).optional(),tools:o.array(o.string().min(1).max(128)).max(256).optional(),effort:o.string().max(64).optional(),delegate:o.boolean().optional(),action_class:o.enum(["reactive","proactive"]).optional()}).strict(),pc=o.object({name:o.string().min(1).max(64).optional(),description:o.string().max(8e3).optional(),manager:Me.optional(),members:o.array(o.object({role:Me,count:o.number().int().min(1).max(16),kind:o.enum(["agent","team"]),tier:o.enum(["lo","med","hi"]).nullable().optional(),effort:Rm.nullable().optional()}).strict()).max(128).optional(),instructions:o.string().max(8e3).optional(),project:o.string().max(8e3).optional()}).strict(),Cm=o.record(o.array(o.string().max(1024)).max(100)),rs=o.array(v).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),Am=o.array(o.object({kind:o.enum(["human","agent"]),account_id:v,endpoint_id:v.optional()}).strict()).max(50).refine(e=>new Set(e.map(t=>`${t.kind}:${t.account_id}:${t.endpoint_id??""}`)).size===e.length,"Duplicate mention"),hc=o.enum(["minutes","hours","days"]);function Om(e){return!pm.test(e)}const VI=e=>ni.safeParse(e).success,ni=o.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(Om),mc=o.enum(["str","int","float","bool","list","dict"]),gc=o.string().max(16384),Pm=2e3,_c=o.string().min(1).max(Pm),yc=o.string().min(1).max(64),jm=o.string().min(1).max(64),Mm=o.string().min(1).max(64),bc=o.object({is_active:o.boolean().nullish(),one_time:o.boolean().nullish(),start_time_utc:o.string().max(64).nullish(),end_time_utc:o.string().max(64).nullish()}).strict(),Dm=o.object({conversation_length:o.number().int().optional(),detail_length:o.number().int().optional(),max_learnings_history:o.number().int().optional(),hosting:o.string().max(256).optional(),model_name:o.string().max(1024).optional(),auto_save_conversation:o.boolean().optional()}).strict(),zs=128,vc=2e3,wc=8e3,Sc=64,kc=64,Ii=e=>[...e].length,Ws=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,Nm=e=>e===9||e===10||e===11||e===12||e===13||e===133,Lm=e=>e<=31||e>=127&&e<=159,$m=e=>hm.test(String.fromCodePoint(e)),Um=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,Zr=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},yd=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&Ws(t[n].codePointAt(0)??0);)n++;for(;r>n&&Ws(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},Fm=e=>{let t="",n=!1;for(const r of e){if(Ws(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function Bm(e){const t=yd(e);if(!t)return"must not be empty";if(Ii(t)>zs)return`must be at most ${zs} characters`;if(mm.test(t))return'must not contain "/", "\\" or ":"';if(Zr(t,Um))return"must not contain Unicode bidirectional override characters";if(Zr(t,Nm))return"must not contain whitespace";if(Zr(t,Lm))return"must not contain control characters";if(Zr(t,$m))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 YI(e){return Fm(yd(e).normalize("NFKC").toLowerCase())}function Gm(e){return e.trim()?Ii(e)>vc?`must be at most ${vc} characters`:null:"must not be empty"}function Hm(e){return e.trim()?Ii(e)>wc?`must be at most ${wc} characters`:null:"must not be empty"}function zm(e){if(e.length>kc)return`must hold at most ${kc} items`;for(const t of e)if(!t.trim()||Ii(t)>Sc)return`must hold items of 1 to ${Sc} characters`;return null}const Wm=e=>Bm(e)===null,Zm=o.string().refine(Wm,{message:"That is not a name the hub can publish."}),Km=o.string().refine(e=>Hm(e)===null,{message:"That instruction body cannot be published."}),Vm=o.string().refine(e=>Gm(e)===null,{message:"That description cannot be published."}),Ym=o.array(o.string()).refine(e=>zm(e)===null,{message:"That tool list cannot be published."}),is={requestId:te.optional(),subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()},Ec=o.object({name:Zm,description:Vm,instructions:Km,kind:o.enum(["role","specialist"]),when_to_use:o.string(),tools:Ym,effort:o.string(),delegate:o.boolean(),version:o.string(),categories:o.array(o.string()),tags:o.array(o.string())}).partial().strict(),Qm=o.enum(["team","agent"]),Xm=o.string().min(1).max(64),Jm=o.string().min(1).max(256),bd=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ss=o.string().regex(bd,{message:"Letters, digits, dot, underscore and dash; no spaces."}),qm=["planning","active","qa","validation","done","paused","archived"],Ic=o.enum(qm),Kr=o.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),xc=o.array(o.string().min(1).max(24)).max(8),Mt=o.string().min(1).max(64),eg=1e3,Rc=240,Tc=80,tg=256,ng=100,rg=200,ig=/^[a-z0-9][a-z0-9_-]{0,23}$/;function QI(e){return e?bd.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 XI(e){return ig.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const Vr=o.enum(["agent","team","skill"]),os=o.string().min(1).max(128).regex(/\S/),Cc=o.enum(Hs),sg=o.object({visible:o.array(Cc).max(Hs.length),more:o.array(Cc).max(Hs.length)}).strict(),Et=o.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),Ac=o.object({selectionToken:o.string().min(1).max(512),reconcileIds:o.array(Et).max(500).optional(),excludedIds:o.array(Et).max(500).optional()}).strict(),og=o.object({operationToken:o.string().min(1).max(512),reconcileIds:o.array(Et).max(500).optional()}).strict(),Oc=o.union([o.object({throughSeq:o.number().int().min(0).optional(),receipt:o.literal(!0).optional(),reconcileIds:o.array(Et).max(500).optional(),items:o.array(o.object({id:Et,revision:o.number().int().min(1)}).strict()).min(1).max(500)}).strict(),o.object({sessionId:L,throughSeq:o.number().int().min(0),observed:o.array(o.object({id:Et,revision:o.number().int().min(1)}).strict()).max(500)}).strict(),o.object({all:o.literal(!0),throughSeq:o.number().int().min(0),observed:o.array(o.object({id:Et,revision:o.number().int().min(1)}).strict()).max(500)}).strict()]),ag={pointer:"pointerdown",key:"keydown",wheel:"wheel"},cg=o.discriminatedUnion("op",[o.object({op:o.literal("capabilities")}).strict(),o.object({op:o.literal("runtimes.list")}).strict(),o.object({op:o.literal("profiles.list")}).strict(),o.object({op:o.literal("profiles.get"),name:Me}).strict(),o.object({op:o.literal("imports.sources")}).strict(),o.object({op:o.literal("imports.sessions"),source:_d,includeSubagents:o.boolean().optional()}).strict(),o.object({op:o.literal("imports.preview"),...uc}).strict(),o.object({op:o.literal("imports.start"),...uc}).strict(),o.object({op:o.literal("imports.status"),jobId:o.string().min(1).max(128)}).strict(),o.object({op:o.literal("imports.cancel"),jobId:o.string().min(1).max(128)}).strict(),o.object({op:o.literal("profiles.update"),name:Me,requestId:te,fields:fc,expectedDefinitionRevision:ic.optional()}).strict(),o.object({op:o.literal("profiles.install"),name:Me,requestId:te}).strict(),o.object({op:o.literal("profiles.create"),name:Me,requestId:te,fields:fc.extend({description:o.string().max(8e3),instructions:o.string().min(1).max(8e3)})}).strict(),o.object({op:o.literal("hub.updates")}).strict(),o.object({op:o.literal("hub.skillPull"),requestId:te,hubId:v,hubSource:o.string().min(1).max(2048),visibility:o.enum(["public","org"]),tenantId:v.nullable(),localAlias:Me,subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional(),dryRun:o.boolean().optional(),adoptionStrategy:o.enum(["merge","keep-local","take-hub"]).optional(),allowLlm:o.boolean().optional(),confirm:o.boolean().optional(),adoptionReceipt:o.string().min(16).max(128).optional()}).strict(),o.object({op:o.literal("hub.skillSubscribe"),requestId:te,hubId:v,hubSource:o.string().min(1).max(2048),visibility:o.enum(["public","org"]),tenantId:v.nullable(),localAlias:Me}).strict(),o.object({op:o.literal("hub.skillUnpull"),requestId:te,linkId:o.string().min(1).max(256)}).strict(),o.object({op:o.literal("hub.skillPublish"),requestId:te,dryRun:o.boolean(),sourceSkill:Me,localAlias:Me,visibility:o.enum(["public","org"]),tenantId:v.nullable(),subscribe:o.boolean(),autoPush:o.boolean(),confirmPublicEgress:o.boolean(),previewReceipt:o.string().min(1).max(4096).optional(),confirmPublish:o.literal(!0).optional()}).strict(),o.object({op:o.literal("hub.links"),kind:o.enum(["agent","team","skill"]).optional()}).strict(),o.object({op:o.literal("hub.policy"),requestId:te,linkId:o.string().min(1).max(256),expectedPolicyRevision:o.string().min(1).max(256),subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()}).strict(),o.object({op:o.literal("hub.check"),requestId:te,kind:Vr.optional(),name:Me.optional(),localId:os.optional()}).strict(),o.object({op:o.literal("hub.apply"),requestId:te,kind:Vr.optional(),name:Me.optional(),localId:os.optional(),prefer:o.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:o.boolean().optional(),dryRun:o.boolean().optional(),resolveSource:o.literal(!0).optional(),hubSource:o.string().min(1).max(2048).optional(),visibility:o.enum(["public","org"]).optional(),tenantId:o.string().min(1).max(128).nullable().optional()}).strict(),o.object({op:o.literal("hub.applyAll"),requestId:te,kind:Vr.optional()}).strict(),o.object({op:o.literal("hub.retry"),requestId:te,kind:Vr.optional(),name:Me.optional(),localId:os.optional()}).strict(),o.object({op:o.literal("hub.push"),requestId:te,linkId:o.string().min(1).max(256),direction:o.literal("push"),dryRun:o.boolean(),previewReceipt:o.string().min(1).max(4096).optional(),confirmPublish:o.literal(!0).optional()}).strict(),o.object({op:o.literal("teams.list")}).strict(),o.object({op:o.literal("teams.get"),name:Me}).strict(),o.object({op:o.literal("teams.effective"),name:Me}).strict(),o.object({op:o.literal("teams.update"),name:Me,requestId:te,fields:pc,expectedDefinitionRevision:ic.optional()}).strict(),o.object({op:o.literal("teams.create"),requestId:te,fields:pc.extend({name:o.string().min(1).max(64)})}).strict(),o.object({op:o.literal("sessions.list"),limit:o.number().int().min(1).max(500).optional(),include_archived:o.boolean().optional(),include_peers:o.boolean().optional(),scope_kind:Qm.optional(),scope_name:Xm.optional(),cursor:Jm.optional(),with_counts:o.boolean().optional(),sort:o.literal("activity").optional()}).strict(),o.object({op:o.literal("delegated_cleanup_notice.ack")}).strict(),o.object({op:o.literal("sessions.search"),q:o.string().min(1).max(wm),limit:o.number().int().min(1).max(500).optional(),include_archived:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.archive"),sessionId:L,archived:o.boolean()}).strict(),o.object({op:o.literal("sessions.delete"),sessionId:L,confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.create"),requestId:te,cwd:o.string().min(1).max(4096).optional(),target:Wr.optional(),purpose:o.literal("agents-config").optional(),model:ns.optional(),draftId:L.optional(),peer:mn.optional()}).strict(),o.object({op:o.literal("sessions.preview"),requestId:te,cwd:o.string().min(1).max(4096),target:Wr.optional(),model:ns.optional()}).strict(),o.object({op:o.literal("sessions.draft"),requestId:te,cwd:o.string().min(1).max(4096),target:Wr.optional(),model:ns.optional()}).strict(),o.object({op:o.literal("sessions.get"),sessionId:L,journalOrder:o.boolean().optional(),orderIds:o.array(o.string().min(1).max(128)).max(512).optional(),peerJournalSource:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.files"),sessionId:L,scope:o.enum(["family","self"]).optional(),kind:o.string().max(256).optional(),q:o.string().max(256).optional(),sort:o.enum(["recent","name","kind","modified","created","size"]).optional(),order:o.enum(["asc","desc"]).optional(),limit:o.number().int().min(1).max(200).optional(),cursor:o.string().max(8192).optional()}).strict(),o.object({op:o.literal("sessions.files.materialise"),sessionId:L,fileId:o.string().regex(/^[a-f0-9]{16}$/)}).strict(),o.object({op:o.literal("sessions.userAttachments"),sessionId:L}).strict(),o.object({op:o.literal("sessions.userAttachments.materialise"),sessionId:L,digest:o.string().regex(/^[a-f0-9]{32}$/)}).strict(),o.object({op:o.literal("sessions.history"),sessionId:L,beforeId:v.optional(),limit:o.number().int().min(1).max(500).optional(),openFrame:o.boolean().optional(),journalOrder:o.boolean().optional(),orderIds:o.array(o.string().min(1).max(128)).max(512).optional(),peerJournalSource:o.boolean().optional(),sourceRead:o.enum(["metadata","payload"]).optional(),expectedJournalGeneration:o.string().min(1).max(128).optional()}).strict(),o.object({op:o.literal("sessions.checkpoints"),sessionId:L}).strict(),o.object({op:o.literal("sessions.checkpoints.warm"),sessionId:L,ids:o.array(v).max(dc).optional(),limit:o.number().int().min(1).max(dc).optional()}).strict(),o.object({op:o.literal("sessions.find"),sessionId:L,q:o.string().min(1).max(km),limit:o.number().int().min(1).max(Im).optional()}).strict(),o.object({op:o.literal("subagents.transcript"),sessionId:L,childId:L,beforeId:v.optional(),limit:o.number().int().min(1).max(500).optional()}).strict(),o.object({op:o.literal("sessions.message"),sessionId:L,requestId:te,text:o.string().max(cc),images:o.array(ac).max(lc).optional(),files:o.array(vm).max(lm).optional(),mode:o.enum(["prompt","steer"]).optional(),inputMode:o.enum(["typed","dictated","mixed"]).optional(),inputPath:o.string().max(1024).optional()}).strict(),o.object({op:o.literal("sessions.command"),sessionId:L,requestId:te,command:o.string().regex(/^\/?[A-Za-z]+$/).max(64),args:o.string().max(cc).optional(),images:o.array(ac).max(lc).optional()}).strict(),o.object({op:o.literal("sessions.move"),sessionId:L,requestId:te,cwd:o.string().min(1).max(4096)}).strict(),o.object({op:o.literal("sessions.answer"),sessionId:L,epoch:v.optional(),requestId:v.optional(),value:o.string().max(32768).optional(),approved:o.boolean().optional(),questionIndex:o.number().int().min(0).optional(),askId:v.optional(),answers:o.record(o.string(),o.array(o.string().max(32768))).optional(),decline:o.boolean().optional(),revise:o.boolean().optional(),dismiss:o.boolean().optional(),reason:o.enum(["answered_in_chat","moot"]).optional()}).strict(),o.object({op:o.literal("sessions.seen"),sessionId:L,completionToken:o.string().uuid()}).strict(),o.object({op:o.literal("attention.seen"),items:o.array(o.object({sessionId:L,completionToken:o.string().uuid()}).strict()).min(1).max(500)}).strict(),o.object({op:o.literal("sessions.notified"),sessionId:L,completionToken:o.string().uuid()}).strict(),o.object({op:o.literal("tags.list")}).strict(),o.object({op:o.literal("tags.replace"),tags:o.array(o.object({id:o.string().optional(),name:o.string()}).strict())}).strict(),o.object({op:o.literal("sessions.tags"),expected_revision:o.string().optional(),sessionId:L,tags:o.array(o.string()),primary:o.string().nullable()}).strict(),o.object({op:o.literal("sessions.pin"),sessionId:L,pinned:o.boolean()}).strict(),o.object({op:o.literal("sessions.watch"),sessionId:L,subscriptionId:o.string().regex(rc),visible:o.boolean(),canNotify:o.boolean()}).strict(),o.object({op:o.literal("sessions.warm"),sessionId:L}).strict(),o.object({op:o.literal("sessions.interrupt"),sessionId:L,requestId:te}).strict(),o.object({op:o.literal("supplements.cancel"),sessionId:L,job:Ji,anchor:qi}).strict(),o.object({op:o.literal("supplements.restart"),sessionId:L,job:Ji,anchor:qi}).strict(),o.object({op:o.literal("supplements.steer"),sessionId:L,job:Ji,anchor:qi,text:o.string().min(1).max(500)}).strict(),o.object({op:o.literal("sessions.variables.list"),sessionId:L}).strict(),o.object({op:o.literal("sessions.variables.create"),sessionId:L,key:ni,value:gc,type:mc}).strict(),o.object({op:o.literal("sessions.variables.update"),sessionId:L,key:ni,value:gc,type:mc}).strict(),o.object({op:o.literal("sessions.variables.delete"),sessionId:L,key:ni}).strict(),o.object({op:o.literal("sessions.presence"),subscriptionId:o.string().regex(/^[a-f0-9]{1,64}$/),canNotify:o.boolean(),canNotifyKinds:o.array(o.enum(["complete","error"])).max(4),sessionId:o.string().regex(/^([a-f0-9]{12})?$/),window:o.object({exists:o.boolean(),focused:o.boolean(),visible:o.boolean(),minimized:o.boolean()}).strict()}).strict(),o.object({op:o.literal("legacy.models"),provider:o.string().max(128).optional(),sort:o.enum(["id","name","provider","recommended"]).optional(),direction:o.enum(["ascending","descending"]).optional()}).strict(),o.object({op:o.literal("legacy.models.providers")}).strict(),o.object({op:o.literal("auth.probe"),provider:v}).strict(),o.object({op:o.literal("legacy.agent.upload"),agentId:v}).strict(),o.object({op:o.literal("agent.publish"),agentId:v,document:Ec.optional(),...is,visibility:o.literal("org").optional(),tenantId:v.optional()}).strict(),o.object({op:o.literal("agent.republish"),agentId:v,hubAgentId:v,expectedRemoteRevision:o.string().min(1).max(512).optional(),document:Ec.optional(),...is,visibility:o.literal("org").optional(),tenantId:v.optional()}).strict(),o.object({op:o.literal("team.publish"),teamId:v,...is,visibility:o.literal("org").optional(),tenantId:v.optional()}).strict(),o.object({op:o.literal("team.pull"),teamId:v,tenantId:v.optional()}).strict(),o.object({op:o.literal("agent.nameAvailability"),name:o.string().min(1).max(zs)}).strict(),o.object({op:o.literal("legacy.agents.list"),page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(500).optional(),name:o.string().max(256).optional(),sort:o.string().max(64).optional(),direction:o.enum(["asc","desc"]).optional()}).strict(),o.object({op:o.literal("legacy.agent.get"),agentId:v}).strict(),o.object({op:o.literal("legacy.agent.history"),agentId:v,page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(500).optional()}).strict(),o.object({op:o.literal("legacy.jobs.list"),agentId:v.optional(),status:o.string().max(64).optional()}).strict(),o.object({op:o.literal("legacy.job.get"),jobId:v}).strict(),o.object({op:o.literal("legacy.schedules.list"),page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("legacy.agent.schedules.list"),agentId:v,page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("legacy.agent.schedule.create"),agentId:v,schedule:bc.extend({prompt:o.string().max(64e3),interval:o.number().int().min(1),unit:hc})}).strict(),o.object({op:o.literal("legacy.schedule.get"),scheduleId:v}).strict(),o.object({op:o.literal("legacy.schedule.edit"),scheduleId:v,schedule:bc.extend({prompt:o.string().max(64e3).nullish(),interval:o.number().int().min(1).nullish(),unit:hc.nullish()})}).strict(),o.object({op:o.literal("legacy.schedule.remove"),scheduleId:v}).strict(),o.object({op:o.literal("legacy.agent.create"),agent:o.record(o.unknown())}).strict(),o.object({op:o.literal("legacy.agent.update"),agentId:v,update:o.record(o.unknown())}).strict(),o.object({op:o.literal("legacy.agent.delete"),agentId:v}).strict(),o.object({op:o.literal("legacy.agent.conversation.clear"),agentId:v}).strict(),o.object({op:o.literal("legacy.agent.systemPrompt.get"),agentId:v}).strict(),o.object({op:o.literal("legacy.agent.systemPrompt.update"),agentId:v,systemPrompt:o.string().max(xm)}).strict(),o.object({op:o.literal("legacy.agent.download"),agentId:v}).strict(),o.object({op:o.literal("legacy.job.cancel"),jobId:v}).strict(),o.object({op:o.literal("commands.list")}).strict(),o.object({op:o.literal("commands.entities"),sessionId:L,command:v,name:o.string().max(128).optional()}).strict(),o.object({op:o.literal("models.catalogue"),live:o.boolean().optional(),scope:o.enum(["usable","all"]).optional()}).strict(),o.object({op:o.literal("usage.get"),provider:v.optional(),live:o.boolean().optional(),refresh:o.boolean().optional()}).strict(),o.object({op:o.literal("quota.notice"),provider:v.optional(),model:o.string().min(1).max(200).optional(),refresh:o.boolean().optional()}).strict(),o.object({op:o.literal("analytics.get"),sessionId:L.optional(),sinceMs:o.number().int().nonnegative().optional(),untilMs:o.number().int().nonnegative().optional(),days:o.number().int().min(1).max(366).optional()}).strict(),o.object({op:o.literal("analytics.models"),sessionId:L.optional(),sinceMs:o.number().int().nonnegative().optional(),untilMs:o.number().int().nonnegative().optional(),days:o.number().int().min(1).max(366).optional()}).strict(),o.object({op:o.literal("info.get")}).strict(),o.object({op:o.literal("sessions.report"),sessionId:L,recentLimit:o.number().int().min(0).max(50).optional()}).strict(),o.object({op:o.literal("skills.list"),sessionId:L.optional(),cwd:_m.optional(),name:Fn.optional()}).strict(),o.object({op:o.literal("skills.create"),requestId:te,name:Fn,copyFrom:Fn}).strict(),o.object({op:o.literal("skills.update"),requestId:te,name:Fn,expectedFingerprint:o.string().regex(/^[a-f0-9]{64}$/),files:o.array(o.object({path:o.string().min(1).max(240),content:o.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),o.object({op:o.literal("skills.remove"),requestId:te,name:Fn,discardLocalChanges:o.boolean()}).strict(),o.object({op:o.literal("sessions.failovers"),sessionId:L}).strict(),o.object({op:o.literal("sessions.credential"),sessionId:L,action:o.enum(["list","store","forget"]),key:Br.optional(),value:Gr.optional(),confirmed:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.fork"),sessionId:L,requestId:te,message:o.string().max(2e5).optional(),boundary:o.enum(["next_safe","at_entry"]).optional(),entryId:o.string().max(128).optional(),autoTag:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.stop"),requestId:te,targets:o.array(L).min(1).max(100),confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.aside"),sessionId:L,requestId:te,text:o.string().min(1).max(32768),asideId:te.optional(),subscriptionId:o.string().regex(rc).optional()}).strict(),o.object({op:o.literal("sessions.adopt"),sessionId:L,requestId:te,asideId:te,confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.aside.get"),sessionId:L,asideId:te}).strict(),o.object({op:o.literal("sessions.aside.close"),sessionId:L,asideId:te}).strict(),o.object({op:o.literal("wakes.list"),limit:o.number().int().min(1).max(500).optional(),includeDormant:o.boolean().optional()}).strict(),o.object({op:o.literal("wakes.create"),requestId:te,sessionId:L.optional(),cwd:o.string().min(1).max(4096).optional(),target:Wr.optional(),message:_c,in:o.string().min(1).max(64).optional(),at:o.string().min(1).max(64).optional(),every:o.string().min(1).max(64).optional(),until:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).optional(),title:o.string().min(1).max(200).optional()}).strict(),o.object({op:o.literal("wakes.edit"),sessionId:L,wakeId:yc,message:_c.optional(),in:o.string().min(1).max(64).optional(),at:o.string().min(1).max(64).optional(),every:o.string().min(1).max(64).optional(),until:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).optional()}).strict(),o.object({op:o.literal("wakes.remove"),sessionId:L,wakeId:yc}).strict(),o.object({op:o.literal("monitors.cancel"),sessionId:L,monitorId:jm}).strict(),o.object({op:o.literal("jobs.cancel"),sessionId:L,jobId:Mm}).strict(),o.object({op:o.literal("mcp.list"),sessionId:L}).strict(),o.object({op:o.literal("mcp.credentials.store"),sessionId:L,name:o.string().min(1).max(256),values:o.record(o.string().min(1).max(128),o.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:o.array(o.string().min(1).max(128)).max(32)}).strict(),o.object({op:o.literal("mcp.control"),sessionId:L,control:o.object({action:o.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:es.optional(),scope:o.enum(["global","project"]).optional(),command:o.string().min(1).max(4096).optional(),args:o.array(o.string().max(8192)).max(128).optional(),env:o.record(Hr).optional(),url:o.string().max(4096).optional(),headers:o.record(Hr).optional(),oauth:o.boolean().optional(),confirmed:o.boolean().optional(),operation_id:nc.optional()}).strict()}).strict(),o.object({op:o.literal("mcp.catalog"),cwd:ts.optional(),sessionId:L.optional()}).strict(),o.object({op:o.literal("mcp.catalog.control"),cwd:ts.optional(),control:o.object({action:o.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:es.optional(),scope:o.enum(["global","project"]).optional(),command:o.string().min(1).max(4096).optional(),args:o.array(o.string().max(8192)).max(128).optional(),env:o.record(Hr).optional(),url:o.string().max(4096).optional(),headers:o.record(Hr).optional(),confirmed:o.boolean().optional(),operation_id:nc.optional()}).strict()}).strict(),o.object({op:o.literal("mcp.catalog.credentials"),header:o.string().min(1).max(128).optional(),cwd:ts.optional(),name:es,values:o.record(o.string().min(1).max(128),o.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:o.array(o.string().min(1).max(128)).max(32)}).strict(),o.object({op:o.literal("radient.request"),control:o.object({operation:o.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"]),request_id:te.optional(),tenant_id:v.optional(),account_id:v.optional(),agent_id:v.optional(),comment_id:v.optional(),team_id:v.optional(),skill_id:v.optional(),query:o.record(o.union([o.string().max(1024),o.number().int()])).optional(),payload:o.record(o.unknown()).optional(),confirmed:o.boolean().optional()}).strict()}).strict(),o.object({op:o.literal("providers.list")}).strict(),o.object({op:o.literal("accounts.list")}).strict(),o.object({op:o.literal("accounts.remove"),accountId:o.number().int().positive(),confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("tunnel.setup.read"),credentialId:o.number().int().positive().optional()}).strict(),o.object({op:o.literal("tunnel.setup.plan"),credentialId:o.number().int().positive().optional()}).strict(),o.object({op:o.literal("tunnel.setup.run"),credentialId:o.number().int().positive(),acceptMonthlyPrice:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("auth.start"),provider:v}).strict(),o.object({op:o.literal("auth.status"),id:v}).strict(),o.object({op:o.literal("auth.input"),id:v,promptId:v,value:Gr}).strict(),o.object({op:o.literal("auth.cancel"),id:v}).strict(),o.object({op:o.literal("auth.key"),provider:v,value:Gr}).strict(),o.object({op:o.literal("auth.logout"),provider:v}).strict(),o.object({op:o.literal("agent_messages.status"),boundary:qa}).strict(),o.object({op:o.literal("agent_messages.enable"),expected_account_id:v,tenant_id:v,state:o.literal("active"),consent_version:o.string().min(1).max(128),consented_via:o.literal("dialog")}).strict(),o.object({op:o.literal("agent_messages.settings"),tenant_id:v.optional()}).strict(),o.object({op:o.literal("agent_messages.settings.put"),expected_account_id:v,tenant_id:v.optional(),consent_version:o.string().min(1).max(128).optional(),consented_via:o.enum(["dialog","settings"]).optional(),label:o.string().min(1).max(128).optional(),state:o.enum(["active","paused","disabled"])}).strict(),o.object({op:o.literal("agent_messages.onboarding.dismiss")}).strict(),o.object({op:o.literal("agent_messages.allowlist.get"),tenant_id:v.optional()}).strict(),o.object({op:o.literal("agent_messages.allowlist.put"),expected_account_id:v,tenant_id:v.optional(),entries:o.array(o.object({direction:o.enum(["send","receive"]),effect:o.enum(["allow","deny"]),target:o.object({endpoint_id:v.optional(),account_id:v.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(),o.object({op:o.literal("team_bridge.conversations.list"),scope:o.literal("account").optional(),tenant_id:v.optional(),limit:o.number().int().min(1).max(100).optional(),cursor:o.string().min(1).max(512).optional(),before:o.string().min(1).max(64).optional(),status:o.enum(["open","archived"]).optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.get"),conversation_id:v,tenant_id:v.optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.create"),expected_account_id:v.optional(),tenant_id:v.optional(),kind:o.enum(["dm","group","channel"]),name:o.string().min(1).max(128).optional(),topic:o.string().min(1).max(512).optional(),visibility:o.enum(["private","tenant"]).optional(),agent_capable:o.boolean().optional(),members:o.array(o.object({account_id:v,kind:o.enum(["human","agent"]),endpoint_id:v.optional(),display_label:o.string().min(1).max(64)}).strict()).max(500)}).strict(),o.object({op:o.literal("team_bridge.conversations.lifecycle"),expected_account_id:v.optional(),tenant_id:v.optional(),conversation_id:v,action:o.enum(["archive","unarchive","join","leave"])}).strict(),o.object({op:o.literal("team_bridge.conversations.join"),expected_account_id:v.optional(),conversation_id:v,tenant_id:v.optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.notify"),expected_account_id:v.optional(),conversation_id:v,tenant_id:v.optional(),notify:o.enum(["all","mention","mute"])}).strict(),o.object({op:o.literal("team_bridge.conversations.agent_notify"),expected_account_id:v.optional(),conversation_id:v,tenant_id:v.optional(),notify:o.enum(["all","mention","mute"])}).strict(),o.object({op:o.literal("team_bridge.conversations.members.add"),expected_account_id:v.optional(),conversation_id:v,tenant_id:v.optional(),members:o.array(o.object({account_id:v,kind:o.enum(["human","agent"]),endpoint_id:v.optional(),display_label:o.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),o.object({op:o.literal("team_bridge.conversations.members.remove"),expected_account_id:v.optional(),tenant_id:v.optional(),conversation_id:v,account_id:v}).strict(),o.object({op:o.literal("team_bridge.conversations.delete"),expected_account_id:v.optional(),tenant_id:v.optional(),conversation_id:v}).strict(),o.object({op:o.literal("team_bridge.conversations.consent"),expected_account_id:v.optional(),conversation_id:v,account_id:v,decision:o.enum(["accept","decline"]),consent_version:o.string().min(1).max(128),tenant_id:v.optional()}).strict(),o.object({op:o.literal("team_bridge.owner_audit.conversations"),expected_account_id:v,tenant_id:v,limit:o.number().int().min(1).max(100).optional(),cursor:o.string().min(1).optional()}).strict(),o.object({op:o.literal("team_bridge.owner_audit.messages"),expected_account_id:v,tenant_id:v,conversation_id:v,limit:o.number().int().min(1).max(100).optional(),before_seq:o.number().int().nonnegative().optional()}).strict(),o.object({op:o.literal("team_bridge.owner_audit.replies"),expected_account_id:v,tenant_id:v,conversation_id:v,message_id:v,limit:o.number().int().min(1).max(100).optional(),after_seq:o.number().int().nonnegative().optional(),before_seq:o.number().int().positive().optional(),order:o.enum(["asc","desc"]).optional()}).strict(),o.object({op:o.literal("team_bridge.messages.list"),conversation_id:v,tenant_id:v.optional(),limit:o.number().int().min(1).max(100).optional(),before_seq:o.number().int().nonnegative().optional(),endpoint_id:v.optional()}).strict(),o.object({op:o.literal("team_bridge.reactions.toggle"),conversation_id:v,message_id:v,expected_account_id:v,tenant_id:v,emoji:o.string().min(1),active:o.boolean()}).strict(),o.object({op:o.literal("team_bridge.messages.send"),expected_account_id:v.optional(),conversation_id:v,tenant_id:v.optional(),client_ref:v,body:o.string(),agent_label:o.string().min(1).max(64).optional(),thread_root_id:v.optional(),attachment_ids:rs.optional(),mentions:Am.optional()}).strict(),o.object({op:o.literal("team_bridge.messages.replies"),conversation_id:v,message_id:v,expected_account_id:v,tenant_id:v,limit:o.number().int().min(1).max(100).optional(),after_seq:o.number().int().nonnegative().optional(),before_seq:o.number().int().positive().optional(),order:o.enum(["asc","desc"]).optional()}).strict(),o.object({op:o.literal("team_bridge.scheduled.list"),tenant_id:v}).strict(),o.object({op:o.literal("team_bridge.scheduled.create"),tenant_id:v,conversation_id:v,client_ref:v,body:o.string(),send_at:o.string().datetime({offset:!0}),attachment_ids:rs.optional(),thread_root_id:v.optional()}).strict(),o.object({op:o.literal("team_bridge.scheduled.update"),tenant_id:v,scheduled_id:v,body:o.string().optional(),send_at:o.string().datetime({offset:!0}).optional(),attachment_ids:rs.optional(),expected_version:o.number().int().nonnegative().optional()}).strict(),o.object({op:o.literal("team_bridge.attachments.delete"),tenant_id:v,conversation_id:v,attachment_id:v,expected_account_id:v}).strict(),o.object({op:o.literal("team_bridge.scheduled.cancel"),tenant_id:v,scheduled_id:v}).strict(),o.object({op:o.literal("team_bridge.read"),expected_account_id:v.optional(),conversation_id:v,tenant_id:v.optional(),seq:o.number().int().nonnegative().optional(),muted:o.boolean().optional()}).strict(),o.object({op:o.literal("team_bridge.unread"),scope:o.literal("account").optional(),tenant_id:v.optional()}).strict(),o.object({op:o.literal("team_bridge.directory"),tenant_id:v}).strict(),o.object({op:o.literal("team_bridge.status"),boundary:qa.optional()}).strict(),o.object({op:o.literal("settings.list")}).strict(),o.object({op:o.literal("settings.edit"),key:Br,value:o.unknown().refine(e=>e!==void 0,"A setting value is required."),base:Cm.optional()}).strict(),o.object({op:o.literal("settings.reset"),key:Br}).strict(),o.object({op:o.literal("tts.paths")}).strict(),o.object({op:o.literal("config.get")}).strict(),o.object({op:o.literal("config.update"),value:Dm}).strict(),o.object({op:o.literal("instructions.get")}).strict(),o.object({op:o.literal("instructions.update"),content:o.string().max(64e3)}).strict(),o.object({op:o.literal("credentials.list")}).strict(),o.object({op:o.literal("credentials.update"),key:Br,value:Gr}).strict(),o.object({op:o.literal("peers.list")}).strict(),o.object({op:o.literal("networks.list")}).strict(),o.object({op:o.literal("networks.invite"),networkId:mn,role:o.enum(["read","drive","admin"]),deviceId:mn.optional()}).strict(),o.object({op:o.literal("networks.member.remove"),networkId:mn,deviceId:mn,confirm:o.string().min(1).max(256)}).strict(),o.object({op:o.literal("sessions.transfer"),sessionId:L,to:o.union([o.literal("local"),mn]),keep:o.boolean().optional(),waitS:o.number().min(0).max(300).optional(),requestId:te.optional()}).strict(),o.object({op:o.literal("approvals.list")}).strict(),o.object({op:o.literal("approvals.approve"),approvalId:zr}).strict(),o.object({op:o.literal("approvals.deny"),approvalId:zr}).strict(),o.object({op:o.literal("approvals.approveCredential"),approvalId:zr,...oc}).strict(),o.object({op:o.literal("approvals.applyCredential"),approvalId:zr,...oc}).strict(),o.object({op:o.literal("asks.list")}).strict(),o.object({op:o.literal("projects.list")}).strict(),o.object({op:o.literal("projects.get"),key:Mt}).strict(),o.object({op:o.literal("projects.create"),name:ss,description:o.string().max(Rc).optional(),status:Ic.optional(),tags:xc.optional()}).strict(),o.object({op:o.literal("projects.update"),key:Mt,fields:o.object({name:ss.optional(),title:o.string().max(80).optional(),owner:o.string().max(80).optional(),team:o.string().max(80).optional(),description:o.string().max(Rc).optional(),status:Ic.optional(),progress:o.string().max(eg).optional(),tags:xc.optional(),start_date:Kr.optional(),target_date:Kr.optional(),completed_at:Kr.optional(),estimate:o.number().positive().max(1e3).optional(),estimate_unit:o.enum(["points","days"]).optional()}).strict(),force_done:o.boolean().optional()}).strict(),o.object({op:o.literal("projects.delete"),key:Mt,confirmed_name:ss}).strict(),o.object({op:o.literal("projects.link"),key:Mt,sessionId:L}).strict(),o.object({op:o.literal("projects.unlink"),key:Mt,sessionId:L}).strict(),o.object({op:o.literal("projects.milestone"),key:Mt,name:o.string().min(1).max(Tc),targetDate:Kr.optional(),completed:o.boolean().optional()}).strict(),o.object({op:o.literal("projects.milestone.remove"),key:Mt,name:o.string().min(1).max(Tc)}).strict(),o.object({op:o.literal("projects.request_update"),key:Mt}).strict(),o.object({op:o.literal("projects.search"),q:o.string().min(1).max(tg),limit:o.number().int().min(1).max(rg).optional()}).strict(),o.object({op:o.literal("aida.status")}).strict(),o.object({op:o.literal("aida.control"),action:o.enum(["open","pause","resume","greet","status"])}).strict(),o.object({op:o.literal("code_requests.list"),sessionId:L}).strict(),o.object({op:o.literal("code_requests.refresh"),sessionId:L,keys:o.array(o.string().min(1).max(512)).max(256).optional(),force:o.boolean().optional()}).strict(),o.object({op:o.literal("static.sign"),route:o.enum(["images","videos","audio","html"]),path:o.string().min(1),ttlS:o.number().int().min(1).max(3600).optional()}).strict(),o.object({op:o.literal("library.list"),scope:o.enum(["final","all"]).optional(),q:o.string().max(512).optional(),category:o.string().min(1).max(64).optional(),kind:o.string().min(1).max(64).optional(),origin_group:o.enum(["generated","created","mentioned"]).optional(),origin:o.string().min(1).max(64).optional(),tag:o.string().min(1).max(128).optional(),tag_mode:o.enum(["all","any"]).optional(),highlighted:o.boolean().optional(),organized:o.boolean().optional(),favorite:o.boolean().optional(),session:o.string().min(1).max(12).optional(),session_id:o.string().min(1).max(512).optional(),sort:o.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:o.enum(["asc","desc"]).optional(),limit:o.number().int().min(1).max(200).optional(),cursor:o.string().max(512).optional()}).strict(),o.object({op:o.literal("library.get"),id:Bn}).strict(),o.object({op:o.literal("library.update"),id:Bn,fields:o.object({name:o.string().max(200).optional(),description:o.string().max(2e3).optional(),favorite:o.boolean().optional(),locked:o.boolean().optional(),archived:o.boolean().optional()}).strict()}).strict(),o.object({op:o.literal("library.tags")}).strict(),o.object({op:o.literal("library.tags.create"),name:o.string().trim().min(1).max(24),category:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("library.tags.update"),id:Gn,name:o.string().trim().min(1).max(24).optional(),category:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("library.tags.delete"),id:Gn}).strict(),o.object({op:o.literal("library.tags.merge"),id:Gn,into:Gn}).strict(),o.object({op:o.literal("library.tags.assign"),id:Bn,tags:o.array(Gn).max(64),primary:o.string().max(128).optional()}).strict(),o.object({op:o.literal("library.chat.link"),id:Bn,sessionId:L}).strict(),o.object({op:o.literal("library.chat.clear"),id:Bn}).strict(),o.object({op:o.literal("library.librarian"),action:o.enum(["status","open","pause","resume","run"]).optional()}).strict(),o.object({op:o.literal("sidebar_layout.get")}).strict(),o.object({op:o.literal("sidebar_layout.set"),layout:sg}).strict(),o.object({op:o.literal("notifications.list"),preview:o.literal(!0).optional(),includeAskReads:o.boolean().optional(),countSessionIds:o.array(L).max(50).optional(),kind:o.enum(["all","asks","updates"]).optional(),bulkPriority:o.enum(["any","high","normal_up"]).optional(),state:o.enum(["unread","all","dismissed"]).optional(),source:o.enum(["notify","ask"]).optional(),priority:o.enum(["high","normal","low"]).optional(),sessionId:L.optional(),throughSeq:o.number().int().min(0).optional(),cursor:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("notifications.get"),id:Et}).strict(),o.object({op:o.literal("notifications.count")}).strict(),o.object({op:o.literal("notifications.read"),verb:o.enum(["read","unread","undo"]),target:o.union([Oc,Ac,og])}).strict(),o.object({op:o.literal("notifications.dismiss"),verb:o.enum(["dismiss","undismiss"]),target:o.union([Oc,Ac])}).strict(),o.object({op:o.literal("notifications.seen"),items:o.array(o.object({id:Et,revision:o.number().int().min(1),anchorId:o.string().min(1).max(256),visibleSinceMs:o.number().int().min(0)}).strict()).min(1).max(50),evidence:o.object({sessionId:L,inputKind:o.enum(["pointer","key","wheel"]),inputAtMs:o.number().int().min(0),visibleSinceMs:o.number().int().min(0)}).strict()}).strict()]);cg.superRefine((e,t)=>{if((e.op==="notifications.read"||e.op==="notifications.dismiss")&&"items"in e.target&&!!e.target.receipt!=(e.target.throughSeq!==void 0)&&t.addIssue({code:o.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:o.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:o.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:o.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:o.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:o.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:o.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,i=e.op!=="hub.check";if(n&&r||i&&!n&&!r||r&&e.kind===void 0){t.addIssue({code:o.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:o.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:o.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:o.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:o.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:o.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:o.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:o.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:o.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:o.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:o.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:o.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:o.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:o.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:o.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:o.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:o.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:o.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:o.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:o.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:o.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:o.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const qe={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},lg={runtimeUnreachable:"runtime_unreachable"},xi="runtime_busy",vd="runtime_retiring";o.object({data:o.object({aside_id:o.string().optional(),status:o.union([o.enum(["adopted","queued"]),o.string()]).optional()}).passthrough()}).passthrough();const wd=o.object({name:o.string(),description:o.string().nullish(),source:o.string().nullish(),link_id:o.string().nullish(),editable:o.boolean().nullish(),installed:o.boolean().nullish(),fingerprint:o.string().nullish(),form:o.string().nullish()}).passthrough(),dg=o.object({path:o.string(),size:o.number().nullish(),preview:o.string().nullish(),preview_truncated:o.boolean().nullish()}).passthrough(),ug=wd.extend({body:o.string().nullish(),body_in_detail:o.boolean().nullish(),body_length:o.number().nullish(),body_bytes:o.number().nullish(),body_truncated:o.boolean().nullish(),files:o.array(dg).nullish(),files_total:o.number().nullish(),files_truncated:o.boolean().nullish(),publish_budget:o.object({limit:o.number(),total:o.number()}).passthrough().nullish()}).passthrough(),JI=o.object({skills:o.array(wd),scope:o.string().nullish(),detail:o.string().nullish(),skill_detail:ug.nullish(),warning_count:o.number().nullish(),version:o.string().nullish()}).passthrough(),qI="aside_adopt_refused",fg=["session_closed","open_tool_batch","turn_running"];function ex(e){if(typeof e!="object"||e===null)return;const t=e.reason;return fg.find(n=>n===t)}const pg={[qe.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[qe.refused]:"ui.common.errors.desktop_refusal.refused",[qe.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[qe.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed"},Zs={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 Ri(e){return e!==void 0&&Object.values(qe).includes(e)}function hg(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return qe.refused;if(t===503)return qe.planeClosed}}const tx=o.object({step:o.string(),blocked_on:o.string(),configured:o.boolean(),ready:o.boolean(),verified:o.boolean(),url:o.string().nullable(),credential_id:o.number().int().positive().nullable(),identity_label:o.string().nullable(),credential_choices:o.array(o.object({id:o.number().int().positive(),identity_label:o.string().nullable().optional()}).passthrough()).default([]),quote:o.object({monthly_price_usd:o.string().nullable(),positive_balance:o.boolean(),eligible:o.boolean(),account_valid:o.boolean()}).passthrough().nullable(),receipts:o.array(o.object({step:o.string(),ok:o.boolean(),text:o.string()})).default([]),remedy:o.object({kind:o.string(),text:o.string(),command:o.string().nullable().optional(),url:o.string().nullable().optional()}).nullable(),source:o.string(),in_progress:o.boolean().default(!1),progress:o.array(o.string()).default([]),active_credential_id:o.number().int().positive().nullable().default(null),billing_outcome:o.string().optional(),reservation_outcome:o.string().optional(),failure_stage:o.string().optional()}).passthrough(),nx=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),mg=88e4,gg=11e5,_g=2e4,yg=9e4,bg=new Set(["analytics.get","analytics.models","sessions.report"]),vg=new Set(["usage.get"]),wg=new Set(["networks.list","peers.list"]),Sg=new Set([...bg,...vg,...wg]),kg=90,Eg=30,Ig=300,xg=10,Sd=15,Rg=1e4;function Tg(e){const n=e.to==="local"||e.keep?Ig:Eg,r=Math.max(0,e.waitS??0);return(kg+n+xg+Sd)*1e3+r*1e3}const Cg=18e4,Ag=Cg+15e3,Og=120,Pg=135e3,jg=93e4,kd=(Og+30+Sd)*1e3,Mg=6e4,Dg=5*kd,Ng=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function Lg(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 kd;case"hub.check":return Mg;case"hub.applyAll":return Dg;default:return null}}function $g(e){if(typeof e!="string"&&e.op==="sessions.transfer")return Tg(e)+Rg;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return Ag;if(t==="tunnel.setup.run")return jg;if(t==="tunnel.setup.plan")return Pg;const n=Lg(t);return n!==null?n:Sg.has(t)?yg:_g}const Ug=5e3;function Ed(e){return $g(e)+Ug}const Oo="deadline_exceeded",Id="foreground_required",xd="View these completions in the foreground before marking them read.",Fg=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"]),Bg=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Gg(e,t){const n=Math.round(t/1e3),r=Oo;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.`}:Ng.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:Fg.has(e)?{code:r,message:Bg.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 rx=mg,ix=gg;o.object({state:o.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:o.string(),kind:o.enum(["balance","subscription","radient","none"]),model_free:o.boolean(),title:o.string(),body:o.string(),actions:o.array(o.object({id:o.enum(["open_url","resend_verification","refresh"]),label:o.string(),url:o.string().nullable().optional()})),resets_at_ms:o.number().int().nullable().optional(),checked_at_ms:o.number().int(),age_ms:o.number().int().nullable().optional(),source:o.enum(["cached","live"])});function Hg(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function Pc(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 as(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 cs(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 jc(e){return{sources:e.sources??null,session_ids:e.sessionIds??{},all:e.all??!1,include_subagents:e.includeSubagents??!1,include_cleared_segments:e.includeClearedSegments??!1,include_memory:e.includeMemory??!0,include_instructions:e.includeInstructions??!0,...e.maxSessions===void 0?{}:{max_sessions:e.maxSessions}}}function Yr(e){const t=new URLSearchParams;return e.tenant_id&&t.set("tenant_id",e.tenant_id),e.expected_account_id&&t.set("expected_account_id",e.expected_account_id),t.size?`?${t.toString()}`:""}function ls(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function zg(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:jc(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:jc(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??Sm)});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"),hi(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),hi(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??Em)});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":{cs(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??{},...as(e)}}}case"agent.republish":{cs(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??{},...as(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{cs(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:as(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,...Hg(e),message:e.message,...Pc(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...Pc(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${ls(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${ls(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)}${ls(e.tenant_id)}`,method:"GET"};case"team_bridge.conversations.create":return{path:"/v1/desktop/team-bridge/conversations",method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},kind:e.kind,...e.name?{name:e.name}:{},...e.topic?{topic:e.topic}:{},...e.visibility?{visibility:e.visibility}:{},...e.agent_capable===void 0?{}:{agent_capable:e.agent_capable},members:e.members}};case"team_bridge.conversations.lifecycle":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/${e.action}${e.action==="join"?"":Yr(e)}`,method:"POST",...e.action==="join"&&(e.tenant_id||e.expected_account_id)?{body:{...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.expected_account_id?{expected_account_id:e.expected_account_id}:{}}}:{}};case"team_bridge.conversations.join":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/join`,method:"POST",...e.tenant_id||e.expected_account_id?{body:{...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.expected_account_id?{expected_account_id:e.expected_account_id}:{}}}:{}};case"team_bridge.conversations.notify":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},notify:e.notify}};case"team_bridge.conversations.agent_notify":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/agent-notify`,method:"PUT",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},notify:e.notify}};case"team_bridge.conversations.members.add":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.expected_account_id&&t.set("expected_account_id",e.expected_account_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members${n}`,method:"POST",body:e.members}}case"team_bridge.conversations.delete":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}${Yr(e)}`,method:"DELETE"};case"team_bridge.conversations.members.remove":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}${Yr(e)}`,method:"DELETE"};case"team_bridge.conversations.consent":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}/consent`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},decision:e.decision,consent_version:e.consent_version}};case"team_bridge.owner_audit.conversations":case"team_bridge.owner_audit.messages":case"team_bridge.owner_audit.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit));let n="/v1/desktop/team-bridge/owner-audit/conversations";return e.op==="team_bridge.owner_audit.conversations"?e.cursor!==void 0&&t.set("cursor",e.cursor):(n+=`/${encodeURIComponent(e.conversation_id)}/messages`,e.op==="team_bridge.owner_audit.messages"?e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)):(n+=`/${encodeURIComponent(e.message_id)}/replies`,e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order))),{path:`${n}?${t}`,method:"GET"}}case"team_bridge.messages.list":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.endpoint_id&&t.set("endpoint_id",e.endpoint_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages${n}`,method:"GET"}}case"team_bridge.reactions.toggle":{const t=`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/reactions/${encodeURIComponent(e.emoji)}`;return e.active?{path:t,method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id}}:{path:`${t}${Yr(e)}`,method:"DELETE"}}case"team_bridge.messages.send":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},client_ref:e.client_ref,body:e.body,...e.agent_label?{agent_label:e.agent_label}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{},...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.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.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??ng)})}`,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,...Wg(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:ag[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function Wg(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 sx=64,ox=64*1024*1024,ax="superseded_completion_token",cx="store_busy",Zg="session_is_remote",Kg="owner_build_behind";function lx(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 wn(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 Vg(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const dx=e=>typeof e?.goal_status=="string",ux=e=>(e?.goal??"").trim().length>0;function Yg(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function Qg(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 tr={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 Xg(e){return e?e===tr.notPaired?"notPaired":e===tr.serverDown?"serverDown":e===tr.frameBudget?"frameTooLarge":"lost":"lost"}const Mc=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const p=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(g=>g(t,p))}},i=()=>t,c={setState:r,getState:i,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d))},l=t=e(r,i,c);return c},Jg=e=>e?Mc(e):Mc,qg=e=>e;function e_(e,t=qg){const n=Fa.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return Fa.useDebugValue(n),n}const Dc=e=>{const t=Jg(e),n=r=>e_(t,r);return Object.assign(n,t),n},Ar=e=>e?Dc(e):Dc;function Rd(e,t){let n;try{n=e()}catch{return}return{getItem:i=>{var s;const a=l=>l===null?null:JSON.parse(l,void 0),c=(s=n.getItem(i))!=null?s:null;return c instanceof Promise?c.then(a):a(c)},setItem:(i,s)=>n.setItem(i,JSON.stringify(s,void 0)),removeItem:i=>n.removeItem(i)}}const Ks=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Ks(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Ks(r)(n)}}}},t_=(e,t)=>(n,r,i)=>{let s={storage:Rd(()=>localStorage),partialize:m=>m,version:0,merge:(m,b)=>({...b,...m}),...t},a=!1;const c=new Set,l=new Set;let d=s.storage;if(!d)return e((...m)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),n(...m)},r,i);const u=()=>{const m=s.partialize({...r()});return d.setItem(s.name,{state:m,version:s.version})},f=i.setState;i.setState=(m,b)=>{f(m,b),u()};const p=e((...m)=>{n(...m),u()},r,i);i.getInitialState=()=>p;let g;const y=()=>{var m,b;if(!d)return;a=!1,c.forEach(k=>{var E;return k((E=r())!=null?E:p)});const _=((b=s.onRehydrateStorage)==null?void 0:b.call(s,(m=r())!=null?m:p))||void 0;return Ks(d.getItem.bind(d))(s.name).then(k=>{if(k)if(typeof k.version=="number"&&k.version!==s.version){if(s.migrate){const E=s.migrate(k.state,k.version);return E instanceof Promise?E.then(A=>[!0,A]):[!0,E]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,k.state];return[!1,void 0]}).then(k=>{var E;const[A,$]=k;if(g=s.merge($,(E=r())!=null?E:p),n(g,!0),A)return u()}).then(()=>{_?.(g,void 0),g=r(),a=!0,l.forEach(k=>k(g))}).catch(k=>{_?.(void 0,k)})};return i.persist={setOptions:m=>{s={...s,...m},m.storage&&(d=m.storage)},clearStorage:()=>{d?.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>y(),hasHydrated:()=>a,onHydrate:m=>(c.add(m),()=>{c.delete(m)}),onFinishHydration:m=>(l.add(m),()=>{l.delete(m)})},s.skipHydration||y(),g||p},Ti=t_,n_=(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 r_(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,i)=>typeof r=="number"&&Number.isFinite(r)?r:i;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 Td=Ar()(Ti(e=>({notice:null,receive:t=>e(n=>n_(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:Rd(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function Po(e){return h(pg[e])}async function Cd(e){if(window.api?.desktop)try{return await i_(window.api.desktop.request(e),e)}catch(n){throw n instanceof ye?n:d_(n)?new Ht(xd,Id):new ye(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 ye(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new ye(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function i_(e,t){const n=Ed(t);let r;return Promise.race([e,new Promise((i,s)=>{r=setTimeout(()=>{const a=Gg(t.op,n);s(new ye(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const Ad="This server did not answer the request for its desktop controls.",s_=()=>h("ui.common.errors.desktop_refusal_placeholder");class ye extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,i,s,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=i,this.retryAfterMs=s,this.detail=a}}class Ht extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function jo(e,t){return e instanceof ye||e instanceof Ht?Ri(e.code)?Po(e.code):e.message===Ad?s_():e.message:t}function o_(e,t,n,r){return typeof r=="string"?r:n===Zs.noCredential?qe.noCredential:n===Zs.transportFailed?qe.transportFailed:hg(zg(e).path,t)}async function Re(e){const t=await Cd(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 ye(t.status,r??Ad,void 0,o_(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"&&a_(n?.result),n?.result}function a_(e){if(typeof e!="object"||e===null)return;const t=r_(e.delegated_cleanup_notice);t&&Td.getState().receive(t)}async function c_(){try{await Re({op:"delegated_cleanup_notice.ack"})}catch{}}async function fx(){Td.getState().dismiss(),await c_()}function l_(e){return e instanceof ye&&e.code===Oo}function px(e){if(!(e instanceof ye))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===Kg:e.code===Zg}function hx(e){return e instanceof Ht&&e.code===Id}function d_(e){return e instanceof Error&&e.message.includes(xd)}async function mx(e){const t=await Cd(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function gx(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await Re({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 u_(e,t){const n=window.api?.desktop?.stream;if(n){const s=n.subscribe(e,t);return()=>s.dispose()}const r=new URLSearchParams({session:e.sessionId});e.epoch&&r.set("epoch",e.epoch),e.afterSeq!==void 0&&r.set("after_seq",String(e.afterSeq)),r.set("frontend_replace","1"),e.openFrame===!0&&r.set("open_frame","1"),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),hi(r,"/__desktop/stream",e.orderIds??[]));const i=new EventSource(`/__desktop/stream?${r}`);return i.onmessage=s=>{t({kind:"data",data:s.data})},i.onerror=()=>{i.readyState===EventSource.CLOSED&&(t({kind:"error",detail:tr.ended}),i.close())},()=>{i.close(),t({kind:"end"})}}async function _x(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}),i=r.headers.get("content-type")??"";if(!r.ok){let s="The media request failed.",a;if(i.includes("application/json"))try{const l=(await r.json())?.detail;if(typeof l=="string")s=l;else if(typeof l=="object"&&l!==null){const d=l;typeof d.text=="string"&&d.text.trim()?s=d.text:typeof d.message=="string"&&d.message.trim()&&(s=d.message),typeof d.code=="string"&&(a=d.code)}}catch{}return{status:r.status,kind:"error",detail:s,code:a!==void 0&&Ri(a)?a:s===Zs.noCredential?qe.noCredential:void 0}}return i.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:i||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function yx(e){return e.kind==="error"?Ri(e.code)?new Ht(Po(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function f_(e){if(l_(e))return"deadline";const t=e instanceof ye?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const Od={unreachable:"",deadline:"",unauthorized:"",get outdated(){return h("ui.common.connection.backend.remedy_outdated")},unknown:""},Vs={get unreachable(){return h("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return h("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return h("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return h("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function p_(e,t){const n=f_(t);return[e,Vs[n],Od[n]].filter(Boolean).join(" ")}const Ys={get successor(){return h("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return h("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return h("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return h("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return h("ui.common.connection.backend.pairing_unpaired")}},h_={get successor(){return h("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return h("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return h("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return h("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return h("ui.common.connection.backend.pane_unpaired")}};function bx(e,t){return e!=="unpaired"?null:h_[t??"unpaired"]}function vx(e,t){return e!=="unpaired"?null:Ys[t??"unpaired"]}function wx(e){const{kind:t,unpaired:n,answered:r,cause:i=null,servedByThisApp:s=!1}=e;return i==="pre-handshake"?s:i!==null||n?!1:r?s:t==="outdated"}function Sx(e){const{kind:t,unpaired:n,missing:r,answered:i,cause:s=null}=e;if(s!==null)return Ys[s];if(!i){if(t==="unreachable")return h("ui.common.connection.backend.compatibility_unreachable",{diagnosis:Vs.unreachable});if(t==="unauthorized")return h("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return h("ui.common.connection.backend.compatibility_deadline",{diagnosis:Vs.deadline});if(t==="outdated")return h("ui.common.connection.backend.compatibility_outdated",{remedy:Od.outdated})}return n?Ys.unpaired:i?h("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):h("ui.common.connection.backend.compatibility_unknown")}const m_=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function kx(e,t=null){return t!==null||!e?!0:m_.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function g_(e,t){return t instanceof ye&&t.status===null?!1:e<1}function Ex(e,t){return t instanceof ye&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const __={get successor(){return h("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return h("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return h("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return h("ui.common.connection.backend.card_credential_refused")},get unpaired(){return h("ui.common.connection.backend.card_unpaired")}};function Ix(e,t,n){return e===null?{sentence:p_(t,n),remedy:!0}:{sentence:__[e],remedy:sd(e)}}const Pd={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]},y_=3e4,b_=15e3;function v_(e){return e?.desktop_available===!0}function xx(){const{client:e,provided:t}=Zp();return id({enabled:t,queryKey:Pd.capabilities,queryFn:async()=>{try{return await Re({op:"capabilities"})}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>v_(n.state.data)?y_:b_,refetchIntervalInBackground:!0},e)}function w_(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function Rx(e,t,n=1){return w_(e,t,n)==="enabled"}function Tx(e){return id({queryKey:Pd.providers,queryFn:()=>Re({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:g_})}const Hn=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function S_(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=Hn(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=Hn(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>Hn(d)===c);l===-1?r.push(a):r[l]=a}if(!t.order)return r;const i=new Map;for(const a of r){const c=Hn(a);c!==null&&i.set(c,a)}const s=[];for(const a of t.order){const c=String(a),l=i.get(c);l&&(s.push(l),i.delete(c))}for(const a of r){const c=Hn(a);c!==null&&i.has(c)?(s.push(a),i.delete(c)):c===null&&s.push(a)}return s}const Qs=e=>({revision:Xe(e),demand:e.orderDemand}),nn=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function On(e,t,n,r,i,s={}){let a=e;const c=t.journal_generation;if(t.reconcile===!0){const p=typeof c=="string"&&c.length>0?c:void 0;return a.orderNeedsReconcile&&a.orderWantedGeneration===p?a.journalMode?a:{...a,journalMode:!0}:{...a,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:p,orderDemand:p!==void 0?{generation:p}:{}}}if(typeof c!="string"||c.length===0)return t.journal_order_state&&t.journal_order_state!=="unsupported"&&!a.journalMode?{...a,journalMode:!0}:a;if(r&&t.journal_order_state==="ready"&&i&&a.orderNeedsReconcile&&a.orderDemand===i.demand&&(a={...a,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),c!==a.journalGeneration&&!r)return a.orderNeedsReconcile&&a.orderWantedGeneration===c?a:{...a,orderNeedsReconcile:!0,orderWantedGeneration:c,orderDemand:{generation:c}};let l=a.journalMode?a:{...a,journalMode:!0};if(c!==a.journalGeneration&&(l={...a,journalMode:!0,journalGeneration:c,orderRevision:(a.orderRevision??0)+1,journalPositions:new Map,orderNeedsReconcile:a.orderNeedsReconcile,orderWantedGeneration:a.orderWantedGeneration,orderDemand:a.orderDemand},s.peer===!0)){const p=(a.orderRevision??0)+1,g=new Map;for(const y of a.records){const m=y.sourceEntryId??(y.kind==="tool"||y.kind==="supplement"?null:y.id);typeof m=="string"&&m.length>0&&m.length<=128&&g.set(m,p)}l={...l,...g.size>0?{journalBodyOwed:g}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(p,g,y)=>{if(!nn(y))return;const m=d.get(p);m&&m.seq>=y||(d===u&&(d=new Map(d)),d.set(p,{entryId:g,seq:y}))};for(const[p,g]of Object.entries(t.journal_ordinals??{}))f(p,p,g);for(const p of n)typeof p.id=="string"&&(f(p.id,p.id,p.journal_seq),p.role==="tool"&&typeof p.tool_call_id=="string"&&f(`tool:${p.tool_call_id}`,p.id,p.journal_seq),typeof p.anchor=="string"&&f(`supplement:${p.anchor}`,p.id,p.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function Mo(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 i=n,s=r;return t.tool_calls.forEach((a,c)=>{!a||typeof a.id!="string"||(n.get(a.id)!==t.id&&(n===i&&(n=new Map(n)),n.set(a.id,t.id)),r.get(a.id)!==c&&(r===s&&(r=new Map(r)),r.set(a.id,c)))}),n===i&&r===s?e:{...e,journalCallOwners:n,journalCallSlots:r}}function jd(e,t){const n=new Set(e.map(s=>s.id));let r=!1,i;for(let s=0;s<e.length;s++){const a=e[s];if(a.kind==="user"&&a.provisional===!0){i=a;continue}if(a.sourcePrecedes!==void 0){if(a.sourceAdmissionAnchor!==void 0){const{sourceAdmissionAnchor:c,...l}=a;e[s]=l,r=!0}i=e[s];continue}!t(a)&&i&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[s]={...a,sourceAdmissionAnchor:i.id},r=!0),i=e[s]}return r}function Md(e,t,n,r,i){const s=[],a=new Set;let c=e,l;for(;c!==void 0;){if(i.has(c.id)){l=i.get(c.id);break}if(n(c)){l=r(c);break}if(c.kind==="user"&&c.provisional===!0||a.has(c.id))break;a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of s)i.set(d,l);return l}const k_=Number.MAX_SAFE_INTEGER;function E_(e,t){const n=new Map,r=new Map,i=new Map;for(const s of e){if(s.sourcePrecedes===void 0)continue;const a=t(s);if(a!==void 0)r.set(s.sourcePrecedes,a);else{const c=r.get(s.sourcePrecedes);c!==void 0&&n.set(s.id,{seq:c,slot:k_})}}for(let s=e.length-1;s>=0;s--){const a=e[s];if(a.sourcePrecedes===void 0)continue;const c=t(a);if(c!==void 0)i.set(a.sourcePrecedes,c);else if(!n.has(a.id)){const l=i.get(a.sourcePrecedes);l!==void 0&&n.set(a.id,{seq:l,slot:-1})}}return n}function Dd(e,t){return{floor:I_(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:E_(e,t)}}function Nd(e,t,n,r){if(r===void 0||e.sourcePrecedes===void 0)return;const i=r.page.get(e.id);if(i!==void 0)return i;const s=new Set;let a=1,c=t.get(e.sourcePrecedes);for(;c!==void 0&&!s.has(c.id);){s.add(c.id);const l=n(c);if(l!==void 0)return{seq:l,slot:-a};const d=r.page.get(c.id);if(d!==void 0)return{seq:d.seq,slot:d.slot-a};a+=1,c=c.sourcePrecedes?t.get(c.sourcePrecedes):void 0}return r.floor===void 0?void 0:{seq:r.floor,slot:-a}}function Ld(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:r}=n,i=new Set;let s=1,a=t.get(e.sourcePrecedes);for(;a!==void 0&&!i.has(a.id);){if(a.sourcePrecedes===void 0){const c=r.get(a.id);return c===void 0?void 0:{slot:c,depth:s}}i.add(a.id),s+=1,a=t.get(a.sourcePrecedes)}}function I_(e,t){let n;for(const r of e){if(r.sourcePrecedes!==void 0)continue;const i=t(r);i!==void 0&&(n===void 0||i<n)&&(n=i)}return n}function $d(e,t){const n=new Map;return r=>{if(!r)return;const i=t(r);if(i===void 0)return;const s=[],a=new Set;let c=r,l=!0;for(;c;){if(n.has(c.id)){l=n.get(c.id)===!0;break}if(a.has(c.id)||t(c)===void 0){l=!1;break}a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of s)n.set(d,l);return l?i:void 0}}function mi(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const i=new Map;t.forEach((a,c)=>{if(a.kind!=="tool")return;const l=n.get(a.toolCallId);if(l===void 0||!r.has(a.toolCallId))return;const d=i.get(l);d?d.push(c):i.set(l,[c])});let s=t;for(const a of i.values()){if(a.length<2)continue;const c=a.map(l=>t[l]).sort((l,d)=>(r.get(l.toolCallId)??0)-(r.get(d.toolCallId)??0));c.every((l,d)=>l===t[a[d]])||(s===t&&(s=t.slice()),a.forEach((l,d)=>{s[l]=c[d]}))}return s}function Ud(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return x_(e,t);const n=e.journalGeneration,r=e.journalPositions;let i=!1,s=!1;const a=t.map(m=>{m.sourcePrecedes!==void 0&&(s=!0);let _=[r?.get(m.sourceEntryId??m.id),r?.get(m.id)].filter(A=>A!==void 0).sort((A,$)=>$.seq-A.seq)[0];if(m.journalGeneration===n&&nn(m.journalSeq)&&(!_||m.journalSeq>_.seq)&&(_={entryId:m.sourceEntryId??m.id,seq:m.journalSeq}),!_||!n||!(m.kind==="user"&&(m.provisional===!0||m.local===!0))&&m.sourceEntryId===_.entryId&&m.journalSeq===_.seq&&m.journalGeneration===n)return m;i=!0;let E={...m,sourceEntryId:_.entryId,journalSeq:_.seq,journalGeneration:n};if(E.kind==="user"){const{provisional:A,local:$,...O}=E;E=O}return E});jd(a,m=>m.journalGeneration===n&&nn(m.journalSeq))&&(i=!0);const l=new Map,d=new Map(a.map(m=>[m.id,m])),u=$d(d,m=>m!==void 0&&m.journalGeneration===n&&nn(m.journalSeq)?m.journalSeq:void 0),f=m=>u(m)!==void 0,p=s?Dd(a,u):void 0,g=(m,b)=>{const _=u(m);if(m.kind==="user"&&m.provisional===!0&&_===void 0)return[1,0,0,0,b];const k=m.kind==="supplement"?m.anchor:m.kind==="tool"?e.journalCallOwners?.get(m.toolCallId)??e.argsByCall.get(m.toolCallId)?.anchorId:void 0,E=typeof k=="string"?u(d.get(k)):void 0,A=E===void 0&&_===void 0?Nd(m,d,u,p):void 0,$=_===void 0&&A===void 0?Md(m,d,f,u,l):void 0,O=E??_??A?.seq??$;if(O===void 0){const C=Ld(m,d,p);return[1,C?.slot??b,C?-C.depth:0,0,b]}return[0,O,E!==void 0?1:_!==void 0?0:A!==void 0?A.slot:2,_??Number.MAX_SAFE_INTEGER,b]},y=a.map((m,b)=>({record:m,index:b,rank:g(m,b)}));return y.sort((m,b)=>{for(let _=0;_<m.rank.length;_++){const k=m.rank[_]-b.rank[_];if(k)return k}return 0}),!i&&y.every((m,b)=>m.index===b)?mi(e,t):mi(e,y.map(m=>m.record))}function x_(e,t){const n=e.journalGeneration,r=e.journalPositions,i=new Map;let s=!1;for(const _ of t){_.sourcePrecedes!==void 0&&(s=!0);let E=[r?.get(_.sourceEntryId??_.id),r?.get(_.id)].filter(A=>A!==void 0).sort((A,$)=>$.seq-A.seq)[0];_.journalGeneration===n&&nn(_.journalSeq)&&(!E||_.journalSeq>E.seq)&&(E={entryId:_.sourceEntryId??_.id,seq:_.journalSeq}),E&&i.set(_.id,E)}const a=_=>_===void 0?void 0:i.get(_.id)??r?.get(_.sourceEntryId??_.id)??r?.get(_.id);let c=!1;const l=t.slice();jd(l,_=>_.journalGeneration===n&&nn(_.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(_=>[_.id,_])),p=$d(f,_=>a(_)?.seq),g=_=>p(_)!==void 0,y=s?Dd(l,p):void 0,m=(_,k)=>{const E=p(_);if(_.kind==="user"&&_.provisional===!0&&E===void 0)return[1,0,0,0,k];const A=_.kind==="supplement"?_.anchor:_.kind==="tool"?e.journalCallOwners?.get(_.toolCallId)??e.argsByCall.get(_.toolCallId)?.anchorId:void 0,$=typeof A=="string"?p(f.get(A)):void 0,O=$===void 0&&E===void 0?Nd(_,f,p,y):void 0,C=E===void 0&&O===void 0?Md(_,f,g,p,u):void 0,I=$??E??O?.seq??C;if(I===void 0){const N=Ld(_,f,y);return[1,N?.slot??k,N?-N.depth:0,0,k]}return[0,I,$!==void 0?1:E!==void 0?0:O!==void 0?O.slot:2,E??Number.MAX_SAFE_INTEGER,k]},b=l.map((_,k)=>({record:_,index:k,rank:m(_,k)}));return b.sort((_,k)=>{for(let E=0;E<_.rank.length;E++){const A=_.rank[E]-k.rank[E];if(A)return A}return 0}),!c&&b.every((_,k)=>_.index===k)?mi(e,t):mi(e,b.map(_=>_.record))}function ut(e){const t=e.records.filter(i=>i.kind==="user"&&i.provisional===!0),n=e.records.filter(i=>i.journalGeneration!==e.journalGeneration||!nn(i.journalSeq)),r=[...t,...n].map(i=>i.sourceEntryId??(i.kind==="tool"||i.kind==="supplement"?null:i.id));if(r.push(...Do(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let i=r.length-1;i>=0;i--){const s=r[i];typeof s=="string"&&e.journalSourceVoid.has(s)&&r.splice(i,1)}return[...new Set(r.filter(i=>typeof i=="string"&&i.length>0&&i.length<=128))]}function Do(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const i=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof i=="string"&&i.length>0&&i.length<=128&&t.add(i)}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 Fd(e,t){const n=e.journalPositions;return ut(e).filter(r=>!n?.has(r)&&!t?.has(r))}const Xe=e=>e.orderRevision??0;async function R_(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"?Do(c):l==="lookup"?Fd(c):ut(c);let i=e.getTranscript().journalGeneration,s=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=Qs(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",p=fm(r(c,f).filter(b=>!n(f).has(b)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),g=await e.read(p,f);if(!e.isCurrent()||Xe(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(g,d,l),!e.isCurrent())return{kind:"stale"};const y=e.getTranscript(),m=e.page(g);if(m.journal_order_state==="ready"&&m.journal_generation===y.journalGeneration){m.journal_generation!==i&&(t.clear(),i=m.journal_generation);for(const k of p)n(f).add(k);if(y.orderNeedsReconcile){if(y.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear();continue}if(f==="payload"){const k=(m.source_retry_ids??[]).filter(E=>typeof E=="string"&&E.length>0&&E.length<=128);if(k.length>0&&p.length>1&&a===0){a++;for(const E of k)n("payload").delete(E);continue}}const b=e.sweep?.(y,n);if(b?.kind==="none")return{kind:"complete",transcript:y};const _=b?.kind??"authority";if(r(y,_).some(k=>!n(_).has(k)))continue;return{kind:"complete",transcript:y}}if(!y.orderNeedsReconcile||y.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear()}}function it(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const i=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof i=="string"&&i?i:e.id}function ds(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function Nc(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function Cx(e){if(!e||e.runs_state!=="ready")return null;const t=e.runs;if(!t||t.length===0)return null;const n=new Map;for(const s of t){if(!s.settled||typeof s.run_key!="string"||s.run_key.length===0)continue;const a=ds(s.action_count);if(a===null)continue;const c={actions:a,workedSeconds:Nc(s.worked_seconds),failed:ds(s.failed_count)??0,complete:s.complete!==!1,openingUserId:typeof s.opening_user_id=="string"&&s.opening_user_id.length>0?s.opening_user_id:null,closingAnswerId:typeof s.closing_answer_id=="string"&&s.closing_answer_id.length>0?s.closing_answer_id:null,crossSessionActions:ds(s.cross_session_action_count),crossSessionWorkedSeconds:Nc(s.cross_session_worked_seconds)};n.set(s.run_key,c),c.openingUserId!==null&&n.set(c.openingUserId,c),c.closingAnswerId!==null&&n.set(c.closingAnswerId,c)}if(n.size===0)return null;const r=new Set;for(const s of e.entries)r.add(it(s));const i=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:i?it(i):null}}}function T_(e){if(!e||e.runs_state!=="ready"||e.head_cut===!0)return null;const t=e.runs,n=e.entries[0];if(!n||!t||t.length===0||!t.find(s=>s.opening_user_id===n.id))return null;const i=Math.round((n.ts??0)*1e3);return i>0?{id:n.id,tsMs:i}:null}function C_(e,t,n){const r=T_(e),i=e?.entries;if(r===null||!i||i.length===0)return!1;const s=Math.round((i[i.length-1].ts??0)*1e3);if(!(s>r.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>r.tsMs)||!(c<s)))return!1;return!0}const No=new Set,zt="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Lo=new RegExp(`[${zt}]`),A_=new RegExp(`[${zt}]+`),Ax=new RegExp(`[${zt}]+`,"g"),O_=new RegExp(`^[${zt}]+|[${zt}]+$`,"g"),P_=new RegExp(`^[${zt}]+`),Ox=new RegExp(`[^${zt}]`);function mt(e){return e.replace(O_,"")}function vr(e){return e.replace(P_,"")}function Bd(e,t){return t===0||Lo.test(e[t-1])}function Gd(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&Bd(e,n)&&t.push(n);return t}function $o(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
2
2
  `,n-1)+1,i=e.indexOf(`
3
- `,n),s=i===-1?e.length:i;let a=e.slice(r,s);return a.endsWith("\r")&&(a=a.slice(0,-1)),{line:a,lineStart:r,column:n-r}}function P_(e,t){if(t.size===0)return null;for(const n of Gd(e)){const r=e.slice(n+1),i=r.indexOf(" ");if(i!==-1&&t.has(r.slice(0,i).toLowerCase()))return n}return null}function Uo(e,t,n){const r=P_(e,n);let i=null;for(const s of Gd(e)){if(s===r)return t>s?s:i;s<=t&&(i=s)}return i}function j_(e,t=null,n=No){const{line:r,lineStart:i,column:s}=$o(e,t),a=Uo(r,s,n);if(a===null)return null;let c=a+1;for(;c<r.length&&!Lo.test(r[c]);)c++;return s>c?null:{start:i+a,query:r.slice(a+1,c),end:i+c}}function Tx(e,t=null,n=No){const{line:r,lineStart:i,column:s}=$o(e,t),a=Uo(r,s,n);return a===null?null:{start:i+a,end:i+r.length}}function M_(e,t,n=null,r=No){const{line:i,lineStart:s,column:a}=$o(e,n),c=r.size>0?r:new Set(t.map(g=>g.toLowerCase())),l=Uo(i,a,c);if(l===null)return null;const d=i.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 p=l+1+f.length;return a<=p?null:{value:d.slice(u+1),start:s+p+1,end:s+i.length,tokenStart:s+l}}function Lc(e,t){return mt(e.slice(0,t))===""}function Cx(e,t,n,r){const i=M_(e,r,t,n);if(i!==null&&Lc(e,i.tokenStart))return"argument";const s=j_(e,t,n);return s!==null&&Lc(e,s.start)?"command":null}function Ax(e,t,n,r){let i=t,s=n;const a=c=>c>=0&&c<e.length&&`
4
- `.includes(e[c]);return r===""?i>0&&a(i-1)?i-=1:a(s)&&(s+=1):i===0&&a(s)&&(s+=1),{text:`${e.slice(0,i)}${r}${e.slice(s)}`,caret:i+r.length}}const D_=1e3,N_=900,L_=40,Hd=3;function $_(e,t){let n=0,r=-2,i=0;for(const s of e){const a=t.indexOf(s,i);if(a<0)return 0;n+=a===r+1?2:1,r=a,i=a+1}return n<=0?0:Math.max(1,Math.min(L_,n))}function zd(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n?n===r?D_:r.startsWith(n)?N_:$_(n,r):0}function U_(e){const n=mt(e).split(C_).pop()??"";return n.startsWith("/")?n.slice(1):n}function F_(e,t){const n=U_(e),r=[];return t.forEach((i,s)=>{let a=0,c=i.name;for(const l of[i.name,...i.aliases]){const d=zd(n,l);d>a&&(a=d,c=l)}a>0&&r.push({score:a,index:s,name:c,command:i})}),r.sort((i,s)=>s.score-i.score||i.index-s.index),r.map(i=>({name:i.name,command:i.command}))}function Ox(e,t){if(!e)return t.map(s=>({name:s.name,command:s}));const n=F_(`/${e}`,t);if(e.length>=Hd)return n;const r=e.toLowerCase(),i=n.filter(({name:s})=>s.toLowerCase().startsWith(r));return i.length>0?i:n}function $c(e,t){if(!e)return t.map(r=>({name:r.name,choice:r}));const n=[];return t.forEach((r,i)=>{const s=Math.max(0,...[r.name,...r.aliases??[]].map(a=>zd(e,a)));s>0&&n.push({score:s,order:i,choice:r})}),n.sort((r,i)=>i.score-r.score||r.order-i.order),n.map(r=>({name:r.choice.name,choice:r.choice}))}const Uc=/^-+/;function Px(e,t,n,r,i){if(i)return!0;const s=mt(e).toLowerCase(),a=mt(t).toLowerCase();return s===a||s.length>0&&s.replace(Uc,"")===a.replace(Uc,"")?!0:!r&&n<=1}const B_=new RegExp("\\p{Ll}","u");function Wd(e){for(const t of e)if(B_.test(t))return!0;return!1}function jx(e,t,n){if(n){if(!e)return t.map(a=>({name:a.name,choice:a}));const r=$c(e,t);if(e.length>=Hd)return r;const i=e.toLowerCase(),s=r.filter(a=>a.name.toLowerCase().startsWith(i));return s.length>0?s:r}return Wd(e)?$c(e,t).filter(r=>r.name.startsWith(e)):[]}const G_=/<skill name="([^"]*)" invocation="([^"]*)">/,H_=/[A-Za-z0-9]/,z_=/[A-Za-z0-9._-]/,W_=/[._-]/;function Z_(e,t){if(t>=e.length||!H_.test(e[t]))return t;let n=t+1;for(;n<e.length&&z_.test(e[n]);)n++;return n}function K_(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!Bd(e,n)){n+=1;continue}const r=Z_(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 V_(e,t,n,r,i,s){let a=n;for(;;){const c=e.slice(t+1,a);if(r.has(c))return{end:a,name:c};if(s||Wd(c)){const l=i.get(c.toLowerCase());if(l!==void 0)return{end:a,name:l}}if(a>t+2&&W_.test(e[a-1])){a-=1;continue}return null}}function Y_(e,t,n={}){return Zd(e,t,n.skipSpans??[],!0)}function Mx(e,t,n={}){return Zd(e,t,n.skipSpans??[],!1)}function Zd(e,t,n,r){const i=new Set(t),s=new Map;for(const l of t)s.has(l.toLowerCase())||s.set(l.toLowerCase(),l);const a=[],c=new Set;for(const l of K_(e)){if(n.some(([f,p])=>f<=l.start&&l.start<p))continue;const d=vr(e.slice(0,l.start))==="",u=V_(e,l.start,l.end,i,s,d);u===null||r&&c.has(u.name)||(c.add(u.name),a.push({start:l.start,end:u.end,text:e.slice(l.start,u.end),name:u.name,leading:d}))}return a}const Sn="<operator-skills>",gi="</operator-skills>",Jn=`
3
+ `,n),s=i===-1?e.length:i;let a=e.slice(r,s);return a.endsWith("\r")&&(a=a.slice(0,-1)),{line:a,lineStart:r,column:n-r}}function j_(e,t){if(t.size===0)return null;for(const n of Gd(e)){const r=e.slice(n+1),i=r.indexOf(" ");if(i!==-1&&t.has(r.slice(0,i).toLowerCase()))return n}return null}function Uo(e,t,n){const r=j_(e,n);let i=null;for(const s of Gd(e)){if(s===r)return t>s?s:i;s<=t&&(i=s)}return i}function M_(e,t=null,n=No){const{line:r,lineStart:i,column:s}=$o(e,t),a=Uo(r,s,n);if(a===null)return null;let c=a+1;for(;c<r.length&&!Lo.test(r[c]);)c++;return s>c?null:{start:i+a,query:r.slice(a+1,c),end:i+c}}function Px(e,t=null,n=No){const{line:r,lineStart:i,column:s}=$o(e,t),a=Uo(r,s,n);return a===null?null:{start:i+a,end:i+r.length}}function D_(e,t,n=null,r=No){const{line:i,lineStart:s,column:a}=$o(e,n),c=r.size>0?r:new Set(t.map(g=>g.toLowerCase())),l=Uo(i,a,c);if(l===null)return null;const d=i.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 p=l+1+f.length;return a<=p?null:{value:d.slice(u+1),start:s+p+1,end:s+i.length,tokenStart:s+l}}function Lc(e,t){return mt(e.slice(0,t))===""}function jx(e,t,n,r){const i=D_(e,r,t,n);if(i!==null&&Lc(e,i.tokenStart))return"argument";const s=M_(e,t,n);return s!==null&&Lc(e,s.start)?"command":null}function Mx(e,t,n,r){let i=t,s=n;const a=c=>c>=0&&c<e.length&&`
4
+ `.includes(e[c]);return r===""?i>0&&a(i-1)?i-=1:a(s)&&(s+=1):i===0&&a(s)&&(s+=1),{text:`${e.slice(0,i)}${r}${e.slice(s)}`,caret:i+r.length}}const N_=1e3,L_=900,$_=40,Hd=3;function U_(e,t){let n=0,r=-2,i=0;for(const s of e){const a=t.indexOf(s,i);if(a<0)return 0;n+=a===r+1?2:1,r=a,i=a+1}return n<=0?0:Math.max(1,Math.min($_,n))}function zd(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n?n===r?N_:r.startsWith(n)?L_:U_(n,r):0}function F_(e){const n=mt(e).split(A_).pop()??"";return n.startsWith("/")?n.slice(1):n}function B_(e,t){const n=F_(e),r=[];return t.forEach((i,s)=>{let a=0,c=i.name;for(const l of[i.name,...i.aliases]){const d=zd(n,l);d>a&&(a=d,c=l)}a>0&&r.push({score:a,index:s,name:c,command:i})}),r.sort((i,s)=>s.score-i.score||i.index-s.index),r.map(i=>({name:i.name,command:i.command}))}function Dx(e,t){if(!e)return t.map(s=>({name:s.name,command:s}));const n=B_(`/${e}`,t);if(e.length>=Hd)return n;const r=e.toLowerCase(),i=n.filter(({name:s})=>s.toLowerCase().startsWith(r));return i.length>0?i:n}function $c(e,t){if(!e)return t.map(r=>({name:r.name,choice:r}));const n=[];return t.forEach((r,i)=>{const s=Math.max(0,...[r.name,...r.aliases??[]].map(a=>zd(e,a)));s>0&&n.push({score:s,order:i,choice:r})}),n.sort((r,i)=>i.score-r.score||r.order-i.order),n.map(r=>({name:r.choice.name,choice:r.choice}))}const Uc=/^-+/;function Nx(e,t,n,r,i){if(i)return!0;const s=mt(e).toLowerCase(),a=mt(t).toLowerCase();return s===a||s.length>0&&s.replace(Uc,"")===a.replace(Uc,"")?!0:!r&&n<=1}const G_=new RegExp("\\p{Ll}","u");function Wd(e){for(const t of e)if(G_.test(t))return!0;return!1}function Lx(e,t,n){if(n){if(!e)return t.map(a=>({name:a.name,choice:a}));const r=$c(e,t);if(e.length>=Hd)return r;const i=e.toLowerCase(),s=r.filter(a=>a.name.toLowerCase().startsWith(i));return s.length>0?s:r}return Wd(e)?$c(e,t).filter(r=>r.name.startsWith(e)):[]}const H_=/<skill name="([^"]*)" invocation="([^"]*)">/,z_=/[A-Za-z0-9]/,W_=/[A-Za-z0-9._-]/,Z_=/[._-]/;function K_(e,t){if(t>=e.length||!z_.test(e[t]))return t;let n=t+1;for(;n<e.length&&W_.test(e[n]);)n++;return n}function V_(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!Bd(e,n)){n+=1;continue}const r=K_(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 Y_(e,t,n,r,i,s){let a=n;for(;;){const c=e.slice(t+1,a);if(r.has(c))return{end:a,name:c};if(s||Wd(c)){const l=i.get(c.toLowerCase());if(l!==void 0)return{end:a,name:l}}if(a>t+2&&Z_.test(e[a-1])){a-=1;continue}return null}}function Q_(e,t,n={}){return Zd(e,t,n.skipSpans??[],!0)}function $x(e,t,n={}){return Zd(e,t,n.skipSpans??[],!1)}function Zd(e,t,n,r){const i=new Set(t),s=new Map;for(const l of t)s.has(l.toLowerCase())||s.set(l.toLowerCase(),l);const a=[],c=new Set;for(const l of V_(e)){if(n.some(([f,p])=>f<=l.start&&l.start<p))continue;const d=vr(e.slice(0,l.start))==="",u=Y_(e,l.start,l.end,i,s,d);u===null||r&&c.has(u.name)||(c.add(u.name),a.push({start:l.start,end:u.end,text:e.slice(l.start,u.end),name:u.name,leading:d}))}return a}const Sn="<operator-skills>",gi="</operator-skills>",Xn=`
5
5
 
6
- `,Kd="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>`.",Fo="​",Q_=Sn.replace("<",`<${Fo}`),J_=gi.replace("<",`<${Fo}`),X_=`<${Fo}skill name=`,q_=/^<skill name="([^"]*)">/;function ey(e){return e.replace(/<\/operator-skills>/g,J_).replace(/<operator-skills>/g,Q_).replace(/<skill name="/g,X_)}function Dx(e){const t=e.map(({name:n,body:r})=>`<skill name="${n}">
7
- ${ey(r)}
8
- </skill>`);return Sn+Jn+Kd+Jn+t.join(Jn)+Jn+gi}function Bo(e){const t=[],n=Sn+Jn+Kd;let r=0;for(;;){const i=e.indexOf(n,r);if(i===-1)return t;const s=e.indexOf(gi,i+n.length),a=e.indexOf(Sn,i+Sn.length);if(s===-1||a!==-1&&a<s){r=i+Sn.length;continue}const c=s+gi.length;t.push([i,c]),r=c}}function ty(e){const t=[];for(const[n,r]of Bo(e)){let i=0;for(const s of e.slice(n,r).split(`
9
- `)){if(i>0){s.startsWith("</skill>")&&(i-=1);continue}const a=q_.exec(s);a!==null&&(t.push(a[1]),i=1)}}return t}function Nx(e,t){const n=Bo(e),r=Y_(e,t,{skipSpans:n});if(r.length===0)return[];const i=new Set(ty(e));return r.filter(s=>!i.has(s.name))}const Fc=new RegExp(`[${zt}]+$`);function Vd(e){const t=Bo(e);if(t.length===0)return e;const n=[];let r=0;for(const[s,a]of[...t].sort((c,l)=>c[0]-l[0])){if(a<=r)continue;const c=Math.max(s,r);n.push(e.slice(r,c).replace(Fc,"")),r=a}n.push(e.slice(r).replace(Fc,""));let i="";for(const s of n)s&&(i&&!Lo.test(s[0])&&(i+=" "),i+=s);return i}function Lx(e){if(!e||mt(e)==="")return!1;let t=vr(e);if(t.startsWith("---")){const n=t.slice(3),r=n.indexOf(`
10
- ---`);r!==-1&&(t=n.slice(r+4))}return mt(t)!==""}function ny(e){return e.replace(/&#10;/g,`
11
- `).replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&quot;/g,'"').replace(/&amp;/g,"&")}const je=[];for(let e=0;e<256;++e)je.push((e+256).toString(16).slice(1));function ry(e,t=0){return(je[e[t+0]]+je[e[t+1]]+je[e[t+2]]+je[e[t+3]]+"-"+je[e[t+4]]+je[e[t+5]]+"-"+je[e[t+6]]+je[e[t+7]]+"-"+je[e[t+8]]+je[e[t+9]]+"-"+je[e[t+10]]+je[e[t+11]]+je[e[t+12]]+je[e[t+13]]+je[e[t+14]]+je[e[t+15]]).toLowerCase()}let us;const iy=new Uint8Array(16);function sy(){if(!us){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");us=crypto.getRandomValues.bind(crypto)}return us(iy)}const oy=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Bc={randomUUID:oy};function ay(e,t,n){if(Bc.randomUUID&&!e)return Bc.randomUUID();e=e||{};const r=e.random??e.rng?.()??sy();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,ry(r)}const Yd=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,Js=e=>{let t=e;for(;;){const n=Yd.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},Gc=e=>{const t=[];let n=e;for(;;){const r=Yd.exec(n);if(r===null)break;t.push({id:ay(),text:r[1]}),n=n.slice(r[0].length)}return{replies:t,remainingContent:n.trim()}};function Ci(e){return Go(e)?.skill}const cy=/^\s/,ly=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,dy=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function uy(e){const t=vr(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 fy(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Hc(e,t){const n=[];for(let r=1;r<e.length;r+=1){const i=e[r];if(t==='"'&&i==="\\"&&r+1<e.length){n.push(i,e[r+1]),r+=1;continue}if(i!==t){n.push(i);continue}if(t==="'"&&e[r+1]==="'"){n.push(i,i),r+=1;continue}const s=e.slice(r+1).trim();if(s!==""&&!s.startsWith("#"))return null;const a=n.join(""),c=t==="'"?a.replace(/''/g,"'"):fy(a);return c===""?null:c}return null}function py(e){const t=e.split(`
13
- `);for(const[n,r]of t.entries()){if(!r.startsWith("description:"))continue;const i=r.slice(12).trim(),s=i!==""&&ly.test(i),a=[];i!==""&&!s&&a.push(i);for(let u=n+1;u<t.length;u+=1){const f=t[u];if(f.trim()!==""){if(!cy.test(f))break;a.push(f.trim())}}if(a.length===0)return null;const c=a.join(" ");if(s)return c.trim()===""?null:c.trim();if(c.startsWith('"'))return Hc(c,'"');if(c.startsWith("'"))return Hc(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function Go(e){const{prefix:t,rest:n}=Js(e),r=n.slice(0,n.length-vr(n).length),i=vr(n),s=dy.exec(i);if(s===null)return null;const a=G_.exec(i.slice(s[0].length));if(a===null||a.index!==0||a[1]!==s[1])return null;const c=s[0].length+a[0].length,l=i.indexOf("</skill>",c);if(l===-1)return null;const d=i.slice(c,l),u=uy(d),f=u===null?null:py(d.slice(0,u)),p=a[1],g=ny(a[2]);return{text:t+r+g,skill:{name:p,token:`$${p}`,request:mt(i.slice(l+8)),purpose:f,body:mt(u===null?d:d.slice(u))}}}function $x(e){const t=Go(e);if(t!==null)return t.text;const n=Vd(e);return n===e?e:mt(n)}function hy(e){const t=Go(e);if(t===null){const r=Vd(e);if(r===e)return null;const{prefix:i}=Js(e);return{replies:Gc(e).replies,text:r.slice(i.length).trimStart()}}const{prefix:n}=Js(e);return{replies:Gc(e).replies,text:t.text.slice(n.length).trimStart()}}function Ux(e){return hy(e)?.text??e}const my=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"]]),gy=/\blabel=(['"])(.*?)\1/,_y=/\bjob=(['"])(.*?)\1/,yy=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function Xs(e){const t=typeof e.text=="string"?e.text:"",n=yy.exec(t);let r=n?.[2];const i=r?.indexOf(`
6
+ `,Kd="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>`.",Fo="​",X_=Sn.replace("<",`<${Fo}`),J_=gi.replace("<",`<${Fo}`),q_=`<${Fo}skill name=`,ey=/^<skill name="([^"]*)">/;function ty(e){return e.replace(/<\/operator-skills>/g,J_).replace(/<operator-skills>/g,X_).replace(/<skill name="/g,q_)}function Ux(e){const t=e.map(({name:n,body:r})=>`<skill name="${n}">
7
+ ${ty(r)}
8
+ </skill>`);return Sn+Xn+Kd+Xn+t.join(Xn)+Xn+gi}function Bo(e){const t=[],n=Sn+Xn+Kd;let r=0;for(;;){const i=e.indexOf(n,r);if(i===-1)return t;const s=e.indexOf(gi,i+n.length),a=e.indexOf(Sn,i+Sn.length);if(s===-1||a!==-1&&a<s){r=i+Sn.length;continue}const c=s+gi.length;t.push([i,c]),r=c}}function ny(e){const t=[];for(const[n,r]of Bo(e)){let i=0;for(const s of e.slice(n,r).split(`
9
+ `)){if(i>0){s.startsWith("</skill>")&&(i-=1);continue}const a=ey.exec(s);a!==null&&(t.push(a[1]),i=1)}}return t}function Fx(e,t){const n=Bo(e),r=Q_(e,t,{skipSpans:n});if(r.length===0)return[];const i=new Set(ny(e));return r.filter(s=>!i.has(s.name))}const Fc=new RegExp(`[${zt}]+$`);function Vd(e){const t=Bo(e);if(t.length===0)return e;const n=[];let r=0;for(const[s,a]of[...t].sort((c,l)=>c[0]-l[0])){if(a<=r)continue;const c=Math.max(s,r);n.push(e.slice(r,c).replace(Fc,"")),r=a}n.push(e.slice(r).replace(Fc,""));let i="";for(const s of n)s&&(i&&!Lo.test(s[0])&&(i+=" "),i+=s);return i}function Bx(e){if(!e||mt(e)==="")return!1;let t=vr(e);if(t.startsWith("---")){const n=t.slice(3),r=n.indexOf(`
10
+ ---`);r!==-1&&(t=n.slice(r+4))}return mt(t)!==""}function ry(e){return e.replace(/&#10;/g,`
11
+ `).replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&quot;/g,'"').replace(/&amp;/g,"&")}const je=[];for(let e=0;e<256;++e)je.push((e+256).toString(16).slice(1));function iy(e,t=0){return(je[e[t+0]]+je[e[t+1]]+je[e[t+2]]+je[e[t+3]]+"-"+je[e[t+4]]+je[e[t+5]]+"-"+je[e[t+6]]+je[e[t+7]]+"-"+je[e[t+8]]+je[e[t+9]]+"-"+je[e[t+10]]+je[e[t+11]]+je[e[t+12]]+je[e[t+13]]+je[e[t+14]]+je[e[t+15]]).toLowerCase()}let us;const sy=new Uint8Array(16);function oy(){if(!us){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");us=crypto.getRandomValues.bind(crypto)}return us(sy)}const ay=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Bc={randomUUID:ay};function cy(e,t,n){if(Bc.randomUUID&&!e)return Bc.randomUUID();e=e||{};const r=e.random??e.rng?.()??oy();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,iy(r)}const Yd=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,Xs=e=>{let t=e;for(;;){const n=Yd.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},Gc=e=>{const t=[];let n=e;for(;;){const r=Yd.exec(n);if(r===null)break;t.push({id:cy(),text:r[1]}),n=n.slice(r[0].length)}return{replies:t,remainingContent:n.trim()}};function Ci(e){return Go(e)?.skill}const ly=/^\s/,dy=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,uy=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function fy(e){const t=vr(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 py(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Hc(e,t){const n=[];for(let r=1;r<e.length;r+=1){const i=e[r];if(t==='"'&&i==="\\"&&r+1<e.length){n.push(i,e[r+1]),r+=1;continue}if(i!==t){n.push(i);continue}if(t==="'"&&e[r+1]==="'"){n.push(i,i),r+=1;continue}const s=e.slice(r+1).trim();if(s!==""&&!s.startsWith("#"))return null;const a=n.join(""),c=t==="'"?a.replace(/''/g,"'"):py(a);return c===""?null:c}return null}function hy(e){const t=e.split(`
13
+ `);for(const[n,r]of t.entries()){if(!r.startsWith("description:"))continue;const i=r.slice(12).trim(),s=i!==""&&dy.test(i),a=[];i!==""&&!s&&a.push(i);for(let u=n+1;u<t.length;u+=1){const f=t[u];if(f.trim()!==""){if(!ly.test(f))break;a.push(f.trim())}}if(a.length===0)return null;const c=a.join(" ");if(s)return c.trim()===""?null:c.trim();if(c.startsWith('"'))return Hc(c,'"');if(c.startsWith("'"))return Hc(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function Go(e){const{prefix:t,rest:n}=Xs(e),r=n.slice(0,n.length-vr(n).length),i=vr(n),s=uy.exec(i);if(s===null)return null;const a=H_.exec(i.slice(s[0].length));if(a===null||a.index!==0||a[1]!==s[1])return null;const c=s[0].length+a[0].length,l=i.indexOf("</skill>",c);if(l===-1)return null;const d=i.slice(c,l),u=fy(d),f=u===null?null:hy(d.slice(0,u)),p=a[1],g=ry(a[2]);return{text:t+r+g,skill:{name:p,token:`$${p}`,request:mt(i.slice(l+8)),purpose:f,body:mt(u===null?d:d.slice(u))}}}function Gx(e){const t=Go(e);if(t!==null)return t.text;const n=Vd(e);return n===e?e:mt(n)}function my(e){const t=Go(e);if(t===null){const r=Vd(e);if(r===e)return null;const{prefix:i}=Xs(e);return{replies:Gc(e).replies,text:r.slice(i.length).trimStart()}}const{prefix:n}=Xs(e);return{replies:Gc(e).replies,text:t.text.slice(n.length).trimStart()}}function Hx(e){return my(e)?.text??e}const gy=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"]]),_y=/\blabel=(['"])(.*?)\1/,yy=/\bjob=(['"])(.*?)\1/,by=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function Js(e){const t=typeof e.text=="string"?e.text:"",n=by.exec(t);let r=n?.[2];const i=r?.indexOf(`
14
14
 
15
- `)??-1,a=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&i>=0?my.get((r??"").slice(0,i)):void 0;n?.[1]==="parent-message"&&a&&(r=(r??"").slice(i+2));const c=typeof e.direction=="string"?e.direction:n?.[1]==="subagent-message"?"to_parent":a?"to_child":"";return{body:typeof e.body=="string"?e.body:r?.trim()?r:t,envelope:t,direction:c,label:Pn(e.label??(n&&gy.exec(n[0].split(`
16
- `,1)[0])?.[2])),jobId:Pn(e.job_id??(n&&_y.exec(n[0].split(`
17
- `,1)[0])?.[2])),sender:tu(e).sender,expectsReply:typeof e.expects_reply=="boolean"?e.expects_reply:e.expects_reply===void 0&&a?a==="ask":null,steer:typeof e.steer=="boolean"?e.steer:e.steer===void 0&&a?a==="steer":null}}function Fx(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 by(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 Bx(e){return by(e)!==null}const Qd=/\s+/,vy=/[\\/]+$/,wy=/[\\/]/,Jd=`
15
+ `)??-1,a=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&i>=0?gy.get((r??"").slice(0,i)):void 0;n?.[1]==="parent-message"&&a&&(r=(r??"").slice(i+2));const c=typeof e.direction=="string"?e.direction:n?.[1]==="subagent-message"?"to_parent":a?"to_child":"";return{body:typeof e.body=="string"?e.body:r?.trim()?r:t,envelope:t,direction:c,label:Pn(e.label??(n&&_y.exec(n[0].split(`
16
+ `,1)[0])?.[2])),jobId:Pn(e.job_id??(n&&yy.exec(n[0].split(`
17
+ `,1)[0])?.[2])),sender:tu(e).sender,expectsReply:typeof e.expects_reply=="boolean"?e.expects_reply:e.expects_reply===void 0&&a?a==="ask":null,steer:typeof e.steer=="boolean"?e.steer:e.steer===void 0&&a?a==="steer":null}}function zx(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 vy(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 Wx(e){return vy(e)!==null}const Qd=/\s+/,wy=/[\\/]+$/,Sy=/[\\/]/,Xd=`
18
18
 
19
- `,Sy=" — cancel with wake(",ky=120,Xd=/(?:\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,Ey=new RegExp("\\p{Cf}","gu"),Iy=4096;function Pn(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(Xd,"").replace(Ey,"").split(Qd).filter(Boolean).join(" ").slice(0,ky)}const Gx={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function qd(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(vy,"");if(t){const n=t.split(wy).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function eu(e){const{name:t,quoted:n}=qd(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function xy(e){const{name:t,quoted:n}=qd(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 Hx(e,t){return t.trim()?!0:xy(e)!==eu(e)}function Ry(e){for(const t of e.slice(0,Iy).split(`
20
- `)){const n=Pn(t);if(n)return n}return""}function zx(e,t){const n=eu(e),r=Ry(t);return r?`${n} · ${r}`:n}function fs(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const Ty=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,Cy=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,Ay=/^<peer-session-message[^>]*>/,Oy=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function tu(e){const t=String(e.text??e.detail??""),n=Ty.exec(t.trim()),r={};if(n)for(const d of n[1].matchAll(Oy))r[d[1]]=d[2]??d[3]??d[4]??"";const i=n?n[2]:"",a=(String(e.body??"").trim()||i||(n?"":t.trim().replace(Ay,""))).replace(Cy,"").trim(),c=e.sender??{},l=(d,u)=>Pn(d)||Pn(u);return{body:a,sender:{pid:l(c.pid,r.from_pid),conversationName:l(c.conversation_name,r.conversation),cwd:l(c.cwd,void 0),sessionId:l(c.session_id,void 0),modelLabel:l(c.model_label,r.model)}}}function Py(e){return!!e.wake_catchup}function jy(e){return e.hidden===!0}function Wx(e){let t=e.split(Jd)[0]??"";t=t.split(Qd).filter(Boolean).join(" "),t=t.split(Sy)[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 Zx(e){const t=e.indexOf(Jd);return t===-1?"":e.slice(t+2).trim()}const Qr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},zn=e=>typeof e=="string"?Pn(e):"";function My(e){const t=Qr(e.bridge_receipt),n=t.v===1,r=Qr(n?t.sender:e.sender),i=n?Qr(t.conversation):{},s=n?t.attachment_count:void 0;return{sender:{name:zn(r.name),...r.kind==="human"||r.kind==="agent"?{kind:r.kind}:{},...zn(r.organization)?{organization:zn(r.organization)}:{}},conversation:{...i.kind==="dm"||i.kind==="group"||i.kind==="channel"?{kind:i.kind}:{},...zn(i.label)?{label:zn(i.label)}:{}},...typeof s=="number"&&Number.isSafeInteger(s)&&s>=0?{attachmentCount:s}:{}}}const Dy=new Set(["channel_post","channel_create","channel_history","channel_thread","react","shared_history"]),Ny=new Set(["channel_post","dm","send","reply"]),Ly=new Set(["take_up","ack","send","reply","channels","channel_create","channel_post","channel_history","react","channel_thread","directory","dm","shared_conversations","shared_history"]),$y=/^(?:bcv|bcmsg|acc|ep)_/i,Uy=/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]|\x9b[0-?]*[ -/]*[@-~]/g,Fy=/[\x00-\x08\x0e-\x1f\x7f-\x9f]/g,By=new RegExp("(?![\\u200c\\u200d])\\p{Cf}","gu"),Gy=/[\t\n\r\v\f ]+/,Hy=/\r\n|\r|\n/,zy=/^bcv_\S+$/,Wy=200;function wr(e){return typeof e!="string"?null:e.replace(Uy,"").replace(Fy,"").replace(By,"").split(Gy).filter(Boolean).join(" ").slice(0,Wy)||null}function Xt(e){const t=wr(e);return t&&!$y.test(t)?t:null}const Zy=/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d{1,9}[.)]\s+)+/u,Ky=/!?\[([^\]]*)\]\([^)]*\)/gu,Vy=/\*\*|__|~~|`+/gu,Yy=/(?<![\p{L}\p{N}_*])[*_](?=[^\s*_])|(?<=[^\s*_])[*_](?![\p{L}\p{N}_*])/gu,Qy=/^[-=*_~`#> ]*$/;function Jy(e){return e.replace(Zy,"").replace(Ky,"$1").replace(Vy,"").replace(Yy,"")}function ps(e){if(typeof e!="string")return null;for(const t of e.split(Hy)){const n=wr(Jy(t));if(n&&!Qy.test(n))return n}return null}const xt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function nu(e){if(typeof e!="string")return null;try{return JSON.parse(e)}catch{}const t=e.indexOf(`
19
+ `,ky=" — cancel with wake(",Ey=120,Jd=/(?:\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,Iy=new RegExp("\\p{Cf}","gu"),xy=4096;function Pn(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(Jd,"").replace(Iy,"").split(Qd).filter(Boolean).join(" ").slice(0,Ey)}const Zx={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function qd(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(wy,"");if(t){const n=t.split(Sy).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function eu(e){const{name:t,quoted:n}=qd(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function Ry(e){const{name:t,quoted:n}=qd(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 Kx(e,t){return t.trim()?!0:Ry(e)!==eu(e)}function Ty(e){for(const t of e.slice(0,xy).split(`
20
+ `)){const n=Pn(t);if(n)return n}return""}function Vx(e,t){const n=eu(e),r=Ty(t);return r?`${n} · ${r}`:n}function fs(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const Cy=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,Ay=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,Oy=/^<peer-session-message[^>]*>/,Py=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function tu(e){const t=String(e.text??e.detail??""),n=Cy.exec(t.trim()),r={};if(n)for(const d of n[1].matchAll(Py))r[d[1]]=d[2]??d[3]??d[4]??"";const i=n?n[2]:"",a=(String(e.body??"").trim()||i||(n?"":t.trim().replace(Oy,""))).replace(Ay,"").trim(),c=e.sender??{},l=(d,u)=>Pn(d)||Pn(u);return{body:a,sender:{pid:l(c.pid,r.from_pid),conversationName:l(c.conversation_name,r.conversation),cwd:l(c.cwd,void 0),sessionId:l(c.session_id,void 0),modelLabel:l(c.model_label,r.model)}}}function jy(e){return!!e.wake_catchup}function My(e){return e.hidden===!0}function Yx(e){let t=e.split(Xd)[0]??"";t=t.split(Qd).filter(Boolean).join(" "),t=t.split(ky)[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 Qx(e){const t=e.indexOf(Xd);return t===-1?"":e.slice(t+2).trim()}const Qr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},zn=e=>typeof e=="string"?Pn(e):"";function Dy(e){const t=Qr(e.bridge_receipt),n=t.v===1,r=Qr(n?t.sender:e.sender),i=n?Qr(t.conversation):{},s=n?t.attachment_count:void 0;return{sender:{name:zn(r.name),...r.kind==="human"||r.kind==="agent"?{kind:r.kind}:{},...zn(r.organization)?{organization:zn(r.organization)}:{}},conversation:{...i.kind==="dm"||i.kind==="group"||i.kind==="channel"?{kind:i.kind}:{},...zn(i.label)?{label:zn(i.label)}:{}},...typeof s=="number"&&Number.isSafeInteger(s)&&s>=0?{attachmentCount:s}:{}}}const Ny=new Set(["channel_post","channel_create","channel_history","channel_thread","react","shared_history"]),Ly=new Set(["channel_post","dm","send","reply"]),$y=new Set(["take_up","ack","send","reply","channels","channel_create","channel_post","channel_history","react","channel_thread","directory","dm","shared_conversations","shared_history"]),Uy=/^(?:bcv|bcmsg|acc|ep)_/i,Fy=/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]|\x9b[0-?]*[ -/]*[@-~]/g,By=/[\x00-\x08\x0e-\x1f\x7f-\x9f]/g,Gy=new RegExp("(?![\\u200c\\u200d])\\p{Cf}","gu"),Hy=/[\t\n\r\v\f ]+/,zy=/\r\n|\r|\n/,Wy=/^bcv_\S+$/,Zy=200;function wr(e){return typeof e!="string"?null:e.replace(Fy,"").replace(By,"").replace(Gy,"").split(Hy).filter(Boolean).join(" ").slice(0,Zy)||null}function Jt(e){const t=wr(e);return t&&!Uy.test(t)?t:null}const Ky=/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d{1,9}[.)]\s+)+/u,Vy=/!?\[([^\]]*)\]\([^)]*\)/gu,Yy=/\*\*|__|~~|`+/gu,Qy=/(?<![\p{L}\p{N}_*])[*_](?=[^\s*_])|(?<=[^\s*_])[*_](?![\p{L}\p{N}_*])/gu,Xy=/^[-=*_~`#> ]*$/;function Jy(e){return e.replace(Ky,"").replace(Vy,"$1").replace(Yy,"").replace(Qy,"")}function ps(e){if(typeof e!="string")return null;for(const t of e.split(zy)){const n=wr(Jy(t));if(n&&!Xy.test(n))return n}return null}const xt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function nu(e){if(typeof e!="string")return null;try{return JSON.parse(e)}catch{}const t=e.indexOf(`
21
21
 
22
- `);if(t<0)return null;try{return JSON.parse(e.slice(t+2))}catch{return null}}function Xy(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 ru(e){return Dy.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function iu(e,t,n){const r=Xt(n?.conversation_label);if(r)return r;if(e==="dm"&&typeof n?.content=="string"){const a="direct message to ";if(n.content.startsWith(a)){const c=n.content.slice(a.length),l=c.indexOf(" in bcv_"),d=l>0?Xt(c.slice(0,l)):null;if(d)return d}}if(e==="channel_create"){const a=xt(nu(n?.content)),c=Xt(a?.name);if(c)return c}if(e==="channel_create"){const a=Xt(t.name);if(a)return a}const i=ru(e);if(i!=="person"&&i!=="dm")return null;const s=xt(t.to);return Xt(s?.name)}function qy(e,t,n){const r=ru(e);return r==="none"||r==="message"||r==="directory"?{kind:r,label:null}:{kind:r,label:iu(e,t,n)}}function eb(e){if(Array.isArray(e))return e.length;const t=xt(e);if(!t)return null;for(const n of["conversations","items","data"])if(Array.isArray(t[n]))return t[n].length;return null}function tb(e,t){if(!t)return null;const n=nu(t.content),r=xt(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 i=xt(r.root)?1:0,s=Array.isArray(r.replies)?r.replies.length:null;return s===null&&i===0?null:i+(s??0)}return e==="directory"?typeof r?.count=="number"&&Number.isInteger(r.count)?r.count:Array.isArray(t.members)?t.members.length:null:e==="channels"||e==="shared_conversations"?eb(n):null}function nb(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=wr(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 Ai(e,t){const n=e??{},r=wr(n.op)??"",i=xt(t),s=Ly.has(r),a=Ny.has(r)||r==="take_up"?ps(n.body)??ps(n.text)??ps(i?.text):null;return{op:r,action:Xy(r,n,i),target:s?qy(r,n,i):{kind:"none",label:null},preview:a,count:s&&i?.ok===!0?tb(r,i):null,emoji:r==="react"?wr(n.emoji):null,...s?nb(r,i):{outcome:null,code:null}}}function su(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&zy.test(n.trim()))return n.trim();return null}const rb=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"]),ou=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return rb.has(t)?t:"unknown"},ib={channel_post:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function qs(e){return ib[ou(e)]()}function au(e,t=null){const{kind:n}=e.target,r=e.target.label??Xt(t);return r?n==="channel"&&!r.startsWith("#")?`#${r}`:r:e.op==="shared_history"?"":n==="channel"?h("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?h("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?h("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?h("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function eo(e,t,n,r){const i=su(t,r),s=!e.target.label&&i&&n?n(i):null,a=au(e,s),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?a:h("ui.chat.canonical.tool_row.bridge.summary.messages",{target:a,count:e.count}).trim();switch(ou(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?h("ui.chat.canonical.tool_row.bridge.target.thread",{target:a}):a;return c(d,e.preview)}case"dm":case"send":case"reply":case"take_up":return c(a,e.preview);case"channels":case"shared_conversations":return e.count===null?"":h("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":h("ui.chat.canonical.tool_row.bridge.summary.members",{count:e.count});case"channel_history":case"channel_thread":case"shared_history":return l();case"react":case"react_remove":return c(a,e.emoji);case"channel_create":case"ack_working":case"ack_done":return a;default:return e.op}}function sb(e){return e.outcome==="refused"?e.code?h("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):h("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?h("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):h("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const ob=["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 cu(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const r=xt(t);if(!r)return n??null;const{_images:i,...s}=r;return n&&cb(n,s)?n:s}function ab(e){const t=xt(e);if(!t)return null;const n=t.destination_type==="conversation_dm"?"dm":t.state==="created"?"channel_create":"channel_post";return iu(n,{},t)}function lu(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:xt(t)?ab(t):n??null}function cb(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 lb={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"},db=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function zc(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function Kx(e,t){const n=e.args??{},r=e.details??null,i=Ai(n,r),s=i.target.label===null&&e.label&&i.target.kind!=="none"&&i.target.kind!=="message"&&i.target.kind!=="directory"?{...i,target:{...i.target,label:e.label}}:i,a=su(n,r),c=!s.target.label&&a&&t?t(a):null,l=au(s,c),d=s.outcome==="refused"||s.outcome==="failed",u=e.failed||d?qs(s.action).failed:null,f=u??qs(s.action).settled,p=eo({...s,preview:null,emoji:null},n,t,r),g=s.target.label??Xt(c)??h("ui.chat.canonical.tool_row.bridge.fallback.teammate"),y=s.op==="dm"?h("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:g}):p?h("ui.chat.canonical.tool_row.bridge.detail.headline.target",{verb:f,target:p}):f,m=[n.body,n.text,r?.text].find(F=>typeof F=="string"&&F.trim()!==""),b=typeof r?.seq=="number"?r.seq:null,_=zc(r?.error),k=(s.target.kind==="channel"||s.target.kind==="dm")&&l?l:h("ui.chat.canonical.tool_row.bridge.fallback.conversation"),E=_?_.replace(db,(F,se)=>se.toLowerCase()==="bcv"?k:"…"):null,A=s.outcome==="refused"||s.outcome==="failed"?E&&s.code?h(s.outcome==="refused"?"ui.chat.canonical.tool_row.bridge.detail.outcome.refused":"ui.chat.canonical.tool_row.bridge.detail.outcome.failed",{code:s.code,error:E}):E:s.outcome==="unconfirmed"?E:r?.ok===!0&&b!==null?h("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:b}):null,$=[],O=new Set,C=(F,se)=>{const me=zc(se);me===null||O.has(F)||(O.add(F),$.push({key:F,value:me}))};for(const F of ob)C(F,r?.[F]);_&&_!==E&&C("error",_);for(const[F,se]of Object.entries(lb))C(se,n[F]);const I=typeof r?.content=="string"&&r.content||e.output||null,N=I&&I.trim()===_?null:I;return{tokens:s,summary:eo(s,n,t,r),failedVerb:u,failureWord:sb(s),headline:y,body:m??null,outcome:A,internals:$,raw:N}}const ub=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),fb=new Set(["true","yes","y","t","on","1"]),pb={hub:{steps:e=>{const t=In(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=In(e);return t!==null&&t>0?`· ${pu(t/1e3)}`:""}}};function In(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 Wc="mcp__",hb=/^\/(?:Users|home)\/[^/]+\//,mb=/\s+/;function gb(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(hb,"~/")}function Ve(e){return typeof e=="string"?gb(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function _b(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function yb(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(mb).filter(Boolean).join(" ")||"?"}function bb(e){return[_b(e),Ve(yb(e))||"?",Ve(e.message)].filter(Boolean).join(" · ")}const vb=new Set(["delivered","mailbox","unconfirmed","failed"]);function wb(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:r}=Ai({op:n},t);return r==="inbox_only"?"inbox_only":r==="awaiting_acceptance"?"awaiting_acceptance":r==="unconfirmed"?"unconfirmed":null}function Sb(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return wb(e);const n=e.delivery;if(!n||typeof n!="object")return null;const r=n.state;return typeof r=="string"&&vb.has(r)?r:null}function du(e,t,n){return!e||typeof e!="object"?t??null:Sb(e,n)}function kb(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 Eb=["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 Ib(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],i=t[n];if(!(!!r&&typeof r=="object")||!(!!i&&typeof i=="object")){if(r!==i)return!1;continue}const c=r,l=i;if(c.message!==l.message||c.timestamp!==l.timestamp)return!1}return!0}const xb=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function Rb(e,t){return e===t?!0:!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>{const i=t[r];return!n||typeof n!="object"||!i||typeof i!="object"?n===i:xb.every(s=>s==="cost"?n.cost?.basis===i.cost?.basis:n[s]===i[s])})}function Tb(e,t){for(const n of Eb){const r=e[n],i=t[n];if(n==="artifacts"){if(!Rb(r,i))return!1;continue}if(n==="cost"){const s=a=>a&&typeof a=="object"?a.basis:void 0;if(s(r)!==s(i))return!1;continue}if(n==="log_lines"){if(!Ib(r,i))return!1;continue}if(r!==i)return!1}return!0}function to(e,t){const n=kb(e);return n?t&&Tb(n,t)?t:n:t??null}const Cb={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},Ab={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."},Ob={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."},Pb={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function uu(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const Or=e=>e.trim().toLowerCase()==="bridge";function Vx(e,t=""){return e?e==="inbox_only"?h("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?h("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&Or(t)?h("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):Cb[e]??null:null}function Yx(e,t){return e==="inbox_only"?h("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?h("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&Or(t)?h("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function Qx(e,t=""){if(e)return e==="inbox_only"?h("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?h("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&Or(t)?h("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):Ab[e]}function Jx(e,t=""){return e?e==="inbox_only"?h("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?h("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&Or(t)?h("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):Pb[e]??null:null}function Xx(e,t=""){return e?e==="inbox_only"?h("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?h("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&Or(t)?h("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):Ob[e]??null:null}function qx(e){return uu(e)?"partial":null}function eR(e){return e==="failed"?"Attempted":null}function tR(e,t){return e!==!0?!1:!uu(t)}function Zc(e){const t=In(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:Ve(e.session)||Ve(e.target)||"?"}function jb(e){const t=Ve(e.query);if(t){const a=In(e.steps);return a!==null&&Number.isInteger(a)&&a>=0?`search ${t} · ${a} around`:`search ${t}`}const n=In(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=In(e.head);if(r!==null&&Number.isInteger(r)&&r>=0)return`first ${r}`;if(e.digest===!0)return"digest";const i=Ve(e.before_id);if(i)return`before ${i}`;const s=Ve(e.around_id);return s?`around ${s}`:""}function Mb(e){const t=$b(e);if(t==="spawn"){const n=Ve(e.visibility)||"workstream",r=Ve(e.name)||Ve(e.prompt);return[n,r].filter(Boolean).join(" · ")}if(t==="stop"||t==="resume"||t==="info")return Zc(e);if(t==="peek")return[Zc(e),jb(e)].filter(Boolean).join(" · ");if(t==="list"){const n=[];e.include_stored===!0&&n.push("stored");const r=Ve(e.query);return r&&n.push(r),n.join(" · ")}return null}function nR(e,t,n,r){const i=e.trim();if(i.toLowerCase()==="bridge")return eo(Ai(t,n),t,r,n);if(!t)return i;if(i==="send")return bb(t)||i;if(i.toLowerCase()==="sessions"){const c=Mb(t);if(c!==null)return c||i}const s=Ub(i)?Object.entries(t).filter(([c])=>!hu.has(c)):Object.entries(t);let a=s.filter(([c])=>ub.has(c)).map(([,c])=>Ve(c)).filter(Boolean);if(a.length===0){const c=pb[i.toLowerCase()];a=s.map(([l,d])=>c?.[l]?.(d)||Ve(d)).filter(Boolean)}return a.slice(0,2).join(" ")||i}function fu(e){const t=e.trim();if(!t.toLowerCase().startsWith(Wc))return t;const n=t.slice(Wc.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function Db(e,t){return e===t||e===fu(t)}const Nb=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,Lb="… ";function rR(e,t=!1){if(!e||t)return null;for(const n of e.split(`
23
- `)){const r=n.trim();if(r&&!Nb.test(r))return`${Lb}${r.slice(0,160)}`}return null}function pu(e){const t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;if(t<3600){const i=Math.floor(t/60),s=t%60;return s===0?`${i}m`:`${i}m${s}s`}if(t<86400){const i=Math.floor(t/3600),s=Math.floor(t%3600/60);return s===0?`${i}h`:`${i}h${s}m`}const n=Math.floor(t/86400);if(n>99)return"100d+";const r=Math.floor(t%86400/3600);return r===0?`${n}d`:`${n}d${r}h`}function iR(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`:pu(t)}function Kc(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 sR(e){return e<1024?`${e} B`:e<1024*1024?`${Kc(e/1024)} KB`:`${Kc(e/(1024*1024))} MB`}function Vc(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const Yc={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 oR(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Yc,t)?Yc[t]:"plain"}function $b(e){if(!e)return"";for(const t of hu){const n=e[t];if(typeof n=="string"&&n.trim()){const r=n.trim().toLowerCase(),i=e.remove,s=i===!0||i===1||typeof i=="string"&&fb.has(i.toLowerCase());return r==="milestone"&&s?"milestone-remove":t==="op"&&(r==="react"||r==="ack")?Ai(e).action:r}}return""}const hu=new Set(["op","action","method"]),Ub=e=>Object.prototype.hasOwnProperty.call(mu,e.trim().toLowerCase()),Fb={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"}},mu={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 Bb(e,t){const n=e.trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(n==="bridge"){const{settled:a,running:c}=qs(r);return{settled:a,running:c,named:!0}}const i=r?mu[n]?.[r]:void 0;if(i)return{...i,named:!0};const s=Fb[n];return s?{...s,named:!0}:{settled:h("ui.chat.canonical.tool_row.generic_verb.settled"),running:h("ui.chat.canonical.tool_row.generic_verb.running"),named:!1}}function aR(e,t,n,r,i="",s=null){const a=Bb(e,i),c=Db(t,e)?n??"":t;return{verb:r?a.running:s??a.settled,object:a.named?c:[fu(e),c].filter(Boolean).join(" ")}}const Gb=new Set(["write","edit"]);function Hb(e){return Gb.has(e.trim().toLowerCase())}function cR(e){return Hb(e.toolName)&&e.diff!==null&&!e.isError}function gu(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 zb(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 _u(e,t){return e===null||zb(e,t)?t:e}function yu(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:Vc(n.added),removed:Vc(n.removed)}}function Wb(e){return e.length>=2&&no(e[0])==="---"&&no(e[1])==="+++"?e.slice(2):e.slice()}const Zb=/\s+$/;function no(e){return e.replace(Zb,"")}function Kb(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const Vb=40;function lR(e){const t=Wb(e),n=t.slice(0,Vb);return{lines:n.map(r=>{const i=no(r);return{text:i,marker:i.slice(0,1),kind:Kb(i)}}),hidden:t.length-n.length}}function dR(e){return`… ${e} more diff line${e===1?"":"s"}`}const Yb=`Continue working toward this goal:
22
+ `);if(t<0)return null;try{return JSON.parse(e.slice(t+2))}catch{return null}}function qy(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 ru(e){return Ny.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function iu(e,t,n){const r=Jt(n?.conversation_label);if(r)return r;if(e==="dm"&&typeof n?.content=="string"){const a="direct message to ";if(n.content.startsWith(a)){const c=n.content.slice(a.length),l=c.indexOf(" in bcv_"),d=l>0?Jt(c.slice(0,l)):null;if(d)return d}}if(e==="channel_create"){const a=xt(nu(n?.content)),c=Jt(a?.name);if(c)return c}if(e==="channel_create"){const a=Jt(t.name);if(a)return a}const i=ru(e);if(i!=="person"&&i!=="dm")return null;const s=xt(t.to);return Jt(s?.name)}function eb(e,t,n){const r=ru(e);return r==="none"||r==="message"||r==="directory"?{kind:r,label:null}:{kind:r,label:iu(e,t,n)}}function tb(e){if(Array.isArray(e))return e.length;const t=xt(e);if(!t)return null;for(const n of["conversations","items","data"])if(Array.isArray(t[n]))return t[n].length;return null}function nb(e,t){if(!t)return null;const n=nu(t.content),r=xt(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 i=xt(r.root)?1:0,s=Array.isArray(r.replies)?r.replies.length:null;return s===null&&i===0?null:i+(s??0)}return e==="directory"?typeof r?.count=="number"&&Number.isInteger(r.count)?r.count:Array.isArray(t.members)?t.members.length:null:e==="channels"||e==="shared_conversations"?tb(n):null}function rb(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=wr(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 Ai(e,t){const n=e??{},r=wr(n.op)??"",i=xt(t),s=$y.has(r),a=Ly.has(r)||r==="take_up"?ps(n.body)??ps(n.text)??ps(i?.text):null;return{op:r,action:qy(r,n,i),target:s?eb(r,n,i):{kind:"none",label:null},preview:a,count:s&&i?.ok===!0?nb(r,i):null,emoji:r==="react"?wr(n.emoji):null,...s?rb(r,i):{outcome:null,code:null}}}function su(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&Wy.test(n.trim()))return n.trim();return null}const ib=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"]),ou=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return ib.has(t)?t:"unknown"},sb={channel_post:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:h("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:h("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:h("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function qs(e){return sb[ou(e)]()}function au(e,t=null){const{kind:n}=e.target,r=e.target.label??Jt(t);return r?n==="channel"&&!r.startsWith("#")?`#${r}`:r:e.op==="shared_history"?"":n==="channel"?h("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?h("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?h("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?h("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function eo(e,t,n,r){const i=su(t,r),s=!e.target.label&&i&&n?n(i):null,a=au(e,s),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?a:h("ui.chat.canonical.tool_row.bridge.summary.messages",{target:a,count:e.count}).trim();switch(ou(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?h("ui.chat.canonical.tool_row.bridge.target.thread",{target:a}):a;return c(d,e.preview)}case"dm":case"send":case"reply":case"take_up":return c(a,e.preview);case"channels":case"shared_conversations":return e.count===null?"":h("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":h("ui.chat.canonical.tool_row.bridge.summary.members",{count:e.count});case"channel_history":case"channel_thread":case"shared_history":return l();case"react":case"react_remove":return c(a,e.emoji);case"channel_create":case"ack_working":case"ack_done":return a;default:return e.op}}function ob(e){return e.outcome==="refused"?e.code?h("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):h("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?h("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):h("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const ab=["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 cu(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const r=xt(t);if(!r)return n??null;const{_images:i,...s}=r;return n&&lb(n,s)?n:s}function cb(e){const t=xt(e);if(!t)return null;const n=t.destination_type==="conversation_dm"?"dm":t.state==="created"?"channel_create":"channel_post";return iu(n,{},t)}function lu(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:xt(t)?cb(t):n??null}function lb(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 db={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"},ub=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function zc(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function Xx(e,t){const n=e.args??{},r=e.details??null,i=Ai(n,r),s=i.target.label===null&&e.label&&i.target.kind!=="none"&&i.target.kind!=="message"&&i.target.kind!=="directory"?{...i,target:{...i.target,label:e.label}}:i,a=su(n,r),c=!s.target.label&&a&&t?t(a):null,l=au(s,c),d=s.outcome==="refused"||s.outcome==="failed",u=e.failed||d?qs(s.action).failed:null,f=u??qs(s.action).settled,p=eo({...s,preview:null,emoji:null},n,t,r),g=s.target.label??Jt(c)??h("ui.chat.canonical.tool_row.bridge.fallback.teammate"),y=s.op==="dm"?h("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:g}):p?h("ui.chat.canonical.tool_row.bridge.detail.headline.target",{verb:f,target:p}):f,m=[n.body,n.text,r?.text].find(F=>typeof F=="string"&&F.trim()!==""),b=typeof r?.seq=="number"?r.seq:null,_=zc(r?.error),k=(s.target.kind==="channel"||s.target.kind==="dm")&&l?l:h("ui.chat.canonical.tool_row.bridge.fallback.conversation"),E=_?_.replace(ub,(F,se)=>se.toLowerCase()==="bcv"?k:"…"):null,A=s.outcome==="refused"||s.outcome==="failed"?E&&s.code?h(s.outcome==="refused"?"ui.chat.canonical.tool_row.bridge.detail.outcome.refused":"ui.chat.canonical.tool_row.bridge.detail.outcome.failed",{code:s.code,error:E}):E:s.outcome==="unconfirmed"?E:r?.ok===!0&&b!==null?h("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:b}):null,$=[],O=new Set,C=(F,se)=>{const me=zc(se);me===null||O.has(F)||(O.add(F),$.push({key:F,value:me}))};for(const F of ab)C(F,r?.[F]);_&&_!==E&&C("error",_);for(const[F,se]of Object.entries(db))C(se,n[F]);const I=typeof r?.content=="string"&&r.content||e.output||null,N=I&&I.trim()===_?null:I;return{tokens:s,summary:eo(s,n,t,r),failedVerb:u,failureWord:ob(s),headline:y,body:m??null,outcome:A,internals:$,raw:N}}const fb=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),pb=new Set(["true","yes","y","t","on","1"]),hb={hub:{steps:e=>{const t=In(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=In(e);return t!==null&&t>0?`· ${pu(t/1e3)}`:""}}};function In(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 Wc="mcp__",mb=/^\/(?:Users|home)\/[^/]+\//,gb=/\s+/;function _b(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(mb,"~/")}function Ve(e){return typeof e=="string"?_b(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function yb(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function bb(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(gb).filter(Boolean).join(" ")||"?"}function vb(e){return[yb(e),Ve(bb(e))||"?",Ve(e.message)].filter(Boolean).join(" · ")}const wb=new Set(["delivered","mailbox","unconfirmed","failed"]);function Sb(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:r}=Ai({op:n},t);return r==="inbox_only"?"inbox_only":r==="awaiting_acceptance"?"awaiting_acceptance":r==="unconfirmed"?"unconfirmed":null}function kb(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return Sb(e);const n=e.delivery;if(!n||typeof n!="object")return null;const r=n.state;return typeof r=="string"&&wb.has(r)?r:null}function du(e,t,n){return!e||typeof e!="object"?t??null:kb(e,n)}function Eb(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 Ib=["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 xb(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],i=t[n];if(!(!!r&&typeof r=="object")||!(!!i&&typeof i=="object")){if(r!==i)return!1;continue}const c=r,l=i;if(c.message!==l.message||c.timestamp!==l.timestamp)return!1}return!0}const Rb=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function Tb(e,t){return e===t?!0:!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>{const i=t[r];return!n||typeof n!="object"||!i||typeof i!="object"?n===i:Rb.every(s=>s==="cost"?n.cost?.basis===i.cost?.basis:n[s]===i[s])})}function Cb(e,t){for(const n of Ib){const r=e[n],i=t[n];if(n==="artifacts"){if(!Tb(r,i))return!1;continue}if(n==="cost"){const s=a=>a&&typeof a=="object"?a.basis:void 0;if(s(r)!==s(i))return!1;continue}if(n==="log_lines"){if(!xb(r,i))return!1;continue}if(r!==i)return!1}return!0}function to(e,t){const n=Eb(e);return n?t&&Cb(n,t)?t:n:t??null}const Ab={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},Ob={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."},Pb={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."},jb={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function uu(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const Or=e=>e.trim().toLowerCase()==="bridge";function Jx(e,t=""){return e?e==="inbox_only"?h("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?h("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&Or(t)?h("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):Ab[e]??null:null}function qx(e,t){return e==="inbox_only"?h("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?h("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&Or(t)?h("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function eR(e,t=""){if(e)return e==="inbox_only"?h("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?h("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&Or(t)?h("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):Ob[e]}function tR(e,t=""){return e?e==="inbox_only"?h("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?h("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&Or(t)?h("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):jb[e]??null:null}function nR(e,t=""){return e?e==="inbox_only"?h("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?h("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&Or(t)?h("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):Pb[e]??null:null}function rR(e){return uu(e)?"partial":null}function iR(e){return e==="failed"?"Attempted":null}function sR(e,t){return e!==!0?!1:!uu(t)}function Zc(e){const t=In(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:Ve(e.session)||Ve(e.target)||"?"}function Mb(e){const t=Ve(e.query);if(t){const a=In(e.steps);return a!==null&&Number.isInteger(a)&&a>=0?`search ${t} · ${a} around`:`search ${t}`}const n=In(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=In(e.head);if(r!==null&&Number.isInteger(r)&&r>=0)return`first ${r}`;if(e.digest===!0)return"digest";const i=Ve(e.before_id);if(i)return`before ${i}`;const s=Ve(e.around_id);return s?`around ${s}`:""}function Db(e){const t=Ub(e);if(t==="spawn"){const n=Ve(e.visibility)||"workstream",r=Ve(e.name)||Ve(e.prompt);return[n,r].filter(Boolean).join(" · ")}if(t==="stop"||t==="resume"||t==="info")return Zc(e);if(t==="peek")return[Zc(e),Mb(e)].filter(Boolean).join(" · ");if(t==="list"){const n=[];e.include_stored===!0&&n.push("stored");const r=Ve(e.query);return r&&n.push(r),n.join(" · ")}return null}function oR(e,t,n,r){const i=e.trim();if(i.toLowerCase()==="bridge")return eo(Ai(t,n),t,r,n);if(!t)return i;if(i==="send")return vb(t)||i;if(i.toLowerCase()==="sessions"){const c=Db(t);if(c!==null)return c||i}const s=Fb(i)?Object.entries(t).filter(([c])=>!hu.has(c)):Object.entries(t);let a=s.filter(([c])=>fb.has(c)).map(([,c])=>Ve(c)).filter(Boolean);if(a.length===0){const c=hb[i.toLowerCase()];a=s.map(([l,d])=>c?.[l]?.(d)||Ve(d)).filter(Boolean)}return a.slice(0,2).join(" ")||i}function fu(e){const t=e.trim();if(!t.toLowerCase().startsWith(Wc))return t;const n=t.slice(Wc.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function Nb(e,t){return e===t||e===fu(t)}const Lb=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,$b="… ";function aR(e,t=!1){if(!e||t)return null;for(const n of e.split(`
23
+ `)){const r=n.trim();if(r&&!Lb.test(r))return`${$b}${r.slice(0,160)}`}return null}function pu(e){const t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;if(t<3600){const i=Math.floor(t/60),s=t%60;return s===0?`${i}m`:`${i}m${s}s`}if(t<86400){const i=Math.floor(t/3600),s=Math.floor(t%3600/60);return s===0?`${i}h`:`${i}h${s}m`}const n=Math.floor(t/86400);if(n>99)return"100d+";const r=Math.floor(t%86400/3600);return r===0?`${n}d`:`${n}d${r}h`}function cR(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`:pu(t)}function Kc(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 lR(e){return e<1024?`${e} B`:e<1024*1024?`${Kc(e/1024)} KB`:`${Kc(e/(1024*1024))} MB`}function Vc(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const Yc={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 dR(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Yc,t)?Yc[t]:"plain"}function Ub(e){if(!e)return"";for(const t of hu){const n=e[t];if(typeof n=="string"&&n.trim()){const r=n.trim().toLowerCase(),i=e.remove,s=i===!0||i===1||typeof i=="string"&&pb.has(i.toLowerCase());return r==="milestone"&&s?"milestone-remove":t==="op"&&(r==="react"||r==="ack")?Ai(e).action:r}}return""}const hu=new Set(["op","action","method"]),Fb=e=>Object.prototype.hasOwnProperty.call(mu,e.trim().toLowerCase()),Bb={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"}},mu={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 Gb(e,t){const n=e.trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(n==="bridge"){const{settled:a,running:c}=qs(r);return{settled:a,running:c,named:!0}}const i=r?mu[n]?.[r]:void 0;if(i)return{...i,named:!0};const s=Bb[n];return s?{...s,named:!0}:{settled:h("ui.chat.canonical.tool_row.generic_verb.settled"),running:h("ui.chat.canonical.tool_row.generic_verb.running"),named:!1}}function uR(e,t,n,r,i="",s=null){const a=Gb(e,i),c=Nb(t,e)?n??"":t;return{verb:r?a.running:s??a.settled,object:a.named?c:[fu(e),c].filter(Boolean).join(" ")}}const Hb=new Set(["write","edit"]);function zb(e){return Hb.has(e.trim().toLowerCase())}function fR(e){return zb(e.toolName)&&e.diff!==null&&!e.isError}function gu(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 Wb(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 _u(e,t){return e===null||Wb(e,t)?t:e}function yu(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:Vc(n.added),removed:Vc(n.removed)}}function Zb(e){return e.length>=2&&no(e[0])==="---"&&no(e[1])==="+++"?e.slice(2):e.slice()}const Kb=/\s+$/;function no(e){return e.replace(Kb,"")}function Vb(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const Yb=40;function pR(e){const t=Zb(e),n=t.slice(0,Yb);return{lines:n.map(r=>{const i=no(r);return{text:i,marker:i.slice(0,1),kind:Vb(i)}}),hidden:t.length-n.length}}function hR(e){return`… ${e} more diff line${e===1?"":"s"}`}const Qb=`Continue working toward this goal:
25
25
 
26
- `,Qb=`
26
+ `,Xb=`
27
27
 
28
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.`,Jb=`Work toward this goal:
29
29
 
30
30
  {goal}
31
31
 
32
- Make concrete progress with the tools available, then briefly state what advanced and what remains. If the goal is already fully met, say so plainly.`,[Xb="",qb=""]=Jb.split("{goal}"),ev="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.",tv="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.",nv="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 bu(e){const t=e.trim();return t===ev||t===tv||t===nv||t.startsWith(Yb)&&t.endsWith(Qb)||t.startsWith(Xb.trim())&&t.endsWith(qb.trim())}const rv=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function iv(e,t){const n=t?.match(rv)?.[0]??null;if(!e||typeof e!="object")return n;const r=e,i=r.cost_usd,s=r.billing_basis;if(typeof i!="number"||!Number.isFinite(i)||i<0)return n;if(s!=="billed"&&s!=="estimated")return null;const a=Number(i.toFixed(4));return`Cost ${a===0&&i>0?"<$0.0001":`$${a}`} (${s}).`}function vu(e){return e}const ro="supplement_v1",sv="superseded",_i=120,Ho=480,ov=20,uR=500;function zo(e){return`supplement:${e}`}function av(e){const t=e.payload??{};if(String(t.custom_type??"")!==ro)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?zo(r):null}function yi(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function cv(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:yi(t.size_bytes)??0,mtime:yi(t.mtime)??0,why:typeof t.why=="string"?t.why:""}}function wu(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=cv(n);r&&t.push(r)}return t}function lv(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!Eu(n))return null;const r=yi(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?_i:Math.min(Ho,Math.max(_i,Math.round(r)))}}function Su(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=lv(n);r&&t.push(r)}return t}function dv(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return Eu(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:yi(t.duration_s)}:null}function ku(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=dv(n);r&&t.push(r)}return t}const uv=/^[a-f0-9]{32}$/,fv=/\s+/,pv=/\.0$/;function Eu(e){return typeof e=="string"&&uv.test(e)}const hv={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function Qc(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 fR(e,t){const n=e.state;if(e.error===sv||e.dismissed||n==="skipped")return"nothing";if(n==="done")return e.files.length||e.components.length||e.sounds?.length?"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?hv[r]??r:r}const pR="Preparing highlights…",hR="Highlights cancelled",mR="Couldn't prepare highlights",gR="Adjust…",_R="Cancel",yR="Retry",mv=64,gv={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 bR(e){return typeof e=="string"&&e?gv[e]??"":""}function hs(e){return typeof e!="string"?"":e.replace(Xd,"").split(fv).filter(Boolean).join(" ")}function vR(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function _v(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(pv,"")} ${n}`;return""}function wR(e){const t=hs(e.name)||hs(e.path),n=hs(e.path);return{name:t,path:n===t?"":n,size:_v(e.sizeBytes)}}function ms(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function SR(e,t,n=e){return t?`Hide ${ms(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${ms(e,"graphic")}`:`Show ${ms(e,"graphic")}`}function kR(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const yv="supplement",bv=1,vv=["ready","resize","error","pong"],wv=["resize","error","pong"],Sv=64,Wo=300,ER=5e3,IR=2e4;function xR(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==yv||n.v!==bv)return null;const r=n.t;if(typeof r!="string"||!vv.includes(r))return null;const i=r;if(wv.includes(i)&&(!t||t.length>Sv||n.n!==t))return null;if(i==="error"){const s=n.msg;if(typeof s!="string"||s.length>Wo)return null}if(i==="resize"){const s=n.h;if(typeof s!="number"||!Number.isFinite(s)||s<0)return null}return{lo:"supplement",v:1,t:i,...typeof n.n=="string"?{n:n.n}:{},...typeof n.h=="number"?{h:n.h}:{},...typeof n.msg=="string"?{msg:n.msg}:{}}}function RR(){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 kv=["--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"],Ev=120;function Iv(e=typeof document>"u"?null:document.documentElement){if(!e||typeof getComputedStyle!="function")return{mode:"dark",vars:{}};const t=getComputedStyle(e),n={};for(const i of kv){const s=t.getPropertyValue(i).trim();s&&(n[i]=s.slice(0,Ev))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function TR(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(Iv()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function CR(e){return`data:text/html;base64,${xv(e)}`}function xv(e){const t=Rv(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let i=0;i<t.length;i+=3){const s=t[i]??0,a=t[i+1]??0,c=t[i+2]??0;r+=n[s>>2],r+=n[(s&3)<<4|a>>4],r+=i+1<t.length?n[(a&15)<<2|c>>6]:"=",r+=i+2<t.length?n[c&63]:"="}return r}function Rv(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 AR(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function Tv(e){return Math.min(Ho,Math.max(_i,e.heightHint))}function Cv(e){return Math.min(Ho,Math.max(_i,e))}function OR(e,t,n){let r=0;const i=[];for(let s=0;s<e.length;s+=1){const a=e[s],c=n?.get(a.attachment),l=c!==void 0?Cv(c):Tv(a);if(s>0&&(!i.every(u=>n?.get(u.attachment)!==void 0)||r+l>t))break;r+=l,i.push(a)}return{visible:i,hidden:e.slice(i.length)}}const Av=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,Iu=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,Ov=/kind=(auth|quota)\b/,Pv=/kind=(transient|timeout)\b/;function xu(e){const t=a=>typeof a=="string"&&Av.test(a)&&!a.includes("://")?a:"",n=t(e.model),r=Array.isArray(e.attempts)?e.attempts.map(t).filter(Boolean).slice(0,8):void 0,i=Array.isArray(e.detail)?e.detail.filter(a=>typeof a=="string"&&(Iu.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,s=typeof e.cause=="string"?e.cause.slice(0,mv):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...i?{detail:i}:{},...s?{cause:s}:{}}}function PR(e){if(!Iu.exec(e))return"";const n=e.split(" "),r=n[1].replace(":",""),i=n[3].slice(7),s=n[4].slice(5);return`Attempt ${r}: ${s}${i==="None"?"":` (HTTP ${i})`}`}function jR(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return Ov.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":Pv.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 jv(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return Ru(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:wu(e.files)}:{},...n==="done"?{components:Su(e.components),sounds:ku(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Wo)}:{},...xu(e),live:!Tu(n)}:null}function Mv(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!Ru(n))return null;const r=typeof e.files_more=="number"&&Number.isInteger(e.files_more)&&e.files_more>=0?e.files_more:0,i=Array.isArray(e.more)?e.more.filter(a=>typeof a=="string").slice(0,ov):[];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:wu(e.files),filesMore:r,more:i,components:Su(e.components),sounds:ku(e.sounds),...xu(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Wo)}:{}}}function Jc(e,t,n){const r=Mv(t);if(!r)return null;const i=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return Cu(i,r,e)}function Ru(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Tu(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Dv(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const i=t[r];return n.path===i.path&&n.name===i.name&&n.kind===i.kind&&n.sizeBytes===i.sizeBytes&&n.mtime===i.mtime&&n.why===i.why})}function Nv(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const i=t[r];return n.attachment===i.attachment&&n.title===i.title&&n.source===i.source&&n.mime===i.mime&&n.heightHint===i.heightHint})}function Lv(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const i=t[r];return n.attachment===i.attachment&&n.mime===i.mime&&n.title===i.title&&n.durationS===i.durationS})}function Cu(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&Qc(t.state)<Qc(e.state)))return null;const r=!e||t.version>e.version,i=t.files!==void 0?t.files:e?.files??[],s=t.components!==void 0?t.components:e?.components??[],a=t.sounds!==void 0?t.sounds:e?.sounds??[],c=t.filesMore!==void 0?t.filesMore:e?.filesMore??0,l=t.more!==void 0?t.more:e?.more??[],d=t.error??(r?"":e?.error??""),u=t.cause??(r?"":e?.cause??""),f=t.dismissed??(r?!1:e?.dismissed??!1),p=t.live!==void 0?t.live===!0?!0:Tu(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:zo(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:Dv(i,e?.files??[])?e?.files??[]:i,filesMore:c,more:$v(l,e?.more??[])?e?.more??[]:l,components:Nv(s,e?.components??[])?e?.components??[]:s,sounds:Lv(a,e?.sounds??[])?e?.sounds??[]:a,error:d,cause:u,model:t.model??(r?"":e?.model??""),attempts:t.attempts??(r?[]:e?.attempts??[]),detail:t.detail??(r?[]:e?.detail??[]),dismissed:f,live:p}}function $v(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const MR=e=>e.kind===void 0||e.kind==="image",st={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function Au(e){return e==="skipped"||e==="aborted"}function Xc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function qc(e,t,n,r){return Xc(n.args)??(r?.kind==="tool"?r.args:null)??Xc(e.argsByCall.get(t)?.arguments)}function Ou(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function Pu(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 Jr(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ft(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!Ou(n)&&Pu(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function en(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:nr;const i=[];for(const s of r){const a=Pu(s);if(s.type==="document"||a===null&&!Ou(s))continue;const c={id:`${t}:${i.length}`,data:typeof s.data=="string"&&s.data?s.data:null,attachment:typeof s.attachment=="string"&&s.attachment?s.attachment:null,mimeType:typeof s.content_type=="string"&&s.content_type||typeof s.mime_type=="string"&&s.mime_type||"image/png"};a!==null&&(c.kind=a,c.width=Jr(s.width),c.height=Jr(s.height),c.sizeBytes=Jr(s.size_bytes),c.durationS=Jr(s.duration_s),c.name=typeof s.name=="string"&&s.name?s.name:null,c.sourceUrl=typeof s.source_url=="string"&&s.source_url?s.source_url:null),i.push(c)}return i.length===0?nr:n&&Zo(n,i)?n:i}const nr=[],io=[];function ju(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:io;const i=[];for(const s of r){const a=typeof s.filename=="string"&&typeof s.mime_type=="string"&&typeof s.attachment=="string"&&s.type===void 0;s.type!=="document"&&!a||i.push({id:`${t}:doc:${i.length}`,attachment:typeof s.attachment=="string"&&s.attachment?s.attachment:null,filename:typeof s.filename=="string"&&s.filename?s.filename:s.name??"Attached file",mimeType:s.mime_type??"application/octet-stream",path:typeof s.path=="string"&&s.path?s.path:null,storedPath:typeof s.stored_path=="string"&&s.stored_path?s.stored_path:null,bytes:typeof s.bytes=="number"?s.bytes:0,...s.injection?{injection:s.injection}:{}})}return i.length===0?n?.length?n:io:n&&Uv(n,i)?n:i}function Uv(e,t){return e.length!==t.length?!1:e.every((n,r)=>{const i=t[r];return n.id===i.id&&n.attachment===i.attachment&&n.filename===i.filename&&n.mimeType===i.mimeType&&n.path===i.path&&n.storedPath===i.storedPath&&n.bytes===i.bytes&&n.injection===i.injection})}function el(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 Mu(e,t,n){if(t.length===0)return e;if(e.length===0||Zo(e,t))return t;const r=el(e),i=el(t);return r!==i?r>i?e:t:n==="incoming"?e:t}function Fv(e,t){return Mu(e,t,"incoming")}function Zo(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 Qe(e){const t=new Map;return e.forEach((n,r)=>t.set(n.id,r)),t}function Bv(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const Rt=new Set;function Ko(e){return e.kind==="user"&&e.provisional===!0}function Du(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{Ko(n)&&r<t&&(t=r)}),t}function Sr(e,t=Rt,n){if(n?.journalMode)return Ud(n,e).map(vu);const r=e.map((a,c)=>({record:a,position:c})),i=Du(e),s=a=>Ko(a.record)||a.position>i&&!t.has(a.record.id);return r.sort((a,c)=>{const l=s(a),d=s(c);return l!==d?l?1:-1:l?a.position-c.position:a.record.ts!==c.record.ts?a.record.ts-c.record.ts:a.position-c.position}).map(a=>a.record)}function Gv(e,t,n){if(!n||t<=0)return Rt;let r=null;for(const i of e){if(!Ko(i)||!(t>i.ts))continue;let s=!1,a=!1;for(const c of e)if(c.ts>i.ts?s=!0:c.ts<i.ts&&Jo(c)&&(a=!0),s&&a)break;s&&a&&(r??=new Set,r.add(i.id))}return r??Rt}function Hv(e){const{provisional:t,...n}=e;return n}function so(e,t){const n=e,r=t,i=Object.keys(n);if(i.length!==Object.keys(r).length)return!1;for(const s of i)if(n[s]!==r[s]){if(s==="images"){const a=n[s],c=r[s];if(Array.isArray(a)&&Array.isArray(c)&&Zo(a,c))continue}if(s==="frame"){const a=n[s],c=r[s];if(a!==void 0&&c!==void 0&&a.epoch===c.epoch&&a.seq===c.seq)continue}if(s==="skill"){const a=n[s],c=r[s];if(a!==void 0&&c!==void 0&&zv(a,c))continue}return!1}return!0}function zv(e,t){return e.name===t.name&&e.token===t.token&&e.request===t.request&&e.purpose===t.purpose&&e.body===t.body}function be(e,t){const n=e.index.get(t.id);if(n!==void 0){const s=e.records[n];if(so(s,t))return e;const a=e.records.slice();if(a[n]=e.journalMode?{...t,...s.sourceEntryId?{sourceEntryId:t.sourceEntryId??s.sourceEntryId}:{},...s.sourceAdmissionAnchor&&!t.sourceAdmissionAnchor?{sourceAdmissionAnchor:s.sourceAdmissionAnchor}:{},...s.sourcePrecedes&&!t.sourcePrecedes?{sourcePrecedes:s.sourcePrecedes}:{},...s.journalGeneration?{journalGeneration:t.journalGeneration??s.journalGeneration,journalSeq:t.journalSeq??s.journalSeq}:{}}:t,!e.journalMode)return{...e,records:a};const c=Sr(a,Rt,e);return{...e,records:c,index:Qe(c)}}const r=e.journalMode?Sr([...e.records,t],Rt,e):[...e.records,t],i=Qe(r);return{...e,records:r,index:i}}function Vo(e,t){if(!e.records.some(t))return e;const n=e.records.filter(r=>!t(r));return{...e,records:n,index:Qe(n)}}function gs(e,t){const n=`tool:${t}`,r=e.index.get(n);if(r===void 0)return e;const i=e.records[r];return i.kind==="tool"&&(i.phase==="composing"||i.phase==="queued")?Vo(e,s=>s.id===n):e}function Wv(e,t,n){const r=e.index.get(`tool:${t}`);if(r===void 0)return e;const i=e.records[r];if(!(i.kind==="tool"&&(i.phase==="composing"||i.phase==="queued")))return e;const s=e.records.slice();return s[r]=n,{...e,records:s,index:Qe(s)}}const Zv=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function Nu(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 Kv(e,t){const n=dl(e),r=dl(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const Lu="Context compacted",Vv=12e4;function $u(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,i=new Set,s=new Map,a=(d,u)=>{r.add(u.id),i.add(d.id),s.set(u.id,d.text)},c=[...t].sort((d,u)=>d.ts-u.ts);for(const d of c){if(d.before===void 0)continue;const u=n.find(f=>!r.has(f.id)&&f.before===d.before);u&&a(d,u)}const l=[];for(const d of c)if(!i.has(d.id))for(const u of n){if(u.before!==void 0)continue;const f=Math.abs(u.ts-d.ts);f>Vv||l.push({live:d,durable:u,distance:f})}l.sort((d,u)=>d.distance-u.distance);for(const{live:d,durable:u}of l)i.has(d.id)||r.has(u.id)||a(d,u);return i.size===0?e:e.filter(d=>!i.has(d.id)).map(d=>{const u=s.get(d.id);return u===void 0||d.kind!=="compaction"&&d.kind!=="notice"||u===d.text?d:{...d,text:u}})}function Yv(e){const t=$u(e.records);return t===e.records?e:{...e,records:t,index:Qe(t)}}const Qv="peer_message",Jv="ask_response",Xv="ask_timeout",Uu="Completed — runtime retired/disposed",Fu="Retired for an update — a turn was in flight and was cut; its earlier output is kept",qv="wake_prompt",ew="session_mcp_unavailable",tw=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),nw=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,tl=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,rw=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."]),Bu=/^\[[^\]]{1,32}\]\s*/,bi="Reason:",iw=/[\n;,(]| [—–] /,sw=/^\d+\.$/,ow=/[A-Z]/,aw=/\s/,rr=160;function ri(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",...fw(t,n)};let r;return e===ew?r=cw(t):tw.has(e)?r=dw(t.trim().replace(Bu,"")):r=pw(t),{level:"info",category:null,provider:null,...r}}function cw(e){const t=e.trim().replace(Bu,"").split(`
32
+ Make concrete progress with the tools available, then briefly state what advanced and what remains. If the goal is already fully met, say so plainly.`,[qb="",ev=""]=Jb.split("{goal}"),tv="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.",nv="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.",rv="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 bu(e){const t=e.trim();return t===tv||t===nv||t===rv||t.startsWith(Qb)&&t.endsWith(Xb)||t.startsWith(qb.trim())&&t.endsWith(ev.trim())}const iv=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function sv(e,t){const n=t?.match(iv)?.[0]??null;if(!e||typeof e!="object")return n;const r=e,i=r.cost_usd,s=r.billing_basis;if(typeof i!="number"||!Number.isFinite(i)||i<0)return n;if(s!=="billed"&&s!=="estimated")return null;const a=Number(i.toFixed(4));return`Cost ${a===0&&i>0?"<$0.0001":`$${a}`} (${s}).`}function vu(e){return e}const ro="supplement_v1",ov="superseded",_i=120,Ho=480,av=20,mR=500,cv=10,lv=["outside","sensitive","missing","too-large"];function wu(e,t){const n=[];let r=0;if(Array.isArray(e))for(const s of e.slice(0,cv)){if(!s||typeof s!="object")continue;const a=s,c=a.reason;if(!lv.includes(c)){r+=1;continue}n.push({name:typeof a.name=="string"?a.name:"",reason:c})}const i=typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;return{withheld:n,withheldMore:i+r}}function zo(e){return`supplement:${e}`}function dv(e){const t=e.payload??{};if(String(t.custom_type??"")!==ro)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?zo(r):null}function yi(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function uv(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:yi(t.size_bytes)??0,mtime:yi(t.mtime)??0,why:typeof t.why=="string"?t.why:"",...t.pinned===!0?{pinned:!0}:{}}}function Su(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=uv(n);r&&t.push(r)}return t}function fv(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!Iu(n))return null;const r=yi(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?_i:Math.min(Ho,Math.max(_i,Math.round(r)))}}function ku(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=fv(n);r&&t.push(r)}return t}function pv(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return Iu(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:yi(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 Eu(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=pv(n);r&&t.push(r)}return t}const hv=/^[a-f0-9]{32}$/,mv=/\s+/,gv=/\.0$/;function Iu(e){return typeof e=="string"&&hv.test(e)}const _v={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function Qc(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 gR(e,t){const n=e.state;if(e.error===ov||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?_v[r]??r:r}const _R="Preparing highlights…",yR="Highlights cancelled",bR="Couldn't prepare highlights",vR="Adjust…",wR="Cancel",SR="Retry",yv=64,bv={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 kR(e){return typeof e=="string"&&e?bv[e]??"":""}function hs(e){return typeof e!="string"?"":e.replace(Jd,"").split(mv).filter(Boolean).join(" ")}function ER(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function vv(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(gv,"")} ${n}`;return""}function IR(e){const t=hs(e.name)||hs(e.path),n=hs(e.path);return{name:t,path:n===t?"":n,size:vv(e.sizeBytes)}}function ms(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function xR(e,t,n=e){return t?`Hide ${ms(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${ms(e,"graphic")}`:`Show ${ms(e,"graphic")}`}function RR(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const wv="supplement",Sv=1,kv=["ready","resize","error","pong"],Ev=["resize","error","pong"],Iv=64,Wo=300,TR=5e3,CR=2e4;function AR(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==wv||n.v!==Sv)return null;const r=n.t;if(typeof r!="string"||!kv.includes(r))return null;const i=r;if(Ev.includes(i)&&(!t||t.length>Iv||n.n!==t))return null;if(i==="error"){const s=n.msg;if(typeof s!="string"||s.length>Wo)return null}if(i==="resize"){const s=n.h;if(typeof s!="number"||!Number.isFinite(s)||s<0)return null}return{lo:"supplement",v:1,t:i,...typeof n.n=="string"?{n:n.n}:{},...typeof n.h=="number"?{h:n.h}:{},...typeof n.msg=="string"?{msg:n.msg}:{}}}function OR(){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 xv=["--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"],Rv=120;function Tv(e=typeof document>"u"?null:document.documentElement){if(!e||typeof getComputedStyle!="function")return{mode:"dark",vars:{}};const t=getComputedStyle(e),n={};for(const i of xv){const s=t.getPropertyValue(i).trim();s&&(n[i]=s.slice(0,Rv))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function PR(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(Tv()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function jR(e){return`data:text/html;base64,${Cv(e)}`}function Cv(e){const t=Av(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let i=0;i<t.length;i+=3){const s=t[i]??0,a=t[i+1]??0,c=t[i+2]??0;r+=n[s>>2],r+=n[(s&3)<<4|a>>4],r+=i+1<t.length?n[(a&15)<<2|c>>6]:"=",r+=i+2<t.length?n[c&63]:"="}return r}function Av(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 MR(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function Ov(e){return Math.min(Ho,Math.max(_i,e.heightHint))}function Pv(e){return Math.min(Ho,Math.max(_i,e))}function DR(e,t,n){let r=0;const i=[];for(let s=0;s<e.length;s+=1){const a=e[s],c=n?.get(a.attachment),l=c!==void 0?Pv(c):Ov(a);if(s>0&&(!i.every(u=>n?.get(u.attachment)!==void 0)||r+l>t))break;r+=l,i.push(a)}return{visible:i,hidden:e.slice(i.length)}}const jv=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,xu=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,Mv=/kind=(auth|quota)\b/,Dv=/kind=(transient|timeout)\b/;function Ru(e){const t=a=>typeof a=="string"&&jv.test(a)&&!a.includes("://")?a:"",n=t(e.model),r=Array.isArray(e.attempts)?e.attempts.map(t).filter(Boolean).slice(0,8):void 0,i=Array.isArray(e.detail)?e.detail.filter(a=>typeof a=="string"&&(xu.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,s=typeof e.cause=="string"?e.cause.slice(0,yv):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...i?{detail:i}:{},...s?{cause:s}:{}}}function NR(e){if(!xu.exec(e))return"";const n=e.split(" "),r=n[1].replace(":",""),i=n[3].slice(7),s=n[4].slice(5);return`Attempt ${r}: ${s}${i==="None"?"":` (HTTP ${i})`}`}function LR(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return Mv.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":Dv.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 Nv(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return Tu(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:Su(e.files),..."withheld"in e||"withheld_more"in e?wu(e.withheld,e.withheld_more):{}}:{},...n==="done"?{components:ku(e.components),sounds:Eu(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Wo)}:{},...Ru(e),live:!Cu(n)}:null}function Lv(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!Tu(n))return null;const r=typeof e.files_more=="number"&&Number.isInteger(e.files_more)&&e.files_more>=0?e.files_more:0,i=Array.isArray(e.more)?e.more.filter(a=>typeof a=="string").slice(0,av):[];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:Su(e.files),filesMore:r,more:i,components:ku(e.components),sounds:Eu(e.sounds),...wu(e.withheld,e.withheld_more),...Ru(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Wo)}:{}}}function Xc(e,t,n){const r=Lv(t);if(!r)return null;const i=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return Au(i,r,e)}function Tu(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Cu(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function $v(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const i=t[r];return n.path===i.path&&n.name===i.name&&n.kind===i.kind&&n.sizeBytes===i.sizeBytes&&n.mtime===i.mtime&&n.why===i.why&&(n.pinned??!1)===(i.pinned??!1)})}function Uv(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const i=t[r];return n.attachment===i.attachment&&n.title===i.title&&n.source===i.source&&n.mime===i.mime&&n.heightHint===i.heightHint})}function Fv(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const i=t[r];return n.attachment===i.attachment&&n.mime===i.mime&&n.title===i.title&&n.durationS===i.durationS&&n.origin===i.origin&&(n.path??"")===(i.path??"")&&(n.pinned??!1)===(i.pinned??!1)})}function Bv(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 Au(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&Qc(t.state)<Qc(e.state)))return null;const r=!e||t.version>e.version,i=t.files!==void 0?t.files:e?.files??[],s=t.components!==void 0?t.components:e?.components??[],a=t.sounds!==void 0?t.sounds:e?.sounds??[],c=t.withheld!==void 0?t.withheld:e?.withheld??[],l=t.withheldMore!==void 0?t.withheldMore:e?.withheldMore??0,d=t.filesMore!==void 0?t.filesMore:e?.filesMore??0,u=t.more!==void 0?t.more:e?.more??[],f=t.error??(r?"":e?.error??""),p=t.cause??(r?"":e?.cause??""),g=t.dismissed??(r?!1:e?.dismissed??!1),y=t.live!==void 0?t.live===!0?!0:Cu(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:zo(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:$v(i,e?.files??[])?e?.files??[]:i,filesMore:d,more:Gv(u,e?.more??[])?e?.more??[]:u,components:Uv(s,e?.components??[])?e?.components??[]:s,sounds:Fv(a,e?.sounds??[])?e?.sounds??[]:a,withheld:Bv(c,e?.withheld??[])?e?.withheld??[]:c,withheldMore:l,error:f,cause:p,model:t.model??(r?"":e?.model??""),attempts:t.attempts??(r?[]:e?.attempts??[]),detail:t.detail??(r?[]:e?.detail??[]),dismissed:g,live:y}}function Gv(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const $R=e=>e.kind===void 0||e.kind==="image",st={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function Ou(e){return e==="skipped"||e==="aborted"}function Jc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function qc(e,t,n,r){return Jc(n.args)??(r?.kind==="tool"?r.args:null)??Jc(e.argsByCall.get(t)?.arguments)}function Pu(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function ju(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 Xr(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ft(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!Pu(n)&&ju(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function en(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:nr;const i=[];for(const s of r){const a=ju(s);if(s.type==="document"||a===null&&!Pu(s))continue;const c={id:`${t}:${i.length}`,data:typeof s.data=="string"&&s.data?s.data:null,attachment:typeof s.attachment=="string"&&s.attachment?s.attachment:null,mimeType:typeof s.content_type=="string"&&s.content_type||typeof s.mime_type=="string"&&s.mime_type||"image/png"};a!==null&&(c.kind=a,c.width=Xr(s.width),c.height=Xr(s.height),c.sizeBytes=Xr(s.size_bytes),c.durationS=Xr(s.duration_s),c.name=typeof s.name=="string"&&s.name?s.name:null,c.sourceUrl=typeof s.source_url=="string"&&s.source_url?s.source_url:null),i.push(c)}return i.length===0?nr:n&&Zo(n,i)?n:i}const nr=[],io=[];function Mu(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:io;const i=[];for(const s of r){const a=typeof s.filename=="string"&&typeof s.mime_type=="string"&&typeof s.attachment=="string"&&s.type===void 0;s.type!=="document"&&!a||i.push({id:`${t}:doc:${i.length}`,attachment:typeof s.attachment=="string"&&s.attachment?s.attachment:null,filename:typeof s.filename=="string"&&s.filename?s.filename:s.name??"Attached file",mimeType:s.mime_type??"application/octet-stream",path:typeof s.path=="string"&&s.path?s.path:null,storedPath:typeof s.stored_path=="string"&&s.stored_path?s.stored_path:null,bytes:typeof s.bytes=="number"?s.bytes:0,...s.injection?{injection:s.injection}:{}})}return i.length===0?n?.length?n:io:n&&Hv(n,i)?n:i}function Hv(e,t){return e.length!==t.length?!1:e.every((n,r)=>{const i=t[r];return n.id===i.id&&n.attachment===i.attachment&&n.filename===i.filename&&n.mimeType===i.mimeType&&n.path===i.path&&n.storedPath===i.storedPath&&n.bytes===i.bytes&&n.injection===i.injection})}function el(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 Du(e,t,n){if(t.length===0)return e;if(e.length===0||Zo(e,t))return t;const r=el(e),i=el(t);return r!==i?r>i?e:t:n==="incoming"?e:t}function zv(e,t){return Du(e,t,"incoming")}function Zo(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 Qe(e){const t=new Map;return e.forEach((n,r)=>t.set(n.id,r)),t}function Wv(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const Rt=new Set;function Ko(e){return e.kind==="user"&&e.provisional===!0}function Nu(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{Ko(n)&&r<t&&(t=r)}),t}function Sr(e,t=Rt,n){if(n?.journalMode)return Ud(n,e).map(vu);const r=e.map((a,c)=>({record:a,position:c})),i=Nu(e),s=a=>Ko(a.record)||a.position>i&&!t.has(a.record.id);return r.sort((a,c)=>{const l=s(a),d=s(c);return l!==d?l?1:-1:l?a.position-c.position:a.record.ts!==c.record.ts?a.record.ts-c.record.ts:a.position-c.position}).map(a=>a.record)}function Zv(e,t,n){if(!n||t<=0)return Rt;let r=null;for(const i of e){if(!Ko(i)||!(t>i.ts))continue;let s=!1,a=!1;for(const c of e)if(c.ts>i.ts?s=!0:c.ts<i.ts&&Xo(c)&&(a=!0),s&&a)break;s&&a&&(r??=new Set,r.add(i.id))}return r??Rt}function Kv(e){const{provisional:t,...n}=e;return n}function so(e,t){const n=e,r=t,i=Object.keys(n);if(i.length!==Object.keys(r).length)return!1;for(const s of i)if(n[s]!==r[s]){if(s==="images"){const a=n[s],c=r[s];if(Array.isArray(a)&&Array.isArray(c)&&Zo(a,c))continue}if(s==="frame"){const a=n[s],c=r[s];if(a!==void 0&&c!==void 0&&a.epoch===c.epoch&&a.seq===c.seq)continue}if(s==="skill"){const a=n[s],c=r[s];if(a!==void 0&&c!==void 0&&Vv(a,c))continue}return!1}return!0}function Vv(e,t){return e.name===t.name&&e.token===t.token&&e.request===t.request&&e.purpose===t.purpose&&e.body===t.body}function be(e,t){const n=e.index.get(t.id);if(n!==void 0){const s=e.records[n];if(so(s,t))return e;const a=e.records.slice();if(a[n]=e.journalMode?{...t,...s.sourceEntryId?{sourceEntryId:t.sourceEntryId??s.sourceEntryId}:{},...s.sourceAdmissionAnchor&&!t.sourceAdmissionAnchor?{sourceAdmissionAnchor:s.sourceAdmissionAnchor}:{},...s.sourcePrecedes&&!t.sourcePrecedes?{sourcePrecedes:s.sourcePrecedes}:{},...s.journalGeneration?{journalGeneration:t.journalGeneration??s.journalGeneration,journalSeq:t.journalSeq??s.journalSeq}:{}}:t,!e.journalMode)return{...e,records:a};const c=Sr(a,Rt,e);return{...e,records:c,index:Qe(c)}}const r=e.journalMode?Sr([...e.records,t],Rt,e):[...e.records,t],i=Qe(r);return{...e,records:r,index:i}}function Vo(e,t){if(!e.records.some(t))return e;const n=e.records.filter(r=>!t(r));return{...e,records:n,index:Qe(n)}}function gs(e,t){const n=`tool:${t}`,r=e.index.get(n);if(r===void 0)return e;const i=e.records[r];return i.kind==="tool"&&(i.phase==="composing"||i.phase==="queued")?Vo(e,s=>s.id===n):e}function Yv(e,t,n){const r=e.index.get(`tool:${t}`);if(r===void 0)return e;const i=e.records[r];if(!(i.kind==="tool"&&(i.phase==="composing"||i.phase==="queued")))return e;const s=e.records.slice();return s[r]=n,{...e,records:s,index:Qe(s)}}const Qv=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function Lu(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 Xv(e,t){const n=dl(e),r=dl(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const $u="Context compacted",Jv=12e4;function Uu(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,i=new Set,s=new Map,a=(d,u)=>{r.add(u.id),i.add(d.id),s.set(u.id,d.text)},c=[...t].sort((d,u)=>d.ts-u.ts);for(const d of c){if(d.before===void 0)continue;const u=n.find(f=>!r.has(f.id)&&f.before===d.before);u&&a(d,u)}const l=[];for(const d of c)if(!i.has(d.id))for(const u of n){if(u.before!==void 0)continue;const f=Math.abs(u.ts-d.ts);f>Jv||l.push({live:d,durable:u,distance:f})}l.sort((d,u)=>d.distance-u.distance);for(const{live:d,durable:u}of l)i.has(d.id)||r.has(u.id)||a(d,u);return i.size===0?e:e.filter(d=>!i.has(d.id)).map(d=>{const u=s.get(d.id);return u===void 0||d.kind!=="compaction"&&d.kind!=="notice"||u===d.text?d:{...d,text:u}})}function qv(e){const t=Uu(e.records);return t===e.records?e:{...e,records:t,index:Qe(t)}}const ew="peer_message",tw="ask_response",nw="ask_timeout",Fu="Completed — runtime retired/disposed",Bu="Retired for an update — a turn was in flight and was cut; its earlier output is kept",rw="wake_prompt",iw="session_mcp_unavailable",sw=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),ow=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,tl=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,aw=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."]),Gu=/^\[[^\]]{1,32}\]\s*/,bi="Reason:",cw=/[\n;,(]| [—–] /,lw=/^\d+\.$/,dw=/[A-Z]/,uw=/\s/,rr=160;function ri(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",...gw(t,n)};let r;return e===iw?r=fw(t):sw.has(e)?r=hw(t.trim().replace(Gu,"")):r=_w(t),{level:"info",category:null,provider:null,...r}}function fw(e){const t=e.trim().replace(Gu,"").split(`
33
33
  `).map(c=>c.trim()),n=t[0]??"",r=t[1]?.startsWith(bi)?t[1]:null,i=t.slice(r?2:1).filter(Boolean).join(`
34
- `),s=(r?`${n} ${r}`:n).trim();if(s.length<=rr)return{headline:s,detail:i||null};const a=r===null?null:lw(r);if(a!==null){const c=(f,p)=>`${bi} ${[f,p].filter(Boolean).join(" ")}`,l=f=>[f,i].filter(Boolean).join(`
35
- `)||null,d=`${n} ${c(a.leading,a.clause)}`;if(d.length<=rr)return{headline:d,detail:l(a.rest)};const u=`${n} ${c("",a.clause)}`;if(u.length<=rr)return{headline:u,detail:l([a.leading,a.rest].filter(Boolean).join(" "))}}return{headline:Hu(s),detail:[r,i].filter(Boolean).join(`
36
- `)||null}}function lw(e){const t=e.startsWith(bi)?e.slice(bi.length):e,n=t.indexOf("/mcp");if(n<0)return null;const r=t.slice(n),i=r.search(iw),s=(i<0?r:r.slice(0,i)).trim();return s?{leading:t.slice(0,n).trim(),clause:s,rest:(i<0?"":r.slice(i)).trim()}:null}function dw(e){const t=e.trim(),n=uw(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 uw(e){for(let t=0;t<e.length-1;t++)if(".!?…".includes(e[t])&&aw.test(e[t+1])&&!sw.test(e.slice(0,t+1))&&ow.test(e.slice(t+1).trimStart()[0]??""))return t+1;return-1}function fw(e,t){const n=e.split(`
37
- `),r=n[0].match(nw),s=(typeof t.raw=="string"?t.raw.trim():"")||(r?n[0].slice(r[0].length):n[0]).trim()||e.trim(),a=n.slice(1).join(`
38
- `).trim();return{provider:(r?.[1]??"").trim()||null,category:(r?.[2]??"").trim()||null,headline:s,detail:a||null}}function Gu(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 i=n.body;if(typeof i!="string"||!i.trim())return null;const s={...n};for(const a of["expects_reply","steer"])typeof s[a]!="boolean"&&(s[a]=null);for(const a of["label","job_id"])a in s&&typeof s[a]!="string"&&delete s[a];return s}function pw(e){const t=hw(e),n=e.split(`
39
- `).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function hw(e){const t=e.split(`
40
- `).map(c=>c.trim()).filter(Boolean),n=c=>!tl.test(c)&&!mw(c),r=t.find(n),i=t.find(c=>tl.test(c)&&!c.startsWith("</"));let s=r??i??e.trim();const a=t.indexOf(s);if(a>=0&&s.endsWith(":")){const c=t.slice(a+1).find(n);c&&(s=`${s} ${c}`)}return Hu(s)}function mw(e){return rw.has(e.replace(/\s+/g," ").trim().toLowerCase())}function Hu(e){const t=e.trim();if(t.length<=rr)return t;const n=t.slice(0,rr),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const gw="harness_injected",zu=e=>!e||typeof e!="object"?!1:e[gw]===!0;function Wu(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function Zu(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const _w="ask";function nl(e,t){return t===!0&&String(e??"")===_w}function yw(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function Ku(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:Lu,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:r,text:a,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const a=n.details??{},c=Nu(String(a.detail??""));return{kind:"notice",id:e.id,ts:r,text:c.text,level:c.level}}if(e.type==="custom"&&n.custom_type==="completion_attention"){const a=n.details??{};if(typeof a.anchor=="string"){if(a.kind==="closed")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:Uu,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:Fu,level:"warning"};if(a.kind==="error"||a.kind==="interrupted")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:a.kind==="error"?"Stopped with an error":"Interrupted",level:a.kind==="error"?"error":"warning"}}}if(e.type==="custom"&&n.custom_type===ro){const a=n.details??{};return Jc(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(Zv.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=Xs(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&fs(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...ri(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(p=>f[p]===u[p])?f:u,images:en(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===Qv){const{body:u,sender:f}=tu(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&fs(t.sender,f)?t.sender:f}}if(a===qv){if(Py(c)||jy(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===Jv){const u=c.answers,f={};if(u&&typeof u=="object")for(const[y,m]of Object.entries(u))f[String(y)]=Array.isArray(m)?m.map(b=>String(b)):[];const p=c.questions,g=Array.isArray(p)?p.flatMap(y=>{if(!y||typeof y!="object")return[];const m=y;return[{id:String(m.id??""),question:String(m.question??""),secret:m.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(a===Xv){const u=Number(c.waited_s);return{kind:"ask_timeout",id:e.id,ts:r,askId:String(c.ask_id??""),waitedS:Number.isFinite(u)&&u>0?u:0,urgent:c.urgent===!0}}if(a===ro)return Jc(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?iv(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:a,text:d,...a==="team_bridge_message"?{bridgeReceipt:My(c)}:{},attribution:n.attribution??"system",...ri(a,d,c)}:null}const s=String(n.role??"");if(s==="user"){const a=Gu(n.provider_payload);if(a){const u=Xs({...a,text:ft(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&fs(f.sender,u.sender)&&(u.sender=f.sender);const p=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",...ri("hub_message",u.envelope||u.body,{...a,text:ft(n)}),receipt:f&&Object.keys(u).every(g=>f[g]===u[g])?f:u,images:en(n,e.id,p)}}}if(zu(n.provider_payload))return null;const c=ft(n);if(bu(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=Ci(c),d=ju(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:en(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(s==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=ft(n);return!c&&a.length>0?{kind:"assistant",id:e.id,ts:r,text:"",streaming:!1,stopReason:String(n.stop_reason??"toolUse"),callsTools:!0,error:!1}:{kind:"assistant",id:e.id,ts:r,text:c,complete:!0,streaming:!1,callsTools:a.length>0,stopReason:n.stop_reason??null,error:!!n.is_error}}if(s==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(Zu(l))return null;const d=Au(l.__fault);return{kind:"tool",id:`tool:${a}`,ts:r,toolCallId:a,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:ft(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:en(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...yu(c.details,t?.kind==="tool"?t:null),diff:_u(gu(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:du(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:cu(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:lu(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:to(c.details,t?.kind==="tool"?t.details??null:null)}}return null}function bw(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 vw=/^(?:tool|compaction|local):/;function ww(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)&&!vw.test(t.id))return t.id}return null}function Sw(e,t){const n=av(t);if(n)return e.records[e.index.get(n)??-1]}function Yo(e){const t=Ud(e,e.records);if(t===e.records)return e;const n=t.map(vu);return{...e,records:n,index:Qe(n)}}const kr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Vu(e,t,n,r){const i={...e,sourceEntryId:t,journalSeq:r,journalGeneration:n};if(e.kind==="user"&&(e.provisional===!0||e.local===!0)){const{provisional:s,local:a,...c}=i;return c}return i}function kw(e){const t=new Set,n=new Set;for(const r of e.records){const i=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof i!="string"||i.length<1||i.length>128||(t.add(i),r.journalGeneration===e.journalGeneration&&kr(r.journalSeq)&&n.add(i))}return{carried:t,admitted:n}}function Qo(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function rl(e,t){const n=new Set;for(const a of t)typeof a=="string"&&a.length>0&&a.length<=128&&n.add(a);if(n.size===0)return e;let r=!1;const i=e.records.map(a=>{const c=a.sourceEntryId??(a.kind==="tool"||a.kind==="supplement"?null:a.id);if(c===null||!n.has(c))return a;const l=Qo(a);return l!==a&&(r=!0),l});let s=r?{...e,records:i}:e;return s=Yu(s,n),s}function Yu(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=kw(e),i=e.orderRevision??0,s=e.journalBodyOwed;let a=null;const c=e.journalSourceVoid;let l=null;for(const d of t)typeof d!="string"||d.length<1||d.length>128||!n.has(d)||r.has(d)||(a||(a=new Map(s??[])),a.set(d,i),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return a?{...e,journalBodyOwed:a,...l?{journalSourceVoid:l}:{}}:e}function vi(e,t,n){const r=n&&e.journalSourceUnavailable===!0?{...e,journalSourceUnavailable:void 0}:e;if(t.length===0)return r;const i=r.journalBodyOwed;let s=null;const a=r.journalSourceVoid;let c=null;for(const l of t)i?.has(l)&&(s||(s=new Map(i)),s.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!s&&!c?r:{...r,...s?{journalBodyOwed:s}:{},...c?{journalSourceVoid:c}:{}}}function Pr(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function Qu(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function Ew(e,t,n){let r=On(e,t,t.entries.map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),!0,n);for(const s of t.entries)r=Mo(r,{...s.payload,id:s.id});const i=Pr(r,!1);return Yo(i.journalPeerSource===void 0&&!i.journalBodyOwed&&!i.journalSourceVoid&&i.journalSourceUnavailable===void 0?i:{...i,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function il(e,t,n){let r=On(e,t,(t.entries??[]).map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=Pr(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const s=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];s.length>0&&(r=Yu(r,s));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=vi(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=Qu(r,t),Yo(r)}function Iw(e,t,n,r){let i=On(e,t,[],!1,n,{peer:!0});i=Pr(i,!0);const s=i.journalBodyOwed,a=g=>r!==void 0&&(s?.get(g)??Number.NEGATIVE_INFINITY)>r,c=t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===i.journalGeneration,l=c?[...t.entries??[],...t.dependency_entries??[]]:[],d=[];let u=i.records,f=i.index;if(l.length>0){const g=new Map;for(const y of l){if(typeof y.id!="string"||y.id===""||a(y.id))continue;const m=`tool:${String(y.payload?.tool_call_id??"")}`,b=f.get(y.id)??f.get(m),_=b===void 0?void 0:u[b];if(!_)continue;let k=Ku(y,_);k&&(k={...k,sourceEntryId:y.id,..._.sourcePrecedes?{sourcePrecedes:_.sourcePrecedes}:{}},kr(y.journal_seq)?(k=Vu(k,y.id,t.journal_generation,y.journal_seq),d.push(y.id)):k=Qo(k),g.set(_.id,k))}g.size>0&&(u=u.map(y=>g.get(y.id)??y),f=Qe(u))}let p=u===i.records?i:{...i,records:u,index:f};if(c){p=vi(p,d,!1);const g=(t.source_missing_ids??[]).filter(y=>typeof y=="string"&&y.length>0&&y.length<=128&&!a(y));if(g.length>0){p=vi(p,g,!1);const y=new Set(p.journalSourceVoid??[]);for(const m of g)y.add(m);p={...p,journalSourceVoid:y}}}return p=Qu(p,t),Yo(p)}function Xr(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function ir(e,t,n={}){let r=e;const i=r,s=[],a=w=>Pr(vi(w,s,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=On(r,t,t.entries.map(w=>({id:w.id,journal_seq:w.journal_seq,role:w.payload?.role,tool_call_id:w.payload?.tool_call_id})),n.authoritative===!0,n.orderRead,{peer:n.peerSource===!0}),t.journal_generation&&t.journal_generation!==r.journalGeneration)return a(r);const c=n.peerSource===!0&&typeof t.journal_generation=="string"&&t.journal_generation.length>0&&t.journal_generation===r.journalGeneration;for(const w of t.entries)r=Mo(r,{...w.payload,id:w.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 w of t.entries){if(l&&!Hw(w,r.clearedAt))continue;const le=r.records[r.index.get(w.id)??-1]??r.records[r.index.get(`tool:${String(w.payload?.tool_call_id??"")}`)??-1]??Sw(r,w);let q=Ku(w,le);if(q&&r.journalMode&&(q={...q,sourceEntryId:w.id}),q&&r.journalMode){const Ce=le?.sourcePrecedes??(n.pagedBefore!==void 0&&!le?d:void 0);Ce!==void 0&&q.sourcePrecedes!==Ce&&(q={...q,sourcePrecedes:Ce})}q&&c&&kr(w.journal_seq)?(q=Vu(q,w.id,t.journal_generation,w.journal_seq),s.push(w.id)):q&&n.peerSource===!0&&(q=Qo(q)),!(q&&le&&yw(le,n.readWitness))&&q&&u.push(q)}let f=r.argsByCall,p=!1;for(const w of t.entries){const le=w.payload?.tool_calls;if(!Array.isArray(le))continue;const q=Math.round((w.ts??0)*1e3);for(const Ce of le)!Ce||typeof Ce.id!="string"||f.has(Ce.id)||(p||(f=new Map(f),p=!0),f.set(Ce.id,{...Ce,anchoredAt:q,anchorId:w.id}))}for(let w=0;w<u.length;w++){const le=u[w];if(le.kind!=="tool")continue;const q=f.get(le.toolCallId);if(!q)continue;const Ce=q.arguments??null;u[w]={...le,args:Ce,intent:typeof Ce?.i=="string"?Ce.i:null}}const g=p?r.records.map(w=>{if(w.kind!=="tool"||w.args)return w;const q=f.get(w.toolCallId)?.arguments??null;return q?{...w,args:q,intent:w.intent??(typeof q.i=="string"?q.i:null)}:w}):r.records,y=new Set(t.entries.map(w=>w.id)),m=n.peerSource===!0&&n.replace===!0?r.records.filter(w=>w.kind==="user"&&(w.provisional===!0||w.local===!0)&&!y.has(w.id)):[],b=n.replace?m.length>0?{...st,records:m,index:Qe(m)}:st:{...r,records:g},_=new Map(b.records.map(w=>[w.id,w]));let k=r!==i||n.replace||!n.replace&&g!==r.records;for(const w of u){const le=_.get(w.id);if(!le){k=!0,_.set(w.id,w);continue}if(le.kind==="tool"&&w.kind==="tool"){const q={...w,args:w.args??le.args,intent:w.intent??le.intent,images:Mu(w.images,le.images,"current")};so(le,q)||(k=!0,_.set(w.id,q));continue}so(le,w)||(k=!0,_.set(w.id,w))}const E=r.compacting&&t.entries.some(w=>r.index.has(w.id)||Math.round((w.ts??0)*1e3)<r.compactingSince?!1:w.type==="compaction"||w.type==="message"&&w.payload?.custom_type==="compaction_refused"),A=t.entries[0],$=A?Math.round((A.ts??0)*1e3):0,O=r.journalMode?Rt:Gv(b.records,$,n.statedByOwner!==!1);let C=b.oldestId,I=b.oldestTs,N=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(A&&(C=A.id,I=$),N=t.has_more):n.pagedBefore!==void 0?A?(C=A.id,I=$,N=t.has_more):N=!1:A&&(r.journalMode?(r.journalPositions?.get(A.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):$>0&&$<r.oldestTs)&&(C=A.id,I=$,N=t.has_more));const F=C!==r.oldestId||I!==r.oldestTs;if(!k&&!F&&r.hasMore===N&&!E&&O.size===0)return a(r);const se=O.size===0?[..._.values()]:[..._.values()].map(w=>O.has(w.id)?Hv(w):w),me=$u(Sr(se,n.statedByOwner===!1?Rt:new Set(u.map(w=>w.id)),r));return n.keepPaging?a({...r,records:me,index:Qe(me),argsByCall:f}):a({...r,records:me,index:Qe(me),oldestId:C,oldestTs:I,hasMore:N,argsByCall:f,compacting:E?!1:r.compacting,compactingSince:E?0:r.compactingSince})}const xw=/^(?:local|notice|retry|subagent|compaction):/;function Jo(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!xw.test(e.id)}}function Rw(e,t,n=Rt){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(i=>!(i.ts<t.ts&&Jo(i)&&!n.has(i.id)));return r.length===e.records.length?e:{...e,records:r,index:Qe(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const vt={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function _s(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function oo(e,t,n=Date.now(),r={}){let i=e;const s=t.message;if(t.type==="journal_order_ready"){const l=typeof t.journal_generation=="string"?t.journal_generation:void 0;if(i={...i,orderNeedsReconcile:!0,orderWantedGeneration:t.reconcile===!0?void 0:l,orderDemand:t.reconcile===!0?{}:{generation:l}},t.reconcile===!0)return i;const d=On(i,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=Sr(d.records,Rt,d);return d===i&&u===i.records?i:{...d,records:u,index:Qe(u)}}s&&(i=Mo(i,s));const a=r.frame,c=r.queuedAskEngine;switch(t.type){case"agent_start":{const l=Number(t.generation??i.generation+1);return l===i.generation?i:{...i,generation:l,compacting:!1,compactingSince:0}}case"compaction_start":return i.compacting?i:{...i,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??i.generation)<i.generation)return i;let d=i;for(const u of i.records)if(u.kind==="assistant"&&u.streaming&&(d=be(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=be(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=_s(s);if(s===void 0||l===null)return vt.idlessFrameRefused+=1,i;const d=i.records[i.index.get(l)??-1];if(s.role==="user"){const u=Gu(s.provider_payload);if(u){const m=ft(s),b=Xs({...u,text:m});if(b.body.trim()){const _=d?.kind==="user"&&d.provisional===!0;return be(i,{kind:"custom",id:l,ts:_?wi(i,n):n,customType:"hub_message",text:b.envelope,attribution:"user",...ri("hub_message",b.envelope||b.body,{...u}),receipt:b,images:en(s,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(zu(s.provider_payload))return i;const f=ft(s);if(bu(f))return i;const p=d?.kind==="user"&&d.provisional===!0,g=ju(s,l,d?.kind==="user"?d.documents:void 0),y=Ci(f);return be(i,{kind:"user",id:l,ts:p?wi(i,n):n,text:f,images:en(s,l,d?.kind==="user"?d.images:void 0),...g.length?{documents:g}:{},...p?{provisional:!0}:{},...y?{skill:y}:{}})}return s.role!=="assistant"||d?i:be(i,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=_s(s);if(s===void 0||l===null)return vt.idlessFrameRefused+=1,i;const d=i.index.get(l),u=String(t.delta??""),f=ft(s);if(d===void 0)return!f&&!u?i:be(i,{kind:"assistant",id:l,ts:n,text:f?f+u:u,streaming:!0,truncated:f===""?"prefix":void 0,...a?{frame:a}:{},stopReason:null,error:!1});const p=i.records[d];if(p.kind!=="assistant")return i;if(!p.streaming)return vt.settledAssistantUpdate+=1,i;if(r.seed!==!0&&a&&p.frame&&a.epoch===p.frame.epoch&&a.seq<=p.frame.seq)return vt.staleUpdateFrameDropped+=1,i;const g=Bv(p.frame,a);if(r.seed===!0&&!f)return!p.text&&!u?i:(vt.seededDeltaWithheld+=p.text?1:0,be(i,{...p,text:p.text||u,...g?{frame:g}:{},truncated:p.text?"interrupted":"prefix"}));let y;if(f){if(y=f+u,y.length<=p.text.length)return i}else{if(!u)return i;y=p.text+u}return be(i,{...p,text:y,...g?{frame:g}:{},truncated:f?void 0:p.truncated})}case"message_end":{const l=_s(s);if(s===void 0)return vt.idlessFrameRefused+=1,i;if(l===null){if(s.role!=="assistant")return vt.idlessFrameRefused+=1,i;let y;for(const _ of i.records)if(!(_.kind!=="assistant"||!_.streaming)){if(y!==void 0)return vt.idlessFrameRefused+=1,i;y=_}if(y===void 0)return vt.idlessFrameRefused+=1,i;const m=Array.isArray(s.tool_calls)?s.tool_calls:[],b={...y,streaming:!1,settledAt:y.settledAt??n,callsTools:m.length>0,...y.text||m.length===0?{complete:!0}:{}};return be(i,b)}if(s.role!=="assistant")return i;const d=i.index.get(l),u=ft(s),f=d===void 0?void 0:i.records[d],p=Array.isArray(s.tool_calls)?s.tool_calls:[],g={kind:"assistant",id:l,ts:d===void 0?n:i.records[d].ts,text:u,...u||p.length===0?{complete:!0}:{},streaming:!1,callsTools:p.length>0,settledAt:f?.kind==="assistant"&&f.settledAt!==void 0?f.settledAt:n,stopReason:s.stop_reason??null,error:!!s.is_error,...a?{frame:a}:{}};return be(i,g)}case"history_delta":{const d=(Array.isArray(t.messages)?t.messages:[]).filter(E=>String(E.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,p=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=i.journalPeerSource===!0||g,m=y&&u!==void 0&&u===i.journalGeneration,b=d.map(E=>String(E.id??"")).filter(E=>E.length>0&&E.length<=128),_={entries:d.map(E=>{const A=String(E.id??""),$=f?.[A],O=p?.[A];return{id:A,ts:m&&typeof O=="number"&&Number.isFinite(O)?O:n/1e3,type:"message",payload:{kind:E.custom_type?"custom":"message",...E},...m&&kr($)?{journal_seq:$}:{}}}),has_more:i.hasMore,...m?{journal_generation:u}:{}};let k=ir(i,_,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:y});if(y&&b.length>0)if(m){const E=b.filter(A=>!kr(f?.[A]));E.length>0&&(k=rl(k,E))}else k=rl(k,b),u!==void 0&&(k=On(k,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),k=Pr(k,!0));return k}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return i;const d=String(t.supersedes_tool_call_id??""),u=`tool:${l}`,f=i.records[i.index.get(u)??-1],p=d?i.records[i.index.get(`tool:${d}`)??-1]:void 0,g=f?.kind==="tool"?f:p?.kind==="tool"?p:void 0;if(g&&g.phase!=="composing"&&g.phase!=="queued")return d&&f?.kind==="tool"?gs(i,d):i;const m=String(t.not_run_reason??"").trim()||null,b=String(t.not_run_kind??"").trim()||null;if(nl(t.tool_name,c)&&!m&&!g)return d?gs(i,d):i;const _=Number(t.argument_bytes??0),k={kind:"tool",id:u,ts:g?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:m?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:_>0?_:g?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:nr,added:0,removed:0,diff:null,stopped:!1,notRunReason:m,notRunKind:m?b:null,neverSent:m!==null};return d&&p?.kind==="tool"&&f?.kind!=="tool"?Wv(i,d,k):be(d&&f?.kind==="tool"?gs(i,d):i,k)}case"tool_execution_start":{const l=String(t.tool_call_id??"");if(!l)return i;const d=`tool:${l}`,u=i.records[i.index.get(d)??-1];if(u&&u.kind==="tool"&&u.phase==="done"&&!u.notRunReason)return i;const f=qc(i,l,t,u),p=f&&!i.argsByCall.has(l)?new Map(i.argsByCall).set(l,{arguments:f,anchoredAt:xn(t)??n}):i.argsByCall,g=p===i.argsByCall?i:{...i,argsByCall:p};return nl(t.tool_name,c)&&!u?g:be(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:xn(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:nr,added:0,removed:0,diff:u?.kind==="tool"?u.diff:null,details:u?.kind==="tool"?u.details??null:null,stopped:!1})}case"tool_execution_update":{const l=String(t.tool_call_id??"");if(!l)return i;const d=`tool:${l}`,u=i.records[i.index.get(d)??-1];if(!u||u.kind!=="tool")return i;const f=t.partial_result??{},p=to(f.details,u.details);return p===(u.details??null)?i:be(i,{...u,details:p})}case"tool_execution_end":{const l=String(t.tool_call_id??"");if(!l)return i;const d=`tool:${l}`,u=i.records[i.index.get(d)??-1],f=t.result??{};if(Zu(f.details))return qu(i,d);const p=qc(i,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:nr,added:0,removed:0,diff:null,stopped:!1},y=p&&!i.argsByCall.has(l)?new Map(i.argsByCall).set(l,{arguments:p,anchoredAt:xn(t)??n}):i.argsByCall,m=y===i.argsByCall?i:{...i,argsByCall:y},b=r.userStoppedAt??null,_=!!(t.is_error??f.is_error),k=Au(f.details?.__fault),E=b!==null&&(typeof g.startedAt=="number"?g.startedAt<=b:_);return be(m,{...g,args:p,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:ft(f)||null,isError:E||k?!1:_,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:Fv(en(f,d,g.images),g.images),...yu(f.details,g),diff:_u(gu(f.details),g.diff),stopped:g.stopped||E||k,delivery:du(f.details,g.delivery,g.toolName),bridge:cu(g.toolName,f.details,g.bridge),bridgeLabel:lu(g.toolName,f.details,g.bridgeLabel),details:to(f.details,g.details)})}case"supplement_progress":{const l=jv(t);if(!l)return i;const d=zo(l.anchor),u=i.records[i.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,p=Cu(f,l,n);return p?be(i,p):i}case"notice":{const l=String(t.text??"");if(!l)return i;const d=`notice:${i.generation}:${l}`;return i.index.has(d)?i:be(i,{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:Nu(String(t.detail??"")),p=f?f.text:l&&d?Kv(l,d):Lu,g=`compaction:${i.generation}:${l}:${d}`,y=i.compacting?{...i,compacting:!1,compactingSince:0}:i;return y.index.has(g)?y:f?be(y,{kind:"notice",id:g,ts:n,text:p,level:f.level}):Yv(be(y,{kind:"compaction",id:g,ts:n,text:p,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:${i.generation}:${String(t.attempt??"")}`;return i.index.has(d)?i:be(i,{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=i.records[i.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?i:be(i,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return i}}function xn(e){return Kg(e.started_at_epoch)}function Xo(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function Tw(e){const t=Xo(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function Cw(e,t){const n=xn(e);if(n!==null)return n;const r=Xo(e);if(!r)return null;const i=t.argsByCall.get(r)?.anchoredAt;return typeof i=="number"&&Number.isFinite(i)&&i>0?i:null}function Aw(e,t){if(xn(e)!==null)return!1;const n=Xo(e);if(!n)return!1;const r=t.argsByCall.get(n)?.anchorId;if(typeof r!="string")return!1;const i=t.index.get(r);return i!==void 0&&i<=Du(t.records)}function qo(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 Oi(e){return e.type==="tool_execution_end"}function Ow(e,t,n=Date.now(),r=null){let i=e;t.streaming&&t.generation>i.generation&&(i={...i,generation:t.generation}),i.compacting&&(i={...i,compacting:!1,compactingSince:0});const s=t.streaming===!0,a=Wu(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let p=n;const g=Tw(f);if(g!==null&&!i.index.has(g)){const y=Cw(f,i);if(y!==null)p=y,c=!0,Aw(f,i)&&l.add(g);else if(Oi(f)||qo(f)||!s)continue}i=oo(i,f,p,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return i;const d=Sr(i.records,l,i);return{...i,records:d,index:Qe(d)}}function sl(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!Oi(r)&&!qo(r))continue;const i=String(r.tool_call_id??"");if(!i)continue;const s=xn(r);s!==null&&t.set(i,s)}return t}function Pw(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n;if(r.type!=="tool_call_compose")continue;const i=r.not_run_reason;if(typeof i=="string"&&i.trim().length>0)continue;const s=String(r.tool_call_id??"");s&&t.add(s)}return t}const jw=5e3;function Mw(e,t){const n=new Set(t),r=new Map;if(n.size===0)return r;for(const i of e){if(i.payload?.role!=="tool")continue;const s=i.payload.tool_call_id;if(typeof s!="string"||!n.has(s))continue;const a=i.ts;typeof a!="number"||!Number.isFinite(a)||r.set(s,Math.round(a*1e3))}return r}function Dw(e,t,n,r=new Map,i=new Set){const s=e[0]?.ts;if(typeof s!="number"||!Number.isFinite(s))return!1;let a=null;for(const l of t){const d=n.get(l);if(d===void 0){if(i.has(l))continue;return!1}(a===null||d<a)&&(a=d)}for(const l of r.values())(a===null||l<a)&&(a=l);return a===null?!1:Math.round(s*1e3)<=a-jw}function ol(e,t){const n=[];for(const r of e??[]){if(!r)continue;const i=r;if(!Oi(i)&&!qo(i))continue;const s=String(i.tool_call_id??"");!s||n.includes(s)||t.has(s)||n.push(s)}return n}function al(e,t,n,r){const i=[],s=new Set;for(const a of t)s.has(a)||(s.add(a),!n.has(a)&&((e.get(a)??0)>=r||i.push(a)));return i}const Nw=3.25,ao=100,ea=500;function cl(e){return e<=0?ao:Math.min(ea,ao+Math.ceil(Nw*e))}function ys(e,t){const n=[];if(t.size===0)return n;for(const r of e){const i=r.payload?.tool_calls;if(Array.isArray(i))for(const s of i)s&&typeof s.id=="string"&&t.has(s.id)&&n.push(s.id)}return n}function Lw(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function $w(e,t){const n=new Set(t);for(const s of e){const a=s.payload?.tool_calls;if(Array.isArray(a))for(const c of a)c&&typeof c.id=="string"&&n.add(c.id)}const r=[],i=new Set;for(const s of e){if(s.payload?.role!=="tool")continue;const a=s.payload.tool_call_id;typeof a!="string"||n.has(a)||i.has(a)||(i.add(a),r.push(a))}return r}function Uw(e,t){return e&&t===0}function Fw(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,i=r.not_run_reason,s=r.type==="tool_call_compose"&&typeof i=="string"&&i.trim().length>0;if(r.type!=="tool_execution_start"&&!Oi(r)&&!s)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function Ju(e,t,n){const r=new Set(e),i=[];for(const s of t)!r.has(s)&&!n.has(s)&&i.push(s);for(const s of e){if(n.has(s))return i;t.has(s)&&i.push(s)}return i}function Bw(e,t,n){return Ju(e,t,n).length}function ll(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=be(t,{...n,truncated:"interrupted"}));return t}function Gw(e,t=Date.now()){return e.records.length===0?e:{...st,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function Hw(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 dl(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function zw(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return Vo(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function wi(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function Xu(e,t,n,r,i=Date.now(),s=io){if(e.index.has(t))return e;const a=Ci(n);return be(e,{kind:"user",id:t,ts:wi(e,i),text:n,images:r,...s.length?{documents:s}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function qu(e,t){return Vo(e,n=>n.id===t)}let ul=0;function Ww(e,t,n,r=Date.now()){return ul+=1,be(e,{kind:"notice",id:`local:${r}:${ul}`,ts:wi(e,r),text:t,level:n})}function DR(e,t,n,r){const i=t?.anchor_id,s=t?.kind;return!i||s!=="error"&&s!=="interrupted"&&s!=="closed"&&s!=="retired"||n||e.index.has(i)||!t?.unseen&&!r?.has(i)?e:(r?.add(i),be(e,{kind:"notice",id:i,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:s==="closed"?Uu:s==="retired"?Fu:s==="error"?"Stopped with an error":"Interrupted",level:s==="closed"?"info":s==="retired"?"warning":s==="error"?"error":"warning"}))}const Zw="compacting context…";function NR(e){return typeof e=="string"&&e.trim()===Zw}const Kw=[1500,5e3];async function LR(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of Kw){await t(n);try{if(await e())return}catch{}}}function Vw(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 fl=new Set(["openrouter","radient","radient-key"]),Yw=new Set(["auto","openrouter/auto"]),Qw="Auto";function ef(e){return e.slice(e.lastIndexOf("/")+1)||e}function Jw(e,t){return e===t||e===ef(t)}function bs(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 $R(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():"",i=fl.has(t)||!r||Jw(r,e.model_id)||r.toLowerCase()==="unknown";return{name:fl.has(t)&&Yw.has(e.model_id)?Qw:i?ef(n):r,selector:n}}function UR(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function FR(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function BR(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function GR(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 HR(e){const t=e?.effort_displacement,n=t?.note;if(typeof n!="string"||!n.trim())return null;const r=new Map;for(const a of[e?.effective_model,e?.selected_model]){const c=typeof a?.display_name=="string"?a.display_name.trim():"";if(!a||!c||!a.provider||!a.model_id)continue;const l=`${a.provider}/${a.model_id}`;l!==t?.serving&&l!==t?.selected||r.set(l,c)}if(!r.size)return n.trim();const i=[...r.keys()].sort((a,c)=>c.length-a.length).map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),s=new RegExp(`(^|[\\s(])(${i.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(s,(a,c,l)=>`${c}${r.get(l)}`)}function zR(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function WR(e){const t=e.trim();return t&&({auto:"Auto",none:"None",minimal:"Minimal",low:h("ui.chat.session_status.effort_level.low"),medium:h("ui.chat.session_status.effort_level.medium"),high:h("ui.chat.session_status.effort_level.high"),xhigh:"xHigh",max:"Max"}[t.toLowerCase()]??t)}function tf(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 ZR(e,t){const n=(e??t)?.effective_model;return tf(n)?null:n?.model_id??null}function KR(e){if(!e)return null;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim().toLowerCase():"",n=Array.isArray(e.reasoning_efforts)?e.reasoning_efforts.filter(s=>typeof s=="string"):null,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",i=tf(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(", ")}.`}:i?{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 VR(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 Xw(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=Wn(n.provider);if(!a)return null;const c=Wn(e?.selected_model?.provider);if(c&&c!==a)return null;const d=["local","pending","eligible_borrow_unverified","effective_borrow","expired","withdrawn","owner_unavailable","device_bound","absent"].includes(n.effective_state)?n.effective_state:"pending";return d==="local"?null:{...d==="absent"?{connectHere:t==="local"}:{},provider:a,label:Wn(n.label)||a,effectiveState:d,owner:Wn(n.owner_label)||Wn(n.owner_device)||"the owner device",observedAt:vs(n.observed_at),lastGrantAt:vs(n.last_grant_at),lastGrantExpiresAt:vs(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 i=e?.effective_model?.provider;if(i&&i!==r)return null;const s=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:s,state:n.state}:{provider:r,label:s}}function YR(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function QR(e){return e&&e.draft!==!0?Xw(e.frontend,e.servingLocality):null}function Wn(e){return typeof e=="string"?e.trim():""}function vs(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function ws(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function JR(e){const{label:t,effectiveState:n}=e,r=e.owner||"the owner device",i={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."]},s=e.state==="temporarily_unavailable",[a,c]=n?i[n]:[s?h("ui.chat.session_status.temporarily_unavailable",{label:t}):h("ui.chat.session_status.not_signed_in",{label:t}),s?h("ui.chat.session_status.temporarily_unavailable_description"):h("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];return n&&e.observedAt!==void 0&&l.push(`Last checked: ${ws(e.observedAt)}.`),n&&e.lastGrantAt!==void 0&&l.push(`Last resolved: ${ws(e.lastGrantAt)}.`),n&&e.lastGrantExpiresAt!==void 0&&l.push(`Recorded grant expiry: ${ws(e.lastGrantExpiresAt)}.`),n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push("History only; not permission to reuse access."),{title:a,description:c,history:l.join(" "),tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!s,canSwitchModel:n!=="effective_borrow"}}function XR(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function qR(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function eT(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function qw(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function e0(e,t){return!!e.streams[t]}function nf(e,t){return e.attached[t]?.turns.at(-1)}function tT(e,t){const n=nf(e,t);return n?e.streams[n.asideId]:void 0}function nT(e,t){const n=e.attached[t]?.turns??[];for(let r=n.length-1;r>=0;r-=1){const i=n[r];if(i&&e.streams[i.asideId]?.settled)return i.asideId}}function t0(){return{text:"",streaming:!0,settled:!1,error:null}}function n0(e){return{text:e,streaming:!1,settled:!0,error:null}}function r0(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const i0=Ar(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(i=>({streams:{...i.streams,[n]:t0()},attached:{...i.attached,[t]:{turns:[...i.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const i=qw(r.streams[t],n);return i?{streams:{...r.streams,[t]:i}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:n0(n)}}:r),failAside:(t,n)=>e(r=>e0(r,t)?{streams:{...r.streams,[t]:r0(r.streams[t],n)}}:r),setAsideNotice:(t,n)=>e(r=>{const i=r.attached[t];return i?{attached:{...r.attached,[t]:{...i,notice:n}}}:r}),queueAdoption:(t,n,r)=>e(i=>{const s=i.attached[t];return s?{attached:{...i.attached,[t]:{...s,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:i}),unqueueAdoption:(t,n,r)=>e(i=>{const s=i.attached[t];if(s?.queued?.asideId!==n)return i;const{queued:a,...c}=s;return{attached:{...i.attached,[t]:{...c,notice:r}}}}),detachAside:t=>e(n=>{const r=n.attached[t],i={...n.attached};if(delete i[t],!r)return{attached:i};const s={...n.streams};for(const a of r.turns)delete s[a.asideId];return{streams:s,attached:i}})}));function rT(e,t){return nf(e,t)?.asideId}const s0=4*1024*1024,pl=1024*1024,pt=new Map;function hl(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function o0(e){const t=e.slice(-200),n=hl(t);if(n<=pl)return{records:t,bytes:n};let r=0,i=t.length,s=0;for(;i-r>1;){const a=Math.floor((r+i)/2),c=hl(t.slice(a));c>pl?r=a:(i=a,s=c)}return{records:t.slice(i),bytes:s}}function a0(e,t){const{records:n,bytes:r}=o0(zw(t.transcript).records);if(n.length===0){pt.delete(e);return}const i={...t.transcript,records:n,index:new Map(n.map((a,c)=>[a.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},s={transcript:i,savedAt:Date.now(),bytes:r,owedLabels:ml(n,t.owedLabels),markLabels:ml(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>i.index.has(a)))};pt.delete(e),pt.set(e,s),l0()}function ml(e,t){if(!t||t.size===0)return gl;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:gl}const gl=new Set;function rf(e){const t=pt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function c0(e){pt.delete(e)}function l0(){let e=0;for(const t of pt.values())e+=t.bytes;for(;e>s0&&pt.size>0;){const t=pt.keys().next().value;if(t===void 0)break;const n=pt.get(t);pt.delete(t),e-=n?.bytes??0}}const d0=8,u0=128,sf=new Set,f0="",St=new Map,ta=e=>e??f0;function iT(e){return St.get(ta(e))??sf}function sT(e,t,n){const r=ta(e),i=St.get(r)??new Set,s=new Set(i);if(n)for(s.delete(t),s.add(t);s.size>u0;){const a=s.values().next().value;if(a===void 0)break;s.delete(a)}else s.delete(t);for(St.delete(r),s.size>0&&St.set(r,s);St.size>d0;){const a=St.keys().next().value;if(a===void 0)break;St.delete(a)}return St.get(r)??sf}function p0(e){St.delete(ta(e))}const h0=128,Si=4096,Ss=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),_l=e=>e.startsWith("qg:")&&e.length>3;function oT(e,t,n=null,r=[]){const i=new Map,s=new Map;for(let c=0;c<e.length;c+=1){const l=e[c];for(let d=0;d<l.segmentIds.length;d+=1){const u=l.segmentIds[d];if(i.has(u))return Ss("duplicate-prior-id");if(i.size===Si)return Ss("prior-id-limit");i.set(u,{ordinal:c,order:d})}l.eligible!==!1&&_l(l.key)&&t.has(l.key)&&s.size<h0&&s.set(c,l.key)}for(const c of r)if(!i.has(c)){if(i.size===Si)return Ss("prior-id-limit");i.set(c,{ordinal:-1,order:-1})}const a=n===null?void 0:i.get(n);if(a!==void 0&&a.ordinal>=0){const c=e[a.ordinal];c.eligible!==!1&&_l(c.key)&&s.set(a.ordinal,c.key)}return{complete:!0,owners:i,keys:s,reason:null}}function aT(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>Si)return r("prior-id-limit");const i=new Set,s=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,p,g)=>{const y=a.get(f);y===void 0?a.set(f,{current:p,many:!1,lastOrder:g,reordered:!1,outside:!1}):(y.current!==p&&(y.many=!0),g<=y.lastOrder&&(y.reordered=!0),y.lastOrder=g)};for(let f=0;f<t.length;f+=1){const p=t[f];let g=null,y=!1;for(const b of p.segmentIds){if(s!==null){if(s.has(b))return r("duplicate-current-id");if(s.size===Si)return r("current-uniqueness-unproved");s.add(b)}const _=e.owners.get(b);if(_!==void 0){if(i.has(b))return r("duplicate-current-id");i.add(b),l(_.ordinal,f,_.order),g===null?g=_.ordinal:g!==_.ordinal&&(y=!0)}}if(p.eligible===!1||y||g===null||g<0)continue;const m=e.keys.get(g);m!==void 0&&c.set(f,{owner:g,key:m})}for(const f of n.outsideCurrentIds??[]){const p=e.owners.get(f);if(p===void 0||i.has(f))continue;const g=a.get(p.ordinal);g!==void 0&&(g.outside=!0)}for(const[f,p]of c){const g=a.get(p.owner),y=p.key.slice(3);(g===void 0||g.many||g.reordered||g.outside||!i.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 p=c.get(f)?.key??t[f].key;if(d.has(p)){if(u.has(p))return r("key-collision");u.add(p)}}return{episodes:t.map((f,p)=>{const g=c.get(p);return g===void 0?f:{...f,key:g.key}}),reason:null}}const m0=8,g0="",qt=new Map,na=e=>e??g0;function cT(e){return qt.get(na(e))??null}function lT(e,t){const n=na(e);for(qt.delete(n),qt.set(n,t);qt.size>m0;){const r=qt.keys().next().value;if(r===void 0)break;qt.delete(r)}}function _0(e){qt.delete(na(e))}function y0(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const i=n.getTranscript().orderRevision??0,s=()=>(n.getTranscript().orderRevision??0)===i;try{let a=r,c=await n.readPage(a);if(!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing){const u=ww(n.getTranscript()),f=u!==null&&u!==a?u:bw(c,a);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(a=f,c=await n.readPage(a),!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing)return{kind:"failed",reason:"cursor-missing"}}let l=n.getTranscript();const d=n.commit(u=>(l=u,(u.orderRevision??0)!==i?u:ir(u,c,{...u.oldestId===r?{pagedBefore:a}:{},...n.peerSource?.()===!0?{peerSource:!0}:{}})));return(d.orderRevision??0)!==i||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 i=r.getTranscript();if(!i.hasMore||!i.oldestId)return Promise.resolve({kind:"nothing-to-load"});const s={key:n,promise:t(r,i.oldestId)};e=s;const a=()=>{e===s&&(e=null)};return s.promise.then(a,a),s.promise}}}const b0={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"},v0={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function ra(e){return{kind:e,statement:h(b0[e]),action:v0[e]}}function yl(e){return ra(Qg(e))}const w0=()=>ra("historyUnreadable"),S0=new Set(["subagent_start","subagent_progress","subagent_end"]),k0=(e,t)=>({...e,[t]:(e[t]??0)+1}),E0=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=of(n);r&&(t[r]=(t[r]??0)+1)}return t},of=e=>{if(!e||typeof e!="object")return null;const t=e;return S0.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},I0=(e,t)=>{const n=of(t);return n?k0(e,n):e};function bl(e,t,n){if(!n||!e)return{};const r=e.context_tokens;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return{};const i=t.context_tokens;return typeof i=="number"&&Number.isFinite(i)&&i>=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 x0(e){for(const t of e)t.type==="aside_delta"&&i0.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function R0(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const Qt=new Set,Xn=new Set;function T0(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 C0=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),A0=15e3,co=[500,1e3,2e3,4e3,8e3,8e3],O0=co.length,P0=2e4,j0=1e4,M0=1e4;function vl(e){const t=Math.max(1,Math.min(e,co.length));return co[t-1]??8e3}const D0=3,N0=250,L0=32*1024,wl=512,Sl=new Set(["turn_end","agent_end"]),kl=2,$0=500,El=ea,U0=6,ks=Ed("sessions.history"),F0=2e3,Il={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},rn=new Map,ii=new Map,B0=8,G0=2048,xl=1024,H0=1024,z0="",Vt=new Map;function Rl(e){const t=e??z0,n=Vt.get(t);if(n)return Vt.delete(t),Vt.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(Vt.set(t,r);Vt.size>B0;){const i=Vt.keys().next().value;if(i===void 0||i===t)break;Vt.delete(i)}return r}function Es(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function Is(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function W0(e,t){return ii.set(e,t),()=>{ii.get(e)===t&&ii.delete(e)}}function dT(e){const t=ii.get(e);return t?(t(),!0):!1}const Te=new Map,Z0=4,K0=16;function af(e,t){e(n=>Xu(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function V0(e,t,n){const r=e.index.get(t),i=r===void 0?void 0:e.records[r];if(r===void 0||!i||i.kind!=="user"||!i.local||i.text===n)return e;const s=e.records.slice(),{skill:a,...c}=i,l=Ci(n);return s[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:s}}function lo(e,t){let n=Te.get(e);if(!n){if(Te.size>=K0){const s=Te.keys().next();s.done||Te.delete(s.value)}n=new Map,Te.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>Z0;){const s=n.keys().next();if(s.done)break;n.delete(s.value)}const i=rn.get(e);i&&af(i,r)}function uT(e){if(!e)return null;const t=Te.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function uo(e,t){const n=Te.get(e);n&&(n.delete(t),n.size===0&&Te.delete(e))}function fo(e,t){const n=Te.get(e)?.get(t);n&&(n.settled=!0)}function Tl(e,t){return e?Te.get(e)?.has(t)===!0:!1}function fT(e){return e?(Te.get(e)?.size??0)>0:!1}function Y0(e,t,n){const r=Te.get(e)?.get(t);if(!r)return;r.text=n;const i=rn.get(e);i&&i(s=>V0(s,t,n))}function Q0(e,t){if(e===t)return;const n=Te.get(e);if(!n)return;Te.delete(e);const r=Te.get(t)??new Map;for(const[i,s]of n)s.identity=t,r.set(i,s);Te.set(t,r)}function qr(e){Te.delete(e)}function J0(e,t){const n=Te.get(e);if(n)for(const r of[...n.keys()]){const i=t.index.get(r),s=i===void 0?void 0:t.records[i];s?.kind==="user"&&s.local!==!0&&uo(e,r)}}function X0(e,t){rn.set(e,t);const n=Te.get(e);if(n)for(const r of n.values())af(t,r);return()=>{rn.get(e)===t&&rn.delete(e)}}function q0(e,t){const n=Te.get(e);if(!n)return t;let r=t;for(const i of n.values())r=Xu(r,i.id,i.text,i.images,void 0,i.documents);return r}function eS(e,t,n){return e===t?!0:!n}function tS(e,t){const n=rn.get(e);if(!n)return uo(e,t),"queued";let r="queued";return n(i=>{const s=i.records[i.index.get(t)??-1];return!s||s.kind!=="user"?i:s.local?(r="retracted",qu(i,t)):(r="owner",i)}),uo(e,t),r}function cf(e,t){const n=rn.get(e);if(!n)return"unseen";let r="unseen";return n(i=>{const s=i.records[i.index.get(t)??-1];return!s||s.kind!=="user"||(r=s.local?"local":"owner"),i}),r}function nS(e){const t=rf(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:st,stale:!1,owedLabels:Qt,markLabels:Xn}}function rS(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function xs(e,t){if(e.size!==0)for(const n of t)e.delete(it(n))}function ei(e,t){for(const n of t)e.add(it(n))}const Cl=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function pT(e,t,n=!0,r=e,i={}){const s=i.openFrame===!0,a=i.journalOrder===!0,c=S.useRef(a);c.current=a;const l=S.useRef(s);l.current=s;const d=i.peerJournalSource===!0,u=S.useRef(d);u.current=d;const f=S.useRef(null),p=S.useRef(0),g=S.useRef(0),y=S.useRef(0),m=S.useRef(null),b=S.useRef(null),_=S.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const P=Ke.getState();return QS(P.sessions,P.placementFacts,e)},[e]),k=S.useCallback(()=>{const P=f.current;return _()&&P!==null&&P.sessionId===e&&P.peer},[_,e]),E=S.useCallback(()=>{const P=f.current;return P!==null&&P.sessionId===e&&P.peer},[e]),[A,$]=S.useState(()=>{const P=t&&e?nS(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?q0(r,P?.transcript??st):st,stale:P?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:P?.owedLabels??Qt,labelMarked:P?.markLabels??Xn,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),O=S.useRef(A),C=S.useCallback(P=>{const z=P(O.current);return z===O.current||(O.current=z,$(z)),z},[]);S.useEffect(()=>up(()=>{C(P=>{const{failure:z}=P;if(!z?.kind)return P;const ee=ra(z.kind);return ee.statement===z.statement&&ee.action===z.action?P:{...P,failure:ee}})}),[C]);const I=S.useRef(e),N=S.useRef([]),F=S.useRef(st.index),se=S.useRef(new Set),me=S.useRef(new Set),w=S.useRef(Rl(e)),le=S.useRef(new Set),q=S.useRef(null),Ce=S.useRef({}),Bi=S.useRef(null),Gi=S.useRef(null),Hi=S.useRef(null),Dn=S.useRef(0),et=S.useRef(0),Ea=S.useRef(0);S.useEffect(()=>{if(!e||!t)return;const P=++et.current,z=new WeakMap;let ee=null;const ve=(K,V)=>{const ie=z.get(K);if(ie===void 0||Je(V)===ie.revision)return!1;const Y=K.payload.history.journal_generation;return!(typeof Y=="string"&&Y.length>0&&Y===V.journalGeneration)};let Z=null,Fe=!1,Ee=0,ae=0,Oe=0,D=0,pe=0,ge=0,he=0,Ie=!1;const Se=()=>{ge&&(window.clearTimeout(ge),ge=0)},Lr=K=>{for(const V of K)w.current.attempts.set(V,(w.current.attempts.get(V)??0)+1)},Ki=K=>{C(V=>{const ie=new Set;for(const _e of V.labelPending)V.labelPending.has(_e)&&(Is(w.current,V.transcript.argsByCall,_e,Es(V))||ie.add(_e));let Y=null;for(const _e of V.labelMarked)Is(w.current,V.transcript.argsByCall,_e,Es(V))||(Y=Y??new Set(V.labelMarked),Y.delete(_e));if(ie.size===0&&!Y)return V;const de=new Set(V.labelPending);for(const _e of ie)de.delete(_e);return{...V,labelPending:de.size?de:Qt,labelMarked:Y&&Y.size===0?Xn:Y??V.labelMarked}})},np=K=>{C(V=>{let ie=null,Y=null;for(const de of K)V.labelPending.has(de)&&(ie=ie??new Set(V.labelPending),ie.delete(de),Y=Y??new Set(V.labelMarked),Y.add(de));return!ie||!Y?V:{...V,labelPending:ie.size?ie:Qt,labelMarked:Y}})},$r=async(K,V,ie=Il,Y=1,de,_e=V,oe=null)=>{Dn.current+=1,et.current===K&&C(Ae=>Ae.historyReadPending?Ae:{...Ae,historyReadPending:!0});for(const Ae of ie.targets)w.current.inFlight.add(Ae),le.current.add(Ae);let Ne=!1;try{Ne=await rp(K,V,_e,oe,ie,Y,de)}finally{if(Dn.current=Math.max(0,Dn.current-1),Dn.current===0&&C(Ae=>Ae.historyReadPending?{...Ae,historyReadPending:!1}:Ae),!Ne){for(const Ae of ie.targets)w.current.inFlight.delete(Ae);w.current.refused&&np(ie.targets),Ki()}}},rp=async(K,V,ie,Y,de,_e,oe)=>{const Ne={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:ie.size===0},Ae=O.current.transcript.viewEpoch,Pe=await ip(K,V,ie,Y,de,_e,Ne,oe);if(Pe||et.current!==K||Ne.reachedHeld||O.current.transcript.viewEpoch!==Ae)return Pe;const He=V!==ie&&[...V].some(We=>ie.has(We));if(He&&Ne.joined)return Pe;let ze;if(Ne.oldest){if(!Ne.hasMore)return Pe;ze={id:Ne.oldest.id,ts:Math.round((Ne.oldest.ts??0)*1e3)}}else{if(He||!Y)return Pe;ze=Y}if(!ze)return Pe;const At=C(We=>{const nt=Rw(We.transcript,ze,Ne.keys);return nt===We.transcript?We:{...We,transcript:nt}});return F.current=At.transcript.index,Pe},ip=async(K,V,ie,Y,de,_e,oe,Ne)=>{const Ae=O.current.transcript.viewEpoch,Pe=()=>O.current.transcript.viewEpoch!==Ae,He=new Set;let ze,At=0,We=0,nt=!1,Ot=ie.size===0,fn=!1;const Ur=O.current.cold,Pt=q.current,Zt=Pt?{epoch:Pt.epoch,seq:Pt.seq}:null,bt=new Set(de.found),pn=()=>Bw(de.order,de.targets,bt),T=()=>Ju(de.order,de.targets,bt),x=()=>{const G=new Map;for(const Ze of ue){if(bt.has(Ze))continue;const rt=Be.get(Ze);rt!==void 0&&G.set(Ze,rt)}return G},ce=new Set(de.every);for(const G of bt)ce.add(G);const ue=new Set,Be=new Map;let B=1;const jt=de.targets.size>0;let ne=Math.max(cl(pn()),jt?w.current.depth:0),xe=0;for(;At<El&&We<U0;){We+=1;let G;const Ze=Qs(O.current.transcript),rt=Ze.revision;try{G=await Re({op:"sessions.history",sessionId:e,...ze?{beforeId:ze}:{},limit:Math.min(ne,El-At),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(O.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}})}catch{if(Pe())return!1;if(O.current.transcript.records.length>0){if(xe++>0)return w.current.refused=!0,!1;continue}return _e<D0?(pe=window.setTimeout(()=>{if(pe=0,et.current!==K||Pe()){Ki();return}$r(K,V,de,_e+1,Ne,ie,Y)},vl(_e)),!0):(C(fe=>({...fe,status:"unavailable",failure:w0(),heldFrontend:null,...fe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{Ki()}if(et.current!==K||Pe())return!1;if(Je(O.current.transcript)!==rt){if(!O.current.hydrated)continue;return!1}w.current.refused=!1;const Kt=G.entries[0];At+=G.entries.length,Ne?.(G.entries.length),xs(se.current,G.entries),ei(me.current,G.entries),C(fe=>{if(Je(fe.transcript)!==rt)return fe;const dt=ir(fe.transcript,G,{authoritative:!0,orderRead:Ze,peerSource:E(),readWitness:Zt}),hn=ys(G.entries,ce),Yi=new Set(fe.labelPending);for(const cp of hn)Yi.delete(cp);return{...fe,hydrated:fe.hydrated||G.entries.length>0||!Ur,labelPending:Yi.size?Yi:Qt,labelMarked:T0(fe.labelMarked,hn),transcript:dt}}),e&&ze===void 0&&Ke.getState().resolveHeldFromServer(e,G.entries,!G.cursor_missing);const ap=pn();for(const fe of ys(G.entries,ce))bt.add(fe),ce.add(fe);if(Lw(G.entries)&&(fn=!0),jt){const fe=$w(G.entries,ce);for(const dt of fe)ue.add(dt),ce.add(dt);for(const[dt,hn]of Mw(G.entries,fe))Be.set(dt,hn);for(const dt of[...ue])bt.has(dt)&&ue.delete(dt);ue.size>0&&B--<=0&&ue.clear()}nt=nt||V.size===0||G.entries.some(fe=>V.has(it(fe))||He.has(fe.id)),Ot=Ot||G.entries.some(fe=>ie.has(it(fe)));for(const fe of G.entries)He.add(fe.id);for(const fe of G.entries)oe.keys.add(it(fe));Kt&&(oe.oldest=Kt),oe.hasMore=G.has_more,oe.joined=nt,oe.reachedHeld=Ot;const Vi=pn()+ue.size;jt&&pn()<ap&&(w.current.depth=Math.min(ea,Math.max(w.current.depth,At)));let Ua=!1;if(jt){const fe=T();Ua=Dw(G.entries,fe,de.starts,x(),new Set(fe.filter(hn=>de.waiting.has(hn))))||fn}if(Uw(nt&&Ot,Ua?0:Vi)||!Kt||!G.has_more)return!1;ze=Kt.id,ne=Vi>0?cl(Vi):ao}return!1},Da=()=>{if(Ee&&cancelAnimationFrame(Ee),ae&&clearTimeout(ae),Ee=0,ae=0,et.current!==P)return;const K=N.current;if(N.current=[],K.length===0)return;const V=new Set,ie=new Map;for(const T of se.current)O.current.transcript.index.has(T)||se.current.delete(T);for(const T of me.current)O.current.transcript.index.has(T)||me.current.delete(T);for(const T of O.current.transcript.records)Jo(T)&&!se.current.has(T.id)&&(V.add(T.id),ie.set(T.id,me.current.has(T.id)?T.ts:null));let Y=null;for(const T of K){if(T.type!=="snapshot")continue;const x=T.payload.history,ce=x.entries[0];if(!ce||!x.has_more)continue;const ue=Math.round((ce.ts??0)*1e3);ue>0&&(!Y||ue<Y.ts)&&(Y={id:ce.id,ts:ue})}x0(K);const de=T=>{const x=T.payload.history.entries,ce=x.at(-1);if(!ce)return!1;if(rS(T.payload)){if(V.size===0)return!0;const ue=new Set;for(const Be of x)ue.add(it(Be));return x.some(Be=>V.has(it(Be)))?!0:T_(T.payload.history,ie,ue)}return ce.id===T.payload.frontend.snapshot.history_cursor?!1:V.has(it(ce))},_e=T=>T!=null&&F.current.has(T);let oe=!1;const Ne=K.some(T=>T.type==="attention"?!_e(T.payload.anchor_id):T.type==="snapshot"&&!de(T)),Ae=O.current.cold&&!O.current.hydrated&&K.some(T=>T.type==="snapshot"||T.type==="frontend.replace"||T.type==="frontend.update"?T.payload.cold===!1:!1),Pe=new Set(O.current.transcript.argsByCall.keys()),He=[],ze=new Set;for(const T of K){if(T.type!=="snapshot")continue;const x=ve(T,O.current.transcript);x||ei(me.current,T.payload.history.entries);for(const ce of T.payload.history.entries){x||ze.add(it(ce));const ue=ce.payload?.tool_calls;if(Array.isArray(ue))for(const Be of ue)Be&&typeof Be.id=="string"&&Pe.add(Be.id)}for(const ce of T.payload.frontend.snapshot.live_events??[]){const ue=ce.message;!x&&typeof ue?.id=="string"&&ze.add(ue.id)}He.push(...T.payload.frontend.snapshot.live_events??[])}const At=K.some(T=>T.type==="event"&&Sl.has(String(T.payload.type??""))),We=al(w.current.attempts,ol(He,Pe),Pe,kl),nt=At?al(w.current.attempts,[...w.current.attempts.keys(),...w.current.settled],Pe,kl):[],Ot=[];for(const T of K){if(T.type!=="event")continue;const x=T.payload;String(x.type??"")==="tool_execution_end"&&String(x.tool_call_id??"")&&Ot.push(x)}const fn=[];for(const T of Ot){const x=String(T.tool_call_id??"");Pe.has(x)||w.current.settled.has(x)||fn.push(x)}for(const T of fn)w.current.settled.add(T);for(;w.current.settled.size>wl;){const T=w.current.settled.values().next().value;if(T===void 0)break;w.current.settled.delete(T)}for(const[T,x]of sl(Ot))w.current.starts.set(T,x);for(;w.current.starts.size>xl;){const T=w.current.starts.keys().next().value;if(T===void 0)break;w.current.starts.delete(T)}const Ur=w.current.settleRows<$0?fn:[],Pt=[...new Set([...We,...nt,...Ur])],Zt=Pt.filter(T=>!w.current.painted.has(T));if(He.length>0){w.current.order=ol(He,new Set);for(const[T,x]of sl(He))w.current.starts.set(T,x);for(;w.current.starts.size>xl;){const T=w.current.starts.keys().next().value;if(T===void 0)break;w.current.starts.delete(T)}for(const T of Pw(He))w.current.waiting.add(T);for(const T of Fw(He))w.current.waiting.delete(T);for(;w.current.waiting.size>H0;){const T=w.current.waiting.values().next().value;if(T===void 0)break;w.current.waiting.delete(T)}}for(const T of[...w.current.attempts.keys()])Pe.has(T)&&w.current.attempts.delete(T);for(Lr([...We,...nt]);w.current.attempts.size>wl;){const T=w.current.attempts.keys().next().value;if(T===void 0)break;w.current.attempts.delete(T)}if(performance.mark("lop:transcript:flush:start"),C(T=>{let x={...T},ce=x.frontend!==null;oe=!1;let ue=null;const Be=Date.now();for(const B of K){if(B.type==="heartbeat")continue;if(B.type==="gap"){ee=null,x={...x,frontend:null,heldFrontend:x.frontend??x.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:ll(x.transcript)},ce=!1;continue}if(B.type==="open")ee=null;else if("seq"in B){const ne={epoch:B.epoch,seq:B.seq},xe=Cl(B);if(!xe&&!Vg(ee,ne,{allowEqual:B.type==="snapshot"}))continue;xe||(ee=ne)}const jt=q.current;if((B.type==="open"||"seq"in B)&&!Cl(B)&&(q.current={epoch:B.epoch,seq:B.seq},x={...x,receipt:q.current}),B.type==="open"){if(x={...x,subscriptionId:B.payload.subscription_id},B.payload.gap){const ne=x.frontend??x.heldFrontend;x={...x,frontend:null,heldFrontend:ne,history:null,transcript:ll(x.transcript)},ne&&x.status==="live"&&(x={...x,status:"reconnecting"}),ce=!1}continue}if(!ce){if(B.type==="event"&&(ue=oo(ue??x.transcript,B.payload,Be,{frame:{epoch:B.epoch,seq:B.seq}})),B.type==="snapshot"){const ne=z.get(B),xe=ve(B,x.transcript);xe&&(oe=!0);const G=B.payload,Ze=!G.history.cursor_missing&&!xe;let rt=ue??x.transcript;Ze&&(performance.mark("lop:open:history:start"),rt=ir(rt,G.history,{authoritative:!0,orderRead:ne,peerSource:E(),readWitness:{epoch:B.epoch,seq:B.seq}}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),xs(se.current,G.history.entries),ei(me.current,G.history.entries)),e&&Ke.getState().resolveHeldFromServer(e,G.history.entries,Ze),performance.mark("lop:open:seed:start"),rt=Ow(rt,G.frontend.snapshot,Be,{epoch:B.epoch,seq:B.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const Kt=bl(x.frontend??x.heldFrontend,G.frontend.snapshot,G.cold===!0||G.attaching===!0);x={...x,contextCarried:Object.keys(Kt).length>0,subagentPulses:E0(G.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...G.frontend.snapshot,...Kt,attention:wn(x.frontend?.attention,G.frontend.snapshot.attention,e)},history:xe?x.history:G.history,cold:G.cold,ownerEpoch:G.frontend.epoch,failure:null,hydrated:x.hydrated||Ze&&G.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:rt},ce=!0,ue=null}continue}if(B.type==="attention"){x.frontend&&(x={...x,frontend:{...x.frontend,attention:wn(x.frontend.attention,B.payload,e)}});continue}if(B.type==="frontend.update"){const ne=B.payload,xe=ne.changes??{};if((ne.degraded===!0||ne.paused===!0)&&(x={...x,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!x.frontend)continue;const G=ne.epoch!==x.ownerEpoch&&xe.epoch===ne.epoch,Ze=ne.changes!==void 0&&xe.epoch===ne.epoch;(G||ne.epoch===x.ownerEpoch&&(x.frontend.sequence<ne.sequence||x.frontend.sequence===ne.sequence&&Ze))&&(x={...x,contextCarried:!1,ownerEpoch:G?ne.epoch:x.ownerEpoch,frontend:{...x.frontend,...xe,...xe.jobs==null&&ne.job_deltas?{jobs:w_(x.frontend.jobs??[],ne.job_deltas)}:{},attention:wn(x.frontend.attention,xe.attention,e),sequence:ne.sequence},...typeof ne.cold=="boolean"?{cold:ne.cold}:{}},Ze&&x.liveUpdatesNotice==="update"&&x.liveUpdatesPaused&&(x={...x,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(B.type==="frontend.replace"){if(x.frontend&&Yg(jt,e,B)){const ne=B.payload.frontend,xe=bl(x.frontend,ne.snapshot,B.payload.cold===!0);x={...x,contextCarried:Object.keys(xe).length>0,frontend:{...ne.snapshot,...xe,attention:wn(x.frontend.attention,ne.snapshot.attention,e)},ownerEpoch:ne.epoch,cold:B.payload.cold,...x.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(B.type==="event"){const ne=String(B.payload.type??"");if(B.payload.action==="reload"){x={...x,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}C0.has(ne)&&(x={...x,terminal:ne}),Sl.has(ne)&&(x={...x,turnsCompleted:x.turnsCompleted+1});const xe=oo(x.transcript,B.payload,Be,{frame:{epoch:B.epoch,seq:B.seq},userStoppedAt:e?Ke.getState().stoppedTurns[e]??null:null,queuedAskEngine:Wu(x.frontend)});xe!==x.transcript&&(x={...x,transcript:xe});const G=I0(x.subagentPulses,B.payload);G!==x.subagentPulses&&(x={...x,subagentPulses:G})}}if(!ce&&ue){for(const B of ue.index.keys())x.transcript.index.has(B)||se.current.add(B);x={...x,transcript:ue}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),F.current=x.transcript.index,!R0(K))return T;if(Zt.length>0){const B=new Set(x.labelPending);for(const jt of Zt)B.add(jt);x={...x,labelPending:B}}return x.frontend!==null&&x.frontend!==x.heldFrontend&&(x={...x,heldFrontend:x.frontend}),x}),Zt.length>0){for(const T of Zt)w.current.painted.add(T);for(;w.current.painted.size>G0;){const T=w.current.painted.values().next().value;if(T===void 0)break;w.current.painted.delete(T)}}const bt=Ne||oe,pn=Ur.length>0&&We.length===0&&nt.length===0&&!bt&&!Ae;if(bt||Pt.length>0||Ae){const T=new Set(Pt),x=w.current.order;$r(P,ze,Pt.length>0?{targets:T,order:x,starts:w.current.starts,waiting:w.current.waiting,every:new Set([...x,...T]),found:new Set(ys(K.flatMap(ce=>ce.type==="snapshot"?ce.payload.history.entries:[]),new Set(x))),pending:Zt}:Il,1,pn?ce=>{w.current.settleRows+=ce}:void 0,V,Y)}},$n=()=>{const K=Z;if(Z=null,f.current=null,p.current+=1,g.current&&(window.clearTimeout(g.current),g.current=0),y.current+=1,!!K){Fe=!0;try{K()}finally{Fe=!1}}},Un=()=>{const K=Qs(O.current.transcript),V=++Ea.current;Se(),ge=window.setTimeout(()=>{ge=0,et.current===P&&($n(),C(Y=>({...Y,subscriptionId:null,status:"unavailable",failure:yl(tr.ended),...Y.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ie&&(Ie=!0,he=window.setTimeout(()=>{he=0,et.current===P&&La()},j0)))},P0);const ie=_();Z=d_({sessionId:e,epoch:Ce.current.epoch,afterSeq:Ce.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:ut(O.current.transcript).slice(0,512),...ie?{peerJournalSource:!0}:{}}:{}},Y=>{if(et.current===P&&Ea.current===V){if(Y.kind==="error"||Y.kind==="end"){if(Fe)return;if(Se(),$n(),Y.kind==="error"&&Y.status===404){if(!n){e&&Ke.getState().retireDraftWarm(e),C(oe=>({...oe,subscriptionId:null}));return}e&&(c0(e),p0(e),_0(e),Ke.getState().retireDraftsForSession(e)),C(oe=>({...oe,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...oe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const de=Y.kind==="error"?Y.detail??h("ui.common.errors.event_stream_failed"):h("ui.common.errors.event_stream_closed");if(C(oe=>({...oe,subscriptionId:null})),Oe>=O0){C(oe=>({...oe,status:"unavailable",failure:yl(de),...oe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}Oe+=1;const _e=q.current;_e&&(Ce.current={epoch:_e.epoch,afterSeq:_e.seq}),C(oe=>oe.status==="unavailable"&&Oe>1?oe:{...oe,status:"reconnecting",failure:null}),D=window.setTimeout(()=>{D=0,et.current===P&&Un()},vl(Oe));return}if(Y.data!==void 0)try{const de=Y.data,_e=de.length>=L0;_e&&performance.mark("lop:open:parse:start");const oe=JSON.parse(de);oe.type==="snapshot"&&z.set(oe,K),_e&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),oe.type==="snapshot"&&(Oe=0,Se(),Ie=!1),N.current.push(oe),Ee||(Ee=requestAnimationFrame(Da)),ae||(ae=window.setTimeout(Da,N0))}catch{}}}),f.current={sessionId:e,peer:ie},p.current+=1},Na=()=>{D!==0&&(window.clearTimeout(D),D=0),Ce.current={},q.current=null,$n(),Un()},La=()=>{Oe=0,he&&(window.clearTimeout(he),he=0),D&&(window.clearTimeout(D),D=0),pe&&(window.clearTimeout(pe),pe=0),C(K=>({...K,failure:null,status:K.status==="unavailable"?"connecting":K.status,transcript:Xr(K.transcript,!1)})),O.current.hydrated||$r(P,new Set(O.current.transcript.index.keys())),!Z&&Un()};Un(),Bi.current=La,Gi.current=()=>{O.current.liveUpdatesReloading||(C(K=>({...K,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Oe=0,D&&(window.clearTimeout(D),D=0),he&&(window.clearTimeout(he),he=0),Na())},Hi.current=()=>{!O.current.hydrated&&Dn.current===0&&$r(P,new Set(O.current.transcript.index.keys()))};const sp=W0(e,Na),$a=()=>{if(!t||!e||m.current===e)return;const K=f.current;K===null||K.sessionId!==e||K.peer||_()&&(m.current=e,$n(),Un())};b.current=$a;const op=Ke.subscribe(()=>{$a()});return()=>{et.current+=1,Bi.current=null,Hi.current=null,Gi.current=null,b.current=null,op(),g.current&&(window.clearTimeout(g.current),g.current=0),sp(),$n(),Ee&&cancelAnimationFrame(Ee),ae&&clearTimeout(ae),D&&clearTimeout(D),pe&&clearTimeout(pe),tt.current&&(window.clearTimeout(tt.current),tt.current=0),yt.current&&(window.clearTimeout(yt.current),yt.current=0),he&&window.clearTimeout(he),Se(),N.current=[]}},[C,e,t,n,a,_,k,E]),S.useEffect(()=>{!e||!t||b.current?.()},[e,t,d]),S.useEffect(()=>{Ce.current={},q.current=null,F.current=st.index;const P=eS(I.current,e,n);I.current=e;const z=e?rf(e):null;F.current=P?O.current.transcript.index:(z?.transcript??st).index;const ee=new Set(P?se.current:[]);for(const Z of z?.replayBorn??[])ee.add(Z);const ve=P?O.current.transcript.index:(z?.transcript??st).index;for(const Z of ee)ve.has(Z)||ee.delete(Z);se.current=ee,P||(me.current=new Set),C(Z=>({...Z,frontend:null,heldFrontend:P?Z.heldFrontend:null,contextCarried:P?Z.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:P?Z.turnsCompleted:0,transcript:P?Z.transcript:z?.transcript??st,stale:P?Z.stale:z!==null,missing:P?Z.missing:!1,status:"connecting",subagentPulses:{},labelPending:z?.owedLabels??Qt,labelMarked:z?.markLabels??Xn,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),w.current=Rl(e)},[e,n]),S.useEffect(()=>{if(e)return()=>{const P=O.current.transcript;P.records.length>0&&a0(e,{transcript:P,owedLabels:new Set([...O.current.labelPending].filter(z=>Is(w.current,O.current.transcript.argsByCall,z,Es(O.current)))),markLabels:new Set(O.current.labelMarked),replayBorn:new Set(se.current)});for(const z of le.current)w.current.inFlight.delete(z);le.current.clear()}},[e]);const tt=S.useRef(0);S.useEffect(()=>{if(A.labelPending.size===0&&A.labelMarked.size===0){tt.current&&(window.clearTimeout(tt.current),tt.current=0);return}if(tt.current)return;const P=()=>{tt.current=0;const z=O.current.labelPending,ee=O.current.labelMarked;if(z.size===0&&ee.size===0)return;const ve=w.current;for(const Z of z)if(ve.inFlight.has(Z)){tt.current=window.setTimeout(P,ks);return}for(const Z of ee)if(ve.inFlight.has(Z)){tt.current=window.setTimeout(P,ks);return}C(Z=>Z.labelPending.size===0&&Z.labelMarked.size===0?Z:{...Z,labelPending:Qt,labelMarked:Xn})};tt.current=window.setTimeout(P,ks)},[C,A.labelPending,A.labelMarked]);const yt=S.useRef(0);S.useEffect(()=>{if(A.labelPending.size===0){yt.current&&(window.clearTimeout(yt.current),yt.current=0),C(P=>P.labelHoldLate?{...P,labelHoldLate:!1}:P);return}A.labelHoldLate||yt.current||(yt.current=window.setTimeout(()=>{yt.current=0,C(P=>P.labelPending.size===0||P.labelHoldLate?P:{...P,labelHoldLate:!0})},F0))},[C,A.labelPending,A.labelHoldLate]);const Ct=S.useRef(e);Ct.current=e;const Nn=S.useRef({id:e,epoch:0});Nn.current.id!==e&&(Nn.current={id:e,epoch:Nn.current.epoch+1});const zi=S.useRef(null);zi.current===null&&(zi.current=y0());const Wi=S.useRef(!1),Ln=S.useRef(null),[Ia,tp]=S.useState(0);S.useEffect(()=>{const P=A.transcript,z=ut(P);if(!e||!a||!P.orderNeedsReconcile&&(!P.journalGeneration||z.length===0)||Wi.current)return;const ee=D=>({fields:JSON.stringify([Ia,e,D.viewEpoch,Je(D),D.orderNeedsReconcile,D.orderWantedGeneration,ut(D)]),demand:D.orderDemand}),ve=ee(P);if(Ln.current?.fields===ve.fields&&Ln.current.demand===ve.demand)return;Ln.current=ve;const Z=e,Fe=P.viewEpoch;Wi.current=!0;let Ee=null,ae=P;const Oe=D=>{if(!D.peer||Ct.current!==Z||O.current.transcript.viewEpoch!==Fe||p.current!==D.streamEpoch)return;const pe=D.kind==="authority"?D.frame.payload.history:D.page,ge=pe.journal_order_state;if(ge==="ready"){g.current&&(window.clearTimeout(g.current),g.current=0),C(Ie=>{const Se=Xr(Ie.transcript,!1);return Se===Ie.transcript?Ie:{...Ie,transcript:Se}});return}if(ge==="unavailable"){if(g.current&&(window.clearTimeout(g.current),g.current=0),pe.reconcile===!0)return;C(Ie=>{const Se=Xr(Ie.transcript,!0);return Se===Ie.transcript?Ie:{...Ie,transcript:Se}});return}if(ge!=="building")return;g.current&&(window.clearTimeout(g.current),g.current=0);const he=++y.current;g.current=window.setTimeout(()=>{g.current=0,y.current===he&&Ct.current===Z&&O.current.transcript.viewEpoch===Fe&&p.current===D.streamEpoch&&C(Ie=>{const Se=Xr(Ie.transcript,!0);return Se===Ie.transcript?Ie:{...Ie,transcript:Se}})},M0)};x_({getTranscript:()=>O.current.transcript,isCurrent:()=>Ct.current===Z&&O.current.transcript.viewEpoch===Fe,sweep:(D,pe)=>{if(!k())return;if(D.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${Z}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const ge=D.journalGeneration;if(typeof ge!="string"||ge.length===0)return{kind:"none",path:`/v1/desktop/sessions/${Z}/history`,query:new URLSearchParams};if(Fd(D,pe?.("lookup")).length>0){const Se=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:ge});return{kind:"lookup",path:`/v1/desktop/sessions/${Z}/history`,query:Se}}if(Do(D).length>0){const Se=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:ge});return{kind:"payload",path:`/v1/desktop/sessions/${Z}/history`,query:Se}}return{kind:"none",path:`/v1/desktop/sessions/${Z}/history`,query:new URLSearchParams}},read:async(D,pe)=>{ae=O.current.transcript,Ln.current=ee(ae);const ge=k(),he=p.current;if(pe==="lookup"||pe==="payload"){const Se=O.current.transcript.journalGeneration,Lr=await Re({op:"sessions.history",sessionId:Z,limit:100,journalOrder:!0,orderIds:D,peerJournalSource:!0,sourceRead:pe==="payload"?"payload":"metadata",...typeof Se=="string"&&Se.length>0?{expectedJournalGeneration:Se}:{}});return pe==="payload"?{kind:"payload",page:Lr,peer:ge,streamEpoch:he}:{kind:"lookup",page:Lr,peer:ge,streamEpoch:he}}return{kind:"authority",frame:await Re({op:"sessions.get",sessionId:Z,journalOrder:!0,orderIds:D,...ge?{peerJournalSource:!0}:{}}),peer:ge,streamEpoch:he}},page:D=>D.kind==="authority"?D.frame.payload.history:D.page,lookupPath:`/v1/desktop/sessions/${Z}`,commit:(D,pe,ge)=>{D.peer&&p.current!==D.streamEpoch||(C(he=>Ct.current!==Z||Je(he.transcript)!==pe||he.transcript.viewEpoch!==Fe?he:{...he,transcript:D.kind==="authority"?D.peer?il(he.transcript,D.frame.payload.history,{authoritative:!0,orderRead:ge}):Ew(he.transcript,D.frame.payload.history,ge):D.kind==="payload"?Iw(he.transcript,D.page,ge,pe):il(he.transcript,D.page,{authoritative:!1})}),Oe(D))}}).then(D=>{Ee=D.kind==="complete"?D.transcript:null}).catch(D=>{console.warn("[canonical] source-order reconcile refused",D)}).finally(()=>{Wi.current=!1;const D=O.current.transcript,pe=Ee??ae;Ee&&Ct.current===Z&&D.viewEpoch===Fe&&!D.orderNeedsReconcile&&(Ln.current=ee(pe)),(Ct.current!==Z||D.viewEpoch!==Fe||Je(D)!==Je(pe)||D.orderWantedGeneration!==pe.orderWantedGeneration||D.orderNeedsReconcile!==pe.orderNeedsReconcile||D.orderDemand!==pe.orderDemand||JSON.stringify(ut(D))!==JSON.stringify(ut(pe)))&&tp(ge=>ge+1)})},[C,e,a,k,A.transcript,Ia]);const Nr=S.useCallback(async()=>{const P=zi.current;if(!e||!P)return{kind:"nothing-to-load"};const z=e,ee=Nn.current.epoch,ve=()=>Nn.current.epoch===ee,Z=O.current.transcript.viewEpoch,Fe=()=>O.current.transcript.viewEpoch===Z,Ee=await P.load(`${z}#${ee}`,{getTranscript:()=>O.current.transcript,readPage:ae=>Re({op:"sessions.history",sessionId:z,beforeId:ae,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(O.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>ve()&&Fe(),commit:ae=>C(Oe=>{const D=ae(Oe.transcript);return D===Oe.transcript?Oe:{...Oe,transcript:D}}).transcript,setLoading:ae=>{ve()&&C(Oe=>Oe.loadingOlder===ae?Oe:{...Oe,loadingOlder:ae})},peerSource:E});return ve()&&(Ee.kind==="failed"?C(ae=>ae.olderFailed?ae:{...ae,olderFailed:!0}):Ee.kind==="applied"&&C(ae=>ae.olderFailed?{...ae,olderFailed:!1}:ae)),Ee},[C,e,k,E]),xa=S.useCallback(async()=>(await Nr()).kind==="applied",[Nr]),Zi=S.useRef(!1),Ra=S.useCallback(async(P,z)=>{if(!e||Zi.current)return!1;const ee=e;Zi.current=!0;const ve=Je(O.current.transcript),Z=q.current,Fe=Z?{epoch:Z.epoch,seq:Z.seq}:null;try{const Ee=await Re({op:"sessions.history",sessionId:ee,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(O.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}});return Ct.current!==ee||Je(O.current.transcript)!==ve||O.current.transcript.viewEpoch!==z?!1:(C(ae=>Je(ae.transcript)!==ve?ae:{...ae,transcript:ir(ae.transcript,Ee,{keepPaging:!0,peerSource:E(),readWitness:Fe})}),xs(se.current,Ee.entries),ei(me.current,Ee.entries),Vw(Ee.entries,P))}catch{return!1}finally{Zi.current=!1}},[C,e,k,E]);S.useEffect(()=>r?X0(r,z=>{C(ee=>{const ve=z(ee.transcript);return ve===ee.transcript?ee:{...ee,transcript:ve}})}):void 0,[C,r]),S.useEffect(()=>{r&&J0(r,A.transcript)},[r,A.transcript]);const Ta=S.useCallback(()=>{C(P=>({...P,transcript:Gw(P.transcript),olderFailed:!1,heldFrontend:null}))},[C]),Ca=S.useCallback(()=>{Bi.current?.()},[]),Aa=S.useCallback(()=>{Gi.current?.()},[]),Oa=S.useCallback(()=>{Hi.current?.()},[]),Pa=S.useCallback((P,z="info")=>{C(ee=>({...ee,transcript:Ww(ee.transcript,P,z)}))},[C]),ja=S.useCallback(P=>{C(z=>({...z,pendingModel:P}))},[C]),Ma=S.useCallback(()=>{C(P=>P.pendingModel===null?P:{...P,pendingModel:null})},[C]);return S.useEffect(()=>{const P=A.pendingModel;if(!P)return;const z=bs(P);if(!z)return;const ee=A.frontend;(bs(ee?.selected_model)===z||bs(ee?.effective_model)===z)&&C(ve=>({...ve,pendingModel:null}))},[C,A.frontend,A.pendingModel]),S.useEffect(()=>{if(!A.pendingModel)return;const P=window.setTimeout(()=>C(z=>({...z,pendingModel:null})),A0);return()=>window.clearTimeout(P)},[C,A.pendingModel]),S.useMemo(()=>({...A,awaitingHydration:t&&!!e&&n&&!A.hydrated,loadOlder:xa,loadOlderDetailed:Nr,refreshTail:Ra,clearView:Ta,addNote:Pa,paintPendingModel:ja,clearPendingModel:Ma,retry:Ca,rehydrate:Oa,reloadFromHistory:Aa}),[A,t,e,n,xa,Nr,Ra,Ta,Pa,ja,Ma,Ca,Oa,Aa])}function Pi(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
34
+ `),s=(r?`${n} ${r}`:n).trim();if(s.length<=rr)return{headline:s,detail:i||null};const a=r===null?null:pw(r);if(a!==null){const c=(f,p)=>`${bi} ${[f,p].filter(Boolean).join(" ")}`,l=f=>[f,i].filter(Boolean).join(`
35
+ `)||null,d=`${n} ${c(a.leading,a.clause)}`;if(d.length<=rr)return{headline:d,detail:l(a.rest)};const u=`${n} ${c("",a.clause)}`;if(u.length<=rr)return{headline:u,detail:l([a.leading,a.rest].filter(Boolean).join(" "))}}return{headline:zu(s),detail:[r,i].filter(Boolean).join(`
36
+ `)||null}}function pw(e){const t=e.startsWith(bi)?e.slice(bi.length):e,n=t.indexOf("/mcp");if(n<0)return null;const r=t.slice(n),i=r.search(cw),s=(i<0?r:r.slice(0,i)).trim();return s?{leading:t.slice(0,n).trim(),clause:s,rest:(i<0?"":r.slice(i)).trim()}:null}function hw(e){const t=e.trim(),n=mw(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 mw(e){for(let t=0;t<e.length-1;t++)if(".!?…".includes(e[t])&&uw.test(e[t+1])&&!lw.test(e.slice(0,t+1))&&dw.test(e.slice(t+1).trimStart()[0]??""))return t+1;return-1}function gw(e,t){const n=e.split(`
37
+ `),r=n[0].match(ow),s=(typeof t.raw=="string"?t.raw.trim():"")||(r?n[0].slice(r[0].length):n[0]).trim()||e.trim(),a=n.slice(1).join(`
38
+ `).trim();return{provider:(r?.[1]??"").trim()||null,category:(r?.[2]??"").trim()||null,headline:s,detail:a||null}}function Hu(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 i=n.body;if(typeof i!="string"||!i.trim())return null;const s={...n};for(const a of["expects_reply","steer"])typeof s[a]!="boolean"&&(s[a]=null);for(const a of["label","job_id"])a in s&&typeof s[a]!="string"&&delete s[a];return s}function _w(e){const t=yw(e),n=e.split(`
39
+ `).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function yw(e){const t=e.split(`
40
+ `).map(c=>c.trim()).filter(Boolean),n=c=>!tl.test(c)&&!bw(c),r=t.find(n),i=t.find(c=>tl.test(c)&&!c.startsWith("</"));let s=r??i??e.trim();const a=t.indexOf(s);if(a>=0&&s.endsWith(":")){const c=t.slice(a+1).find(n);c&&(s=`${s} ${c}`)}return zu(s)}function bw(e){return aw.has(e.replace(/\s+/g," ").trim().toLowerCase())}function zu(e){const t=e.trim();if(t.length<=rr)return t;const n=t.slice(0,rr),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const vw="harness_injected",Wu=e=>!e||typeof e!="object"?!1:e[vw]===!0;function Zu(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function Ku(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const ww="ask";function nl(e,t){return t===!0&&String(e??"")===ww}function Sw(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function Vu(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:$u,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:r,text:a,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const a=n.details??{},c=Lu(String(a.detail??""));return{kind:"notice",id:e.id,ts:r,text:c.text,level:c.level}}if(e.type==="custom"&&n.custom_type==="completion_attention"){const a=n.details??{};if(typeof a.anchor=="string"){if(a.kind==="closed")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:Fu,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:Bu,level:"warning"};if(a.kind==="error"||a.kind==="interrupted")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:a.kind==="error"?"Stopped with an error":"Interrupted",level:a.kind==="error"?"error":"warning"}}}if(e.type==="custom"&&n.custom_type===ro){const a=n.details??{};return Xc(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(Qv.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=Js(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&fs(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...ri(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(p=>f[p]===u[p])?f:u,images:en(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===ew){const{body:u,sender:f}=tu(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&fs(t.sender,f)?t.sender:f}}if(a===rw){if(jy(c)||My(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===tw){const u=c.answers,f={};if(u&&typeof u=="object")for(const[y,m]of Object.entries(u))f[String(y)]=Array.isArray(m)?m.map(b=>String(b)):[];const p=c.questions,g=Array.isArray(p)?p.flatMap(y=>{if(!y||typeof y!="object")return[];const m=y;return[{id:String(m.id??""),question:String(m.question??""),secret:m.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(a===nw){const u=Number(c.waited_s);return{kind:"ask_timeout",id:e.id,ts:r,askId:String(c.ask_id??""),waitedS:Number.isFinite(u)&&u>0?u:0,urgent:c.urgent===!0}}if(a===ro)return Xc(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?sv(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:a,text:d,...a==="team_bridge_message"?{bridgeReceipt:Dy(c)}:{},attribution:n.attribution??"system",...ri(a,d,c)}:null}const s=String(n.role??"");if(s==="user"){const a=Hu(n.provider_payload);if(a){const u=Js({...a,text:ft(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&fs(f.sender,u.sender)&&(u.sender=f.sender);const p=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",...ri("hub_message",u.envelope||u.body,{...a,text:ft(n)}),receipt:f&&Object.keys(u).every(g=>f[g]===u[g])?f:u,images:en(n,e.id,p)}}}if(Wu(n.provider_payload))return null;const c=ft(n);if(bu(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=Ci(c),d=Mu(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:en(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(s==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=ft(n);return!c&&a.length>0?{kind:"assistant",id:e.id,ts:r,text:"",streaming:!1,stopReason:String(n.stop_reason??"toolUse"),callsTools:!0,error:!1}:{kind:"assistant",id:e.id,ts:r,text:c,complete:!0,streaming:!1,callsTools:a.length>0,stopReason:n.stop_reason??null,error:!!n.is_error}}if(s==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(Ku(l))return null;const d=Ou(l.__fault);return{kind:"tool",id:`tool:${a}`,ts:r,toolCallId:a,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:ft(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:en(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...yu(c.details,t?.kind==="tool"?t:null),diff:_u(gu(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:du(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:cu(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:lu(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:to(c.details,t?.kind==="tool"?t.details??null:null)}}return null}function kw(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 Ew=/^(?:tool|compaction|local):/;function Iw(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)&&!Ew.test(t.id))return t.id}return null}function xw(e,t){const n=dv(t);if(n)return e.records[e.index.get(n)??-1]}function Yo(e){const t=Ud(e,e.records);if(t===e.records)return e;const n=t.map(vu);return{...e,records:n,index:Qe(n)}}const kr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Yu(e,t,n,r){const i={...e,sourceEntryId:t,journalSeq:r,journalGeneration:n};if(e.kind==="user"&&(e.provisional===!0||e.local===!0)){const{provisional:s,local:a,...c}=i;return c}return i}function Rw(e){const t=new Set,n=new Set;for(const r of e.records){const i=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof i!="string"||i.length<1||i.length>128||(t.add(i),r.journalGeneration===e.journalGeneration&&kr(r.journalSeq)&&n.add(i))}return{carried:t,admitted:n}}function Qo(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function rl(e,t){const n=new Set;for(const a of t)typeof a=="string"&&a.length>0&&a.length<=128&&n.add(a);if(n.size===0)return e;let r=!1;const i=e.records.map(a=>{const c=a.sourceEntryId??(a.kind==="tool"||a.kind==="supplement"?null:a.id);if(c===null||!n.has(c))return a;const l=Qo(a);return l!==a&&(r=!0),l});let s=r?{...e,records:i}:e;return s=Qu(s,n),s}function Qu(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=Rw(e),i=e.orderRevision??0,s=e.journalBodyOwed;let a=null;const c=e.journalSourceVoid;let l=null;for(const d of t)typeof d!="string"||d.length<1||d.length>128||!n.has(d)||r.has(d)||(a||(a=new Map(s??[])),a.set(d,i),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return a?{...e,journalBodyOwed:a,...l?{journalSourceVoid:l}:{}}:e}function vi(e,t,n){const r=n&&e.journalSourceUnavailable===!0?{...e,journalSourceUnavailable:void 0}:e;if(t.length===0)return r;const i=r.journalBodyOwed;let s=null;const a=r.journalSourceVoid;let c=null;for(const l of t)i?.has(l)&&(s||(s=new Map(i)),s.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!s&&!c?r:{...r,...s?{journalBodyOwed:s}:{},...c?{journalSourceVoid:c}:{}}}function Pr(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function Xu(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function Tw(e,t,n){let r=On(e,t,t.entries.map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),!0,n);for(const s of t.entries)r=Mo(r,{...s.payload,id:s.id});const i=Pr(r,!1);return Yo(i.journalPeerSource===void 0&&!i.journalBodyOwed&&!i.journalSourceVoid&&i.journalSourceUnavailable===void 0?i:{...i,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function il(e,t,n){let r=On(e,t,(t.entries??[]).map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=Pr(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const s=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];s.length>0&&(r=Qu(r,s));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=vi(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=Xu(r,t),Yo(r)}function Cw(e,t,n,r){let i=On(e,t,[],!1,n,{peer:!0});i=Pr(i,!0);const s=i.journalBodyOwed,a=g=>r!==void 0&&(s?.get(g)??Number.NEGATIVE_INFINITY)>r,c=t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===i.journalGeneration,l=c?[...t.entries??[],...t.dependency_entries??[]]:[],d=[];let u=i.records,f=i.index;if(l.length>0){const g=new Map;for(const y of l){if(typeof y.id!="string"||y.id===""||a(y.id))continue;const m=`tool:${String(y.payload?.tool_call_id??"")}`,b=f.get(y.id)??f.get(m),_=b===void 0?void 0:u[b];if(!_)continue;let k=Vu(y,_);k&&(k={...k,sourceEntryId:y.id,..._.sourcePrecedes?{sourcePrecedes:_.sourcePrecedes}:{}},kr(y.journal_seq)?(k=Yu(k,y.id,t.journal_generation,y.journal_seq),d.push(y.id)):k=Qo(k),g.set(_.id,k))}g.size>0&&(u=u.map(y=>g.get(y.id)??y),f=Qe(u))}let p=u===i.records?i:{...i,records:u,index:f};if(c){p=vi(p,d,!1);const g=(t.source_missing_ids??[]).filter(y=>typeof y=="string"&&y.length>0&&y.length<=128&&!a(y));if(g.length>0){p=vi(p,g,!1);const y=new Set(p.journalSourceVoid??[]);for(const m of g)y.add(m);p={...p,journalSourceVoid:y}}}return p=Xu(p,t),Yo(p)}function Jr(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function ir(e,t,n={}){let r=e;const i=r,s=[],a=w=>Pr(vi(w,s,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=On(r,t,t.entries.map(w=>({id:w.id,journal_seq:w.journal_seq,role:w.payload?.role,tool_call_id:w.payload?.tool_call_id})),n.authoritative===!0,n.orderRead,{peer:n.peerSource===!0}),t.journal_generation&&t.journal_generation!==r.journalGeneration)return a(r);const c=n.peerSource===!0&&typeof t.journal_generation=="string"&&t.journal_generation.length>0&&t.journal_generation===r.journalGeneration;for(const w of t.entries)r=Mo(r,{...w.payload,id:w.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 w of t.entries){if(l&&!Kw(w,r.clearedAt))continue;const le=r.records[r.index.get(w.id)??-1]??r.records[r.index.get(`tool:${String(w.payload?.tool_call_id??"")}`)??-1]??xw(r,w);let q=Vu(w,le);if(q&&r.journalMode&&(q={...q,sourceEntryId:w.id}),q&&r.journalMode){const Ce=le?.sourcePrecedes??(n.pagedBefore!==void 0&&!le?d:void 0);Ce!==void 0&&q.sourcePrecedes!==Ce&&(q={...q,sourcePrecedes:Ce})}q&&c&&kr(w.journal_seq)?(q=Yu(q,w.id,t.journal_generation,w.journal_seq),s.push(w.id)):q&&n.peerSource===!0&&(q=Qo(q)),!(q&&le&&Sw(le,n.readWitness))&&q&&u.push(q)}let f=r.argsByCall,p=!1;for(const w of t.entries){const le=w.payload?.tool_calls;if(!Array.isArray(le))continue;const q=Math.round((w.ts??0)*1e3);for(const Ce of le)!Ce||typeof Ce.id!="string"||f.has(Ce.id)||(p||(f=new Map(f),p=!0),f.set(Ce.id,{...Ce,anchoredAt:q,anchorId:w.id}))}for(let w=0;w<u.length;w++){const le=u[w];if(le.kind!=="tool")continue;const q=f.get(le.toolCallId);if(!q)continue;const Ce=q.arguments??null;u[w]={...le,args:Ce,intent:typeof Ce?.i=="string"?Ce.i:null}}const g=p?r.records.map(w=>{if(w.kind!=="tool"||w.args)return w;const q=f.get(w.toolCallId)?.arguments??null;return q?{...w,args:q,intent:w.intent??(typeof q.i=="string"?q.i:null)}:w}):r.records,y=new Set(t.entries.map(w=>w.id)),m=n.peerSource===!0&&n.replace===!0?r.records.filter(w=>w.kind==="user"&&(w.provisional===!0||w.local===!0)&&!y.has(w.id)):[],b=n.replace?m.length>0?{...st,records:m,index:Qe(m)}:st:{...r,records:g},_=new Map(b.records.map(w=>[w.id,w]));let k=r!==i||n.replace||!n.replace&&g!==r.records;for(const w of u){const le=_.get(w.id);if(!le){k=!0,_.set(w.id,w);continue}if(le.kind==="tool"&&w.kind==="tool"){const q={...w,args:w.args??le.args,intent:w.intent??le.intent,images:Du(w.images,le.images,"current")};so(le,q)||(k=!0,_.set(w.id,q));continue}so(le,w)||(k=!0,_.set(w.id,w))}const E=r.compacting&&t.entries.some(w=>r.index.has(w.id)||Math.round((w.ts??0)*1e3)<r.compactingSince?!1:w.type==="compaction"||w.type==="message"&&w.payload?.custom_type==="compaction_refused"),A=t.entries[0],$=A?Math.round((A.ts??0)*1e3):0,O=r.journalMode?Rt:Zv(b.records,$,n.statedByOwner!==!1);let C=b.oldestId,I=b.oldestTs,N=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(A&&(C=A.id,I=$),N=t.has_more):n.pagedBefore!==void 0?A?(C=A.id,I=$,N=t.has_more):N=!1:A&&(r.journalMode?(r.journalPositions?.get(A.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):$>0&&$<r.oldestTs)&&(C=A.id,I=$,N=t.has_more));const F=C!==r.oldestId||I!==r.oldestTs;if(!k&&!F&&r.hasMore===N&&!E&&O.size===0)return a(r);const se=O.size===0?[..._.values()]:[..._.values()].map(w=>O.has(w.id)?Kv(w):w),me=Uu(Sr(se,n.statedByOwner===!1?Rt:new Set(u.map(w=>w.id)),r));return n.keepPaging?a({...r,records:me,index:Qe(me),argsByCall:f}):a({...r,records:me,index:Qe(me),oldestId:C,oldestTs:I,hasMore:N,argsByCall:f,compacting:E?!1:r.compacting,compactingSince:E?0:r.compactingSince})}const Aw=/^(?:local|notice|retry|subagent|compaction):/;function Xo(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!Aw.test(e.id)}}function Ow(e,t,n=Rt){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(i=>!(i.ts<t.ts&&Xo(i)&&!n.has(i.id)));return r.length===e.records.length?e:{...e,records:r,index:Qe(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const vt={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function _s(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function oo(e,t,n=Date.now(),r={}){let i=e;const s=t.message;if(t.type==="journal_order_ready"){const l=typeof t.journal_generation=="string"?t.journal_generation:void 0;if(i={...i,orderNeedsReconcile:!0,orderWantedGeneration:t.reconcile===!0?void 0:l,orderDemand:t.reconcile===!0?{}:{generation:l}},t.reconcile===!0)return i;const d=On(i,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=Sr(d.records,Rt,d);return d===i&&u===i.records?i:{...d,records:u,index:Qe(u)}}s&&(i=Mo(i,s));const a=r.frame,c=r.queuedAskEngine;switch(t.type){case"agent_start":{const l=Number(t.generation??i.generation+1);return l===i.generation?i:{...i,generation:l,compacting:!1,compactingSince:0}}case"compaction_start":return i.compacting?i:{...i,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??i.generation)<i.generation)return i;let d=i;for(const u of i.records)if(u.kind==="assistant"&&u.streaming&&(d=be(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=be(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=_s(s);if(s===void 0||l===null)return vt.idlessFrameRefused+=1,i;const d=i.records[i.index.get(l)??-1];if(s.role==="user"){const u=Hu(s.provider_payload);if(u){const m=ft(s),b=Js({...u,text:m});if(b.body.trim()){const _=d?.kind==="user"&&d.provisional===!0;return be(i,{kind:"custom",id:l,ts:_?wi(i,n):n,customType:"hub_message",text:b.envelope,attribution:"user",...ri("hub_message",b.envelope||b.body,{...u}),receipt:b,images:en(s,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(Wu(s.provider_payload))return i;const f=ft(s);if(bu(f))return i;const p=d?.kind==="user"&&d.provisional===!0,g=Mu(s,l,d?.kind==="user"?d.documents:void 0),y=Ci(f);return be(i,{kind:"user",id:l,ts:p?wi(i,n):n,text:f,images:en(s,l,d?.kind==="user"?d.images:void 0),...g.length?{documents:g}:{},...p?{provisional:!0}:{},...y?{skill:y}:{}})}return s.role!=="assistant"||d?i:be(i,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=_s(s);if(s===void 0||l===null)return vt.idlessFrameRefused+=1,i;const d=i.index.get(l),u=String(t.delta??""),f=ft(s);if(d===void 0)return!f&&!u?i:be(i,{kind:"assistant",id:l,ts:n,text:f?f+u:u,streaming:!0,truncated:f===""?"prefix":void 0,...a?{frame:a}:{},stopReason:null,error:!1});const p=i.records[d];if(p.kind!=="assistant")return i;if(!p.streaming)return vt.settledAssistantUpdate+=1,i;if(r.seed!==!0&&a&&p.frame&&a.epoch===p.frame.epoch&&a.seq<=p.frame.seq)return vt.staleUpdateFrameDropped+=1,i;const g=Wv(p.frame,a);if(r.seed===!0&&!f)return!p.text&&!u?i:(vt.seededDeltaWithheld+=p.text?1:0,be(i,{...p,text:p.text||u,...g?{frame:g}:{},truncated:p.text?"interrupted":"prefix"}));let y;if(f){if(y=f+u,y.length<=p.text.length)return i}else{if(!u)return i;y=p.text+u}return be(i,{...p,text:y,...g?{frame:g}:{},truncated:f?void 0:p.truncated})}case"message_end":{const l=_s(s);if(s===void 0)return vt.idlessFrameRefused+=1,i;if(l===null){if(s.role!=="assistant")return vt.idlessFrameRefused+=1,i;let y;for(const _ of i.records)if(!(_.kind!=="assistant"||!_.streaming)){if(y!==void 0)return vt.idlessFrameRefused+=1,i;y=_}if(y===void 0)return vt.idlessFrameRefused+=1,i;const m=Array.isArray(s.tool_calls)?s.tool_calls:[],b={...y,streaming:!1,settledAt:y.settledAt??n,callsTools:m.length>0,...y.text||m.length===0?{complete:!0}:{}};return be(i,b)}if(s.role!=="assistant")return i;const d=i.index.get(l),u=ft(s),f=d===void 0?void 0:i.records[d],p=Array.isArray(s.tool_calls)?s.tool_calls:[],g={kind:"assistant",id:l,ts:d===void 0?n:i.records[d].ts,text:u,...u||p.length===0?{complete:!0}:{},streaming:!1,callsTools:p.length>0,settledAt:f?.kind==="assistant"&&f.settledAt!==void 0?f.settledAt:n,stopReason:s.stop_reason??null,error:!!s.is_error,...a?{frame:a}:{}};return be(i,g)}case"history_delta":{const d=(Array.isArray(t.messages)?t.messages:[]).filter(E=>String(E.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,p=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=i.journalPeerSource===!0||g,m=y&&u!==void 0&&u===i.journalGeneration,b=d.map(E=>String(E.id??"")).filter(E=>E.length>0&&E.length<=128),_={entries:d.map(E=>{const A=String(E.id??""),$=f?.[A],O=p?.[A];return{id:A,ts:m&&typeof O=="number"&&Number.isFinite(O)?O:n/1e3,type:"message",payload:{kind:E.custom_type?"custom":"message",...E},...m&&kr($)?{journal_seq:$}:{}}}),has_more:i.hasMore,...m?{journal_generation:u}:{}};let k=ir(i,_,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:y});if(y&&b.length>0)if(m){const E=b.filter(A=>!kr(f?.[A]));E.length>0&&(k=rl(k,E))}else k=rl(k,b),u!==void 0&&(k=On(k,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),k=Pr(k,!0));return k}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return i;const d=String(t.supersedes_tool_call_id??""),u=`tool:${l}`,f=i.records[i.index.get(u)??-1],p=d?i.records[i.index.get(`tool:${d}`)??-1]:void 0,g=f?.kind==="tool"?f:p?.kind==="tool"?p:void 0;if(g&&g.phase!=="composing"&&g.phase!=="queued")return d&&f?.kind==="tool"?gs(i,d):i;const m=String(t.not_run_reason??"").trim()||null,b=String(t.not_run_kind??"").trim()||null;if(nl(t.tool_name,c)&&!m&&!g)return d?gs(i,d):i;const _=Number(t.argument_bytes??0),k={kind:"tool",id:u,ts:g?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:m?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:_>0?_:g?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:nr,added:0,removed:0,diff:null,stopped:!1,notRunReason:m,notRunKind:m?b:null,neverSent:m!==null};return d&&p?.kind==="tool"&&f?.kind!=="tool"?Yv(i,d,k):be(d&&f?.kind==="tool"?gs(i,d):i,k)}case"tool_execution_start":{const l=String(t.tool_call_id??"");if(!l)return i;const d=`tool:${l}`,u=i.records[i.index.get(d)??-1];if(u&&u.kind==="tool"&&u.phase==="done"&&!u.notRunReason)return i;const f=qc(i,l,t,u),p=f&&!i.argsByCall.has(l)?new Map(i.argsByCall).set(l,{arguments:f,anchoredAt:xn(t)??n}):i.argsByCall,g=p===i.argsByCall?i:{...i,argsByCall:p};return nl(t.tool_name,c)&&!u?g:be(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:xn(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:nr,added:0,removed:0,diff:u?.kind==="tool"?u.diff:null,details:u?.kind==="tool"?u.details??null:null,stopped:!1})}case"tool_execution_update":{const l=String(t.tool_call_id??"");if(!l)return i;const d=`tool:${l}`,u=i.records[i.index.get(d)??-1];if(!u||u.kind!=="tool")return i;const f=t.partial_result??{},p=to(f.details,u.details);return p===(u.details??null)?i:be(i,{...u,details:p})}case"tool_execution_end":{const l=String(t.tool_call_id??"");if(!l)return i;const d=`tool:${l}`,u=i.records[i.index.get(d)??-1],f=t.result??{};if(Ku(f.details))return ef(i,d);const p=qc(i,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:nr,added:0,removed:0,diff:null,stopped:!1},y=p&&!i.argsByCall.has(l)?new Map(i.argsByCall).set(l,{arguments:p,anchoredAt:xn(t)??n}):i.argsByCall,m=y===i.argsByCall?i:{...i,argsByCall:y},b=r.userStoppedAt??null,_=!!(t.is_error??f.is_error),k=Ou(f.details?.__fault),E=b!==null&&(typeof g.startedAt=="number"?g.startedAt<=b:_);return be(m,{...g,args:p,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:ft(f)||null,isError:E||k?!1:_,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:zv(en(f,d,g.images),g.images),...yu(f.details,g),diff:_u(gu(f.details),g.diff),stopped:g.stopped||E||k,delivery:du(f.details,g.delivery,g.toolName),bridge:cu(g.toolName,f.details,g.bridge),bridgeLabel:lu(g.toolName,f.details,g.bridgeLabel),details:to(f.details,g.details)})}case"supplement_progress":{const l=Nv(t);if(!l)return i;const d=zo(l.anchor),u=i.records[i.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,p=Au(f,l,n);return p?be(i,p):i}case"notice":{const l=String(t.text??"");if(!l)return i;const d=`notice:${i.generation}:${l}`;return i.index.has(d)?i:be(i,{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:Lu(String(t.detail??"")),p=f?f.text:l&&d?Xv(l,d):$u,g=`compaction:${i.generation}:${l}:${d}`,y=i.compacting?{...i,compacting:!1,compactingSince:0}:i;return y.index.has(g)?y:f?be(y,{kind:"notice",id:g,ts:n,text:p,level:f.level}):qv(be(y,{kind:"compaction",id:g,ts:n,text:p,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:${i.generation}:${String(t.attempt??"")}`;return i.index.has(d)?i:be(i,{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=i.records[i.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?i:be(i,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return i}}function xn(e){return Vg(e.started_at_epoch)}function Jo(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function Pw(e){const t=Jo(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function jw(e,t){const n=xn(e);if(n!==null)return n;const r=Jo(e);if(!r)return null;const i=t.argsByCall.get(r)?.anchoredAt;return typeof i=="number"&&Number.isFinite(i)&&i>0?i:null}function Mw(e,t){if(xn(e)!==null)return!1;const n=Jo(e);if(!n)return!1;const r=t.argsByCall.get(n)?.anchorId;if(typeof r!="string")return!1;const i=t.index.get(r);return i!==void 0&&i<=Nu(t.records)}function qo(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 Oi(e){return e.type==="tool_execution_end"}function Dw(e,t,n=Date.now(),r=null){let i=e;t.streaming&&t.generation>i.generation&&(i={...i,generation:t.generation}),i.compacting&&(i={...i,compacting:!1,compactingSince:0});const s=t.streaming===!0,a=Zu(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let p=n;const g=Pw(f);if(g!==null&&!i.index.has(g)){const y=jw(f,i);if(y!==null)p=y,c=!0,Mw(f,i)&&l.add(g);else if(Oi(f)||qo(f)||!s)continue}i=oo(i,f,p,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return i;const d=Sr(i.records,l,i);return{...i,records:d,index:Qe(d)}}function sl(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!Oi(r)&&!qo(r))continue;const i=String(r.tool_call_id??"");if(!i)continue;const s=xn(r);s!==null&&t.set(i,s)}return t}function Nw(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n;if(r.type!=="tool_call_compose")continue;const i=r.not_run_reason;if(typeof i=="string"&&i.trim().length>0)continue;const s=String(r.tool_call_id??"");s&&t.add(s)}return t}const Lw=5e3;function $w(e,t){const n=new Set(t),r=new Map;if(n.size===0)return r;for(const i of e){if(i.payload?.role!=="tool")continue;const s=i.payload.tool_call_id;if(typeof s!="string"||!n.has(s))continue;const a=i.ts;typeof a!="number"||!Number.isFinite(a)||r.set(s,Math.round(a*1e3))}return r}function Uw(e,t,n,r=new Map,i=new Set){const s=e[0]?.ts;if(typeof s!="number"||!Number.isFinite(s))return!1;let a=null;for(const l of t){const d=n.get(l);if(d===void 0){if(i.has(l))continue;return!1}(a===null||d<a)&&(a=d)}for(const l of r.values())(a===null||l<a)&&(a=l);return a===null?!1:Math.round(s*1e3)<=a-Lw}function ol(e,t){const n=[];for(const r of e??[]){if(!r)continue;const i=r;if(!Oi(i)&&!qo(i))continue;const s=String(i.tool_call_id??"");!s||n.includes(s)||t.has(s)||n.push(s)}return n}function al(e,t,n,r){const i=[],s=new Set;for(const a of t)s.has(a)||(s.add(a),!n.has(a)&&((e.get(a)??0)>=r||i.push(a)));return i}const Fw=3.25,ao=100,ea=500;function cl(e){return e<=0?ao:Math.min(ea,ao+Math.ceil(Fw*e))}function ys(e,t){const n=[];if(t.size===0)return n;for(const r of e){const i=r.payload?.tool_calls;if(Array.isArray(i))for(const s of i)s&&typeof s.id=="string"&&t.has(s.id)&&n.push(s.id)}return n}function Bw(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function Gw(e,t){const n=new Set(t);for(const s of e){const a=s.payload?.tool_calls;if(Array.isArray(a))for(const c of a)c&&typeof c.id=="string"&&n.add(c.id)}const r=[],i=new Set;for(const s of e){if(s.payload?.role!=="tool")continue;const a=s.payload.tool_call_id;typeof a!="string"||n.has(a)||i.has(a)||(i.add(a),r.push(a))}return r}function Hw(e,t){return e&&t===0}function zw(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,i=r.not_run_reason,s=r.type==="tool_call_compose"&&typeof i=="string"&&i.trim().length>0;if(r.type!=="tool_execution_start"&&!Oi(r)&&!s)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function Ju(e,t,n){const r=new Set(e),i=[];for(const s of t)!r.has(s)&&!n.has(s)&&i.push(s);for(const s of e){if(n.has(s))return i;t.has(s)&&i.push(s)}return i}function Ww(e,t,n){return Ju(e,t,n).length}function ll(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=be(t,{...n,truncated:"interrupted"}));return t}function Zw(e,t=Date.now()){return e.records.length===0?e:{...st,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function Kw(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 dl(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function Vw(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return Vo(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function wi(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function qu(e,t,n,r,i=Date.now(),s=io){if(e.index.has(t))return e;const a=Ci(n);return be(e,{kind:"user",id:t,ts:wi(e,i),text:n,images:r,...s.length?{documents:s}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function ef(e,t){return Vo(e,n=>n.id===t)}let ul=0;function Yw(e,t,n,r=Date.now()){return ul+=1,be(e,{kind:"notice",id:`local:${r}:${ul}`,ts:wi(e,r),text:t,level:n})}function UR(e,t,n,r){const i=t?.anchor_id,s=t?.kind;return!i||s!=="error"&&s!=="interrupted"&&s!=="closed"&&s!=="retired"||n||e.index.has(i)||!t?.unseen&&!r?.has(i)?e:(r?.add(i),be(e,{kind:"notice",id:i,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:s==="closed"?Fu:s==="retired"?Bu:s==="error"?"Stopped with an error":"Interrupted",level:s==="closed"?"info":s==="retired"?"warning":s==="error"?"error":"warning"}))}const Qw="compacting context…";function FR(e){return typeof e=="string"&&e.trim()===Qw}const Xw=[1500,5e3];async function BR(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of Xw){await t(n);try{if(await e())return}catch{}}}function Jw(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 fl=new Set(["openrouter","radient","radient-key"]),qw=new Set(["auto","openrouter/auto"]),e0="Auto";function tf(e){return e.slice(e.lastIndexOf("/")+1)||e}function t0(e,t){return e===t||e===tf(t)}function bs(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 GR(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():"",i=fl.has(t)||!r||t0(r,e.model_id)||r.toLowerCase()==="unknown";return{name:fl.has(t)&&qw.has(e.model_id)?e0:i?tf(n):r,selector:n}}function HR(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function zR(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function WR(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function ZR(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 KR(e){const t=e?.effort_displacement,n=t?.note;if(typeof n!="string"||!n.trim())return null;const r=new Map;for(const a of[e?.effective_model,e?.selected_model]){const c=typeof a?.display_name=="string"?a.display_name.trim():"";if(!a||!c||!a.provider||!a.model_id)continue;const l=`${a.provider}/${a.model_id}`;l!==t?.serving&&l!==t?.selected||r.set(l,c)}if(!r.size)return n.trim();const i=[...r.keys()].sort((a,c)=>c.length-a.length).map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),s=new RegExp(`(^|[\\s(])(${i.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(s,(a,c,l)=>`${c}${r.get(l)}`)}function VR(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function YR(e){const t=e.trim();return t&&({auto:"Auto",none:"None",minimal:"Minimal",low:h("ui.chat.session_status.effort_level.low"),medium:h("ui.chat.session_status.effort_level.medium"),high:h("ui.chat.session_status.effort_level.high"),xhigh:"xHigh",max:"Max"}[t.toLowerCase()]??t)}function nf(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 QR(e,t){const n=(e??t)?.effective_model;return nf(n)?null:n?.model_id??null}function XR(e){if(!e)return null;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim().toLowerCase():"",n=Array.isArray(e.reasoning_efforts)?e.reasoning_efforts.filter(s=>typeof s=="string"):null,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",i=nf(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(", ")}.`}:i?{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 JR(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 n0(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=Wn(n.provider);if(!a)return null;const c=Wn(e?.selected_model?.provider);if(c&&c!==a)return null;const d=["local","pending","eligible_borrow_unverified","effective_borrow","expired","withdrawn","owner_unavailable","device_bound","absent"].includes(n.effective_state)?n.effective_state:"pending";return d==="local"?null:{...d==="absent"?{connectHere:t==="local"}:{},provider:a,label:Wn(n.label)||a,effectiveState:d,owner:Wn(n.owner_label)||Wn(n.owner_device)||"the owner device",observedAt:vs(n.observed_at),lastGrantAt:vs(n.last_grant_at),lastGrantExpiresAt:vs(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 i=e?.effective_model?.provider;if(i&&i!==r)return null;const s=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:s,state:n.state}:{provider:r,label:s}}function qR(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function eT(e){return e&&e.draft!==!0?n0(e.frontend,e.servingLocality):null}function Wn(e){return typeof e=="string"?e.trim():""}function vs(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function ws(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function tT(e){const{label:t,effectiveState:n}=e,r=e.owner||"the owner device",i={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."]},s=e.state==="temporarily_unavailable",[a,c]=n?i[n]:[s?h("ui.chat.session_status.temporarily_unavailable",{label:t}):h("ui.chat.session_status.not_signed_in",{label:t}),s?h("ui.chat.session_status.temporarily_unavailable_description"):h("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];return n&&e.observedAt!==void 0&&l.push(`Last checked: ${ws(e.observedAt)}.`),n&&e.lastGrantAt!==void 0&&l.push(`Last resolved: ${ws(e.lastGrantAt)}.`),n&&e.lastGrantExpiresAt!==void 0&&l.push(`Recorded grant expiry: ${ws(e.lastGrantExpiresAt)}.`),n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push("History only; not permission to reuse access."),{title:a,description:c,history:l.join(" "),tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!s,canSwitchModel:n!=="effective_borrow"}}function nT(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function rT(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function iT(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function r0(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function i0(e,t){return!!e.streams[t]}function rf(e,t){return e.attached[t]?.turns.at(-1)}function sT(e,t){const n=rf(e,t);return n?e.streams[n.asideId]:void 0}function oT(e,t){const n=e.attached[t]?.turns??[];for(let r=n.length-1;r>=0;r-=1){const i=n[r];if(i&&e.streams[i.asideId]?.settled)return i.asideId}}function s0(){return{text:"",streaming:!0,settled:!1,error:null}}function o0(e){return{text:e,streaming:!1,settled:!0,error:null}}function a0(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const c0=Ar(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(i=>({streams:{...i.streams,[n]:s0()},attached:{...i.attached,[t]:{turns:[...i.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const i=r0(r.streams[t],n);return i?{streams:{...r.streams,[t]:i}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:o0(n)}}:r),failAside:(t,n)=>e(r=>i0(r,t)?{streams:{...r.streams,[t]:a0(r.streams[t],n)}}:r),setAsideNotice:(t,n)=>e(r=>{const i=r.attached[t];return i?{attached:{...r.attached,[t]:{...i,notice:n}}}:r}),queueAdoption:(t,n,r)=>e(i=>{const s=i.attached[t];return s?{attached:{...i.attached,[t]:{...s,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:i}),unqueueAdoption:(t,n,r)=>e(i=>{const s=i.attached[t];if(s?.queued?.asideId!==n)return i;const{queued:a,...c}=s;return{attached:{...i.attached,[t]:{...c,notice:r}}}}),detachAside:t=>e(n=>{const r=n.attached[t],i={...n.attached};if(delete i[t],!r)return{attached:i};const s={...n.streams};for(const a of r.turns)delete s[a.asideId];return{streams:s,attached:i}})}));function aT(e,t){return rf(e,t)?.asideId}const l0=4*1024*1024,pl=1024*1024,pt=new Map;function hl(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function d0(e){const t=e.slice(-200),n=hl(t);if(n<=pl)return{records:t,bytes:n};let r=0,i=t.length,s=0;for(;i-r>1;){const a=Math.floor((r+i)/2),c=hl(t.slice(a));c>pl?r=a:(i=a,s=c)}return{records:t.slice(i),bytes:s}}function u0(e,t){const{records:n,bytes:r}=d0(Vw(t.transcript).records);if(n.length===0){pt.delete(e);return}const i={...t.transcript,records:n,index:new Map(n.map((a,c)=>[a.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},s={transcript:i,savedAt:Date.now(),bytes:r,owedLabels:ml(n,t.owedLabels),markLabels:ml(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>i.index.has(a)))};pt.delete(e),pt.set(e,s),p0()}function ml(e,t){if(!t||t.size===0)return gl;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:gl}const gl=new Set;function sf(e){const t=pt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function f0(e){pt.delete(e)}function p0(){let e=0;for(const t of pt.values())e+=t.bytes;for(;e>l0&&pt.size>0;){const t=pt.keys().next().value;if(t===void 0)break;const n=pt.get(t);pt.delete(t),e-=n?.bytes??0}}const h0=8,m0=128,of=new Set,g0="",St=new Map,ta=e=>e??g0;function cT(e){return St.get(ta(e))??of}function lT(e,t,n){const r=ta(e),i=St.get(r)??new Set,s=new Set(i);if(n)for(s.delete(t),s.add(t);s.size>m0;){const a=s.values().next().value;if(a===void 0)break;s.delete(a)}else s.delete(t);for(St.delete(r),s.size>0&&St.set(r,s);St.size>h0;){const a=St.keys().next().value;if(a===void 0)break;St.delete(a)}return St.get(r)??of}function _0(e){St.delete(ta(e))}const y0=128,Si=4096,Ss=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),_l=e=>e.startsWith("qg:")&&e.length>3;function dT(e,t,n=null,r=[]){const i=new Map,s=new Map;for(let c=0;c<e.length;c+=1){const l=e[c];for(let d=0;d<l.segmentIds.length;d+=1){const u=l.segmentIds[d];if(i.has(u))return Ss("duplicate-prior-id");if(i.size===Si)return Ss("prior-id-limit");i.set(u,{ordinal:c,order:d})}l.eligible!==!1&&_l(l.key)&&t.has(l.key)&&s.size<y0&&s.set(c,l.key)}for(const c of r)if(!i.has(c)){if(i.size===Si)return Ss("prior-id-limit");i.set(c,{ordinal:-1,order:-1})}const a=n===null?void 0:i.get(n);if(a!==void 0&&a.ordinal>=0){const c=e[a.ordinal];c.eligible!==!1&&_l(c.key)&&s.set(a.ordinal,c.key)}return{complete:!0,owners:i,keys:s,reason:null}}function uT(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>Si)return r("prior-id-limit");const i=new Set,s=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,p,g)=>{const y=a.get(f);y===void 0?a.set(f,{current:p,many:!1,lastOrder:g,reordered:!1,outside:!1}):(y.current!==p&&(y.many=!0),g<=y.lastOrder&&(y.reordered=!0),y.lastOrder=g)};for(let f=0;f<t.length;f+=1){const p=t[f];let g=null,y=!1;for(const b of p.segmentIds){if(s!==null){if(s.has(b))return r("duplicate-current-id");if(s.size===Si)return r("current-uniqueness-unproved");s.add(b)}const _=e.owners.get(b);if(_!==void 0){if(i.has(b))return r("duplicate-current-id");i.add(b),l(_.ordinal,f,_.order),g===null?g=_.ordinal:g!==_.ordinal&&(y=!0)}}if(p.eligible===!1||y||g===null||g<0)continue;const m=e.keys.get(g);m!==void 0&&c.set(f,{owner:g,key:m})}for(const f of n.outsideCurrentIds??[]){const p=e.owners.get(f);if(p===void 0||i.has(f))continue;const g=a.get(p.ordinal);g!==void 0&&(g.outside=!0)}for(const[f,p]of c){const g=a.get(p.owner),y=p.key.slice(3);(g===void 0||g.many||g.reordered||g.outside||!i.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 p=c.get(f)?.key??t[f].key;if(d.has(p)){if(u.has(p))return r("key-collision");u.add(p)}}return{episodes:t.map((f,p)=>{const g=c.get(p);return g===void 0?f:{...f,key:g.key}}),reason:null}}const b0=8,v0="",qt=new Map,na=e=>e??v0;function fT(e){return qt.get(na(e))??null}function pT(e,t){const n=na(e);for(qt.delete(n),qt.set(n,t);qt.size>b0;){const r=qt.keys().next().value;if(r===void 0)break;qt.delete(r)}}function w0(e){qt.delete(na(e))}function S0(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const i=n.getTranscript().orderRevision??0,s=()=>(n.getTranscript().orderRevision??0)===i;try{let a=r,c=await n.readPage(a);if(!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing){const u=Iw(n.getTranscript()),f=u!==null&&u!==a?u:kw(c,a);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(a=f,c=await n.readPage(a),!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing)return{kind:"failed",reason:"cursor-missing"}}let l=n.getTranscript();const d=n.commit(u=>(l=u,(u.orderRevision??0)!==i?u:ir(u,c,{...u.oldestId===r?{pagedBefore:a}:{},...n.peerSource?.()===!0?{peerSource:!0}:{}})));return(d.orderRevision??0)!==i||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 i=r.getTranscript();if(!i.hasMore||!i.oldestId)return Promise.resolve({kind:"nothing-to-load"});const s={key:n,promise:t(r,i.oldestId)};e=s;const a=()=>{e===s&&(e=null)};return s.promise.then(a,a),s.promise}}}const k0={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"},E0={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function ra(e){return{kind:e,statement:h(k0[e]),action:E0[e]}}function yl(e){return ra(Xg(e))}const I0=()=>ra("historyUnreadable"),x0=new Set(["subagent_start","subagent_progress","subagent_end"]),R0=(e,t)=>({...e,[t]:(e[t]??0)+1}),T0=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=af(n);r&&(t[r]=(t[r]??0)+1)}return t},af=e=>{if(!e||typeof e!="object")return null;const t=e;return x0.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},C0=(e,t)=>{const n=af(t);return n?R0(e,n):e};function bl(e,t,n){if(!n||!e)return{};const r=e.context_tokens;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return{};const i=t.context_tokens;return typeof i=="number"&&Number.isFinite(i)&&i>=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 A0(e){for(const t of e)t.type==="aside_delta"&&c0.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function O0(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const Qt=new Set,Jn=new Set;function P0(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 j0=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),M0=15e3,co=[500,1e3,2e3,4e3,8e3,8e3],D0=co.length,N0=2e4,L0=1e4,$0=1e4;function vl(e){const t=Math.max(1,Math.min(e,co.length));return co[t-1]??8e3}const U0=3,F0=250,B0=32*1024,wl=512,Sl=new Set(["turn_end","agent_end"]),kl=2,G0=500,El=ea,H0=6,ks=Ed("sessions.history"),z0=2e3,Il={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},rn=new Map,ii=new Map,W0=8,Z0=2048,xl=1024,K0=1024,V0="",Vt=new Map;function Rl(e){const t=e??V0,n=Vt.get(t);if(n)return Vt.delete(t),Vt.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(Vt.set(t,r);Vt.size>W0;){const i=Vt.keys().next().value;if(i===void 0||i===t)break;Vt.delete(i)}return r}function Es(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function Is(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function Y0(e,t){return ii.set(e,t),()=>{ii.get(e)===t&&ii.delete(e)}}function hT(e){const t=ii.get(e);return t?(t(),!0):!1}const Te=new Map,Q0=4,X0=16;function cf(e,t){e(n=>qu(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function J0(e,t,n){const r=e.index.get(t),i=r===void 0?void 0:e.records[r];if(r===void 0||!i||i.kind!=="user"||!i.local||i.text===n)return e;const s=e.records.slice(),{skill:a,...c}=i,l=Ci(n);return s[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:s}}function lo(e,t){let n=Te.get(e);if(!n){if(Te.size>=X0){const s=Te.keys().next();s.done||Te.delete(s.value)}n=new Map,Te.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>Q0;){const s=n.keys().next();if(s.done)break;n.delete(s.value)}const i=rn.get(e);i&&cf(i,r)}function mT(e){if(!e)return null;const t=Te.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function uo(e,t){const n=Te.get(e);n&&(n.delete(t),n.size===0&&Te.delete(e))}function fo(e,t){const n=Te.get(e)?.get(t);n&&(n.settled=!0)}function Tl(e,t){return e?Te.get(e)?.has(t)===!0:!1}function gT(e){return e?(Te.get(e)?.size??0)>0:!1}function q0(e,t,n){const r=Te.get(e)?.get(t);if(!r)return;r.text=n;const i=rn.get(e);i&&i(s=>J0(s,t,n))}function eS(e,t){if(e===t)return;const n=Te.get(e);if(!n)return;Te.delete(e);const r=Te.get(t)??new Map;for(const[i,s]of n)s.identity=t,r.set(i,s);Te.set(t,r)}function qr(e){Te.delete(e)}function tS(e,t){const n=Te.get(e);if(n)for(const r of[...n.keys()]){const i=t.index.get(r),s=i===void 0?void 0:t.records[i];s?.kind==="user"&&s.local!==!0&&uo(e,r)}}function nS(e,t){rn.set(e,t);const n=Te.get(e);if(n)for(const r of n.values())cf(t,r);return()=>{rn.get(e)===t&&rn.delete(e)}}function rS(e,t){const n=Te.get(e);if(!n)return t;let r=t;for(const i of n.values())r=qu(r,i.id,i.text,i.images,void 0,i.documents);return r}function iS(e,t,n){return e===t?!0:!n}function sS(e,t){const n=rn.get(e);if(!n)return uo(e,t),"queued";let r="queued";return n(i=>{const s=i.records[i.index.get(t)??-1];return!s||s.kind!=="user"?i:s.local?(r="retracted",ef(i,t)):(r="owner",i)}),uo(e,t),r}function lf(e,t){const n=rn.get(e);if(!n)return"unseen";let r="unseen";return n(i=>{const s=i.records[i.index.get(t)??-1];return!s||s.kind!=="user"||(r=s.local?"local":"owner"),i}),r}function oS(e){const t=sf(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:st,stale:!1,owedLabels:Qt,markLabels:Jn}}function aS(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function xs(e,t){if(e.size!==0)for(const n of t)e.delete(it(n))}function ei(e,t){for(const n of t)e.add(it(n))}const Cl=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function _T(e,t,n=!0,r=e,i={}){const s=i.openFrame===!0,a=i.journalOrder===!0,c=S.useRef(a);c.current=a;const l=S.useRef(s);l.current=s;const d=i.peerJournalSource===!0,u=S.useRef(d);u.current=d;const f=S.useRef(null),p=S.useRef(0),g=S.useRef(0),y=S.useRef(0),m=S.useRef(null),b=S.useRef(null),_=S.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const P=Ke.getState();return ek(P.sessions,P.placementFacts,e)},[e]),k=S.useCallback(()=>{const P=f.current;return _()&&P!==null&&P.sessionId===e&&P.peer},[_,e]),E=S.useCallback(()=>{const P=f.current;return P!==null&&P.sessionId===e&&P.peer},[e]),[A,$]=S.useState(()=>{const P=t&&e?oS(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?rS(r,P?.transcript??st):st,stale:P?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:P?.owedLabels??Qt,labelMarked:P?.markLabels??Jn,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),O=S.useRef(A),C=S.useCallback(P=>{const z=P(O.current);return z===O.current||(O.current=z,$(z)),z},[]);S.useEffect(()=>fp(()=>{C(P=>{const{failure:z}=P;if(!z?.kind)return P;const ee=ra(z.kind);return ee.statement===z.statement&&ee.action===z.action?P:{...P,failure:ee}})}),[C]);const I=S.useRef(e),N=S.useRef([]),F=S.useRef(st.index),se=S.useRef(new Set),me=S.useRef(new Set),w=S.useRef(Rl(e)),le=S.useRef(new Set),q=S.useRef(null),Ce=S.useRef({}),Bi=S.useRef(null),Gi=S.useRef(null),Hi=S.useRef(null),Dn=S.useRef(0),et=S.useRef(0),Ea=S.useRef(0);S.useEffect(()=>{if(!e||!t)return;const P=++et.current,z=new WeakMap;let ee=null;const ve=(K,V)=>{const ie=z.get(K);if(ie===void 0||Xe(V)===ie.revision)return!1;const Y=K.payload.history.journal_generation;return!(typeof Y=="string"&&Y.length>0&&Y===V.journalGeneration)};let Z=null,Fe=!1,Ee=0,ae=0,Oe=0,D=0,pe=0,ge=0,he=0,Ie=!1;const Se=()=>{ge&&(window.clearTimeout(ge),ge=0)},Lr=K=>{for(const V of K)w.current.attempts.set(V,(w.current.attempts.get(V)??0)+1)},Ki=K=>{C(V=>{const ie=new Set;for(const _e of V.labelPending)V.labelPending.has(_e)&&(Is(w.current,V.transcript.argsByCall,_e,Es(V))||ie.add(_e));let Y=null;for(const _e of V.labelMarked)Is(w.current,V.transcript.argsByCall,_e,Es(V))||(Y=Y??new Set(V.labelMarked),Y.delete(_e));if(ie.size===0&&!Y)return V;const de=new Set(V.labelPending);for(const _e of ie)de.delete(_e);return{...V,labelPending:de.size?de:Qt,labelMarked:Y&&Y.size===0?Jn:Y??V.labelMarked}})},rp=K=>{C(V=>{let ie=null,Y=null;for(const de of K)V.labelPending.has(de)&&(ie=ie??new Set(V.labelPending),ie.delete(de),Y=Y??new Set(V.labelMarked),Y.add(de));return!ie||!Y?V:{...V,labelPending:ie.size?ie:Qt,labelMarked:Y}})},$r=async(K,V,ie=Il,Y=1,de,_e=V,oe=null)=>{Dn.current+=1,et.current===K&&C(Ae=>Ae.historyReadPending?Ae:{...Ae,historyReadPending:!0});for(const Ae of ie.targets)w.current.inFlight.add(Ae),le.current.add(Ae);let Ne=!1;try{Ne=await ip(K,V,_e,oe,ie,Y,de)}finally{if(Dn.current=Math.max(0,Dn.current-1),Dn.current===0&&C(Ae=>Ae.historyReadPending?{...Ae,historyReadPending:!1}:Ae),!Ne){for(const Ae of ie.targets)w.current.inFlight.delete(Ae);w.current.refused&&rp(ie.targets),Ki()}}},ip=async(K,V,ie,Y,de,_e,oe)=>{const Ne={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:ie.size===0},Ae=O.current.transcript.viewEpoch,Pe=await sp(K,V,ie,Y,de,_e,Ne,oe);if(Pe||et.current!==K||Ne.reachedHeld||O.current.transcript.viewEpoch!==Ae)return Pe;const He=V!==ie&&[...V].some(We=>ie.has(We));if(He&&Ne.joined)return Pe;let ze;if(Ne.oldest){if(!Ne.hasMore)return Pe;ze={id:Ne.oldest.id,ts:Math.round((Ne.oldest.ts??0)*1e3)}}else{if(He||!Y)return Pe;ze=Y}if(!ze)return Pe;const At=C(We=>{const nt=Ow(We.transcript,ze,Ne.keys);return nt===We.transcript?We:{...We,transcript:nt}});return F.current=At.transcript.index,Pe},sp=async(K,V,ie,Y,de,_e,oe,Ne)=>{const Ae=O.current.transcript.viewEpoch,Pe=()=>O.current.transcript.viewEpoch!==Ae,He=new Set;let ze,At=0,We=0,nt=!1,Ot=ie.size===0,fn=!1;const Ur=O.current.cold,Pt=q.current,Zt=Pt?{epoch:Pt.epoch,seq:Pt.seq}:null,bt=new Set(de.found),pn=()=>Ww(de.order,de.targets,bt),T=()=>Ju(de.order,de.targets,bt),x=()=>{const G=new Map;for(const Ze of ue){if(bt.has(Ze))continue;const rt=Be.get(Ze);rt!==void 0&&G.set(Ze,rt)}return G},ce=new Set(de.every);for(const G of bt)ce.add(G);const ue=new Set,Be=new Map;let B=1;const jt=de.targets.size>0;let ne=Math.max(cl(pn()),jt?w.current.depth:0),xe=0;for(;At<El&&We<H0;){We+=1;let G;const Ze=Qs(O.current.transcript),rt=Ze.revision;try{G=await Re({op:"sessions.history",sessionId:e,...ze?{beforeId:ze}:{},limit:Math.min(ne,El-At),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(O.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}})}catch{if(Pe())return!1;if(O.current.transcript.records.length>0){if(xe++>0)return w.current.refused=!0,!1;continue}return _e<U0?(pe=window.setTimeout(()=>{if(pe=0,et.current!==K||Pe()){Ki();return}$r(K,V,de,_e+1,Ne,ie,Y)},vl(_e)),!0):(C(fe=>({...fe,status:"unavailable",failure:I0(),heldFrontend:null,...fe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{Ki()}if(et.current!==K||Pe())return!1;if(Xe(O.current.transcript)!==rt){if(!O.current.hydrated)continue;return!1}w.current.refused=!1;const Kt=G.entries[0];At+=G.entries.length,Ne?.(G.entries.length),xs(se.current,G.entries),ei(me.current,G.entries),C(fe=>{if(Xe(fe.transcript)!==rt)return fe;const dt=ir(fe.transcript,G,{authoritative:!0,orderRead:Ze,peerSource:E(),readWitness:Zt}),hn=ys(G.entries,ce),Yi=new Set(fe.labelPending);for(const lp of hn)Yi.delete(lp);return{...fe,hydrated:fe.hydrated||G.entries.length>0||!Ur,labelPending:Yi.size?Yi:Qt,labelMarked:P0(fe.labelMarked,hn),transcript:dt}}),e&&ze===void 0&&Ke.getState().resolveHeldFromServer(e,G.entries,!G.cursor_missing);const cp=pn();for(const fe of ys(G.entries,ce))bt.add(fe),ce.add(fe);if(Bw(G.entries)&&(fn=!0),jt){const fe=Gw(G.entries,ce);for(const dt of fe)ue.add(dt),ce.add(dt);for(const[dt,hn]of $w(G.entries,fe))Be.set(dt,hn);for(const dt of[...ue])bt.has(dt)&&ue.delete(dt);ue.size>0&&B--<=0&&ue.clear()}nt=nt||V.size===0||G.entries.some(fe=>V.has(it(fe))||He.has(fe.id)),Ot=Ot||G.entries.some(fe=>ie.has(it(fe)));for(const fe of G.entries)He.add(fe.id);for(const fe of G.entries)oe.keys.add(it(fe));Kt&&(oe.oldest=Kt),oe.hasMore=G.has_more,oe.joined=nt,oe.reachedHeld=Ot;const Vi=pn()+ue.size;jt&&pn()<cp&&(w.current.depth=Math.min(ea,Math.max(w.current.depth,At)));let Ua=!1;if(jt){const fe=T();Ua=Uw(G.entries,fe,de.starts,x(),new Set(fe.filter(hn=>de.waiting.has(hn))))||fn}if(Hw(nt&&Ot,Ua?0:Vi)||!Kt||!G.has_more)return!1;ze=Kt.id,ne=Vi>0?cl(Vi):ao}return!1},Da=()=>{if(Ee&&cancelAnimationFrame(Ee),ae&&clearTimeout(ae),Ee=0,ae=0,et.current!==P)return;const K=N.current;if(N.current=[],K.length===0)return;const V=new Set,ie=new Map;for(const T of se.current)O.current.transcript.index.has(T)||se.current.delete(T);for(const T of me.current)O.current.transcript.index.has(T)||me.current.delete(T);for(const T of O.current.transcript.records)Xo(T)&&!se.current.has(T.id)&&(V.add(T.id),ie.set(T.id,me.current.has(T.id)?T.ts:null));let Y=null;for(const T of K){if(T.type!=="snapshot")continue;const x=T.payload.history,ce=x.entries[0];if(!ce||!x.has_more)continue;const ue=Math.round((ce.ts??0)*1e3);ue>0&&(!Y||ue<Y.ts)&&(Y={id:ce.id,ts:ue})}A0(K);const de=T=>{const x=T.payload.history.entries,ce=x.at(-1);if(!ce)return!1;if(aS(T.payload)){if(V.size===0)return!0;const ue=new Set;for(const Be of x)ue.add(it(Be));return x.some(Be=>V.has(it(Be)))?!0:C_(T.payload.history,ie,ue)}return ce.id===T.payload.frontend.snapshot.history_cursor?!1:V.has(it(ce))},_e=T=>T!=null&&F.current.has(T);let oe=!1;const Ne=K.some(T=>T.type==="attention"?!_e(T.payload.anchor_id):T.type==="snapshot"&&!de(T)),Ae=O.current.cold&&!O.current.hydrated&&K.some(T=>T.type==="snapshot"||T.type==="frontend.replace"||T.type==="frontend.update"?T.payload.cold===!1:!1),Pe=new Set(O.current.transcript.argsByCall.keys()),He=[],ze=new Set;for(const T of K){if(T.type!=="snapshot")continue;const x=ve(T,O.current.transcript);x||ei(me.current,T.payload.history.entries);for(const ce of T.payload.history.entries){x||ze.add(it(ce));const ue=ce.payload?.tool_calls;if(Array.isArray(ue))for(const Be of ue)Be&&typeof Be.id=="string"&&Pe.add(Be.id)}for(const ce of T.payload.frontend.snapshot.live_events??[]){const ue=ce.message;!x&&typeof ue?.id=="string"&&ze.add(ue.id)}He.push(...T.payload.frontend.snapshot.live_events??[])}const At=K.some(T=>T.type==="event"&&Sl.has(String(T.payload.type??""))),We=al(w.current.attempts,ol(He,Pe),Pe,kl),nt=At?al(w.current.attempts,[...w.current.attempts.keys(),...w.current.settled],Pe,kl):[],Ot=[];for(const T of K){if(T.type!=="event")continue;const x=T.payload;String(x.type??"")==="tool_execution_end"&&String(x.tool_call_id??"")&&Ot.push(x)}const fn=[];for(const T of Ot){const x=String(T.tool_call_id??"");Pe.has(x)||w.current.settled.has(x)||fn.push(x)}for(const T of fn)w.current.settled.add(T);for(;w.current.settled.size>wl;){const T=w.current.settled.values().next().value;if(T===void 0)break;w.current.settled.delete(T)}for(const[T,x]of sl(Ot))w.current.starts.set(T,x);for(;w.current.starts.size>xl;){const T=w.current.starts.keys().next().value;if(T===void 0)break;w.current.starts.delete(T)}const Ur=w.current.settleRows<G0?fn:[],Pt=[...new Set([...We,...nt,...Ur])],Zt=Pt.filter(T=>!w.current.painted.has(T));if(He.length>0){w.current.order=ol(He,new Set);for(const[T,x]of sl(He))w.current.starts.set(T,x);for(;w.current.starts.size>xl;){const T=w.current.starts.keys().next().value;if(T===void 0)break;w.current.starts.delete(T)}for(const T of Nw(He))w.current.waiting.add(T);for(const T of zw(He))w.current.waiting.delete(T);for(;w.current.waiting.size>K0;){const T=w.current.waiting.values().next().value;if(T===void 0)break;w.current.waiting.delete(T)}}for(const T of[...w.current.attempts.keys()])Pe.has(T)&&w.current.attempts.delete(T);for(Lr([...We,...nt]);w.current.attempts.size>wl;){const T=w.current.attempts.keys().next().value;if(T===void 0)break;w.current.attempts.delete(T)}if(performance.mark("lop:transcript:flush:start"),C(T=>{let x={...T},ce=x.frontend!==null;oe=!1;let ue=null;const Be=Date.now();for(const B of K){if(B.type==="heartbeat")continue;if(B.type==="gap"){ee=null,x={...x,frontend:null,heldFrontend:x.frontend??x.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:ll(x.transcript)},ce=!1;continue}if(B.type==="open")ee=null;else if("seq"in B){const ne={epoch:B.epoch,seq:B.seq},xe=Cl(B);if(!xe&&!Yg(ee,ne,{allowEqual:B.type==="snapshot"}))continue;xe||(ee=ne)}const jt=q.current;if((B.type==="open"||"seq"in B)&&!Cl(B)&&(q.current={epoch:B.epoch,seq:B.seq},x={...x,receipt:q.current}),B.type==="open"){if(x={...x,subscriptionId:B.payload.subscription_id},B.payload.gap){const ne=x.frontend??x.heldFrontend;x={...x,frontend:null,heldFrontend:ne,history:null,transcript:ll(x.transcript)},ne&&x.status==="live"&&(x={...x,status:"reconnecting"}),ce=!1}continue}if(!ce){if(B.type==="event"&&(ue=oo(ue??x.transcript,B.payload,Be,{frame:{epoch:B.epoch,seq:B.seq}})),B.type==="snapshot"){const ne=z.get(B),xe=ve(B,x.transcript);xe&&(oe=!0);const G=B.payload,Ze=!G.history.cursor_missing&&!xe;let rt=ue??x.transcript;Ze&&(performance.mark("lop:open:history:start"),rt=ir(rt,G.history,{authoritative:!0,orderRead:ne,peerSource:E(),readWitness:{epoch:B.epoch,seq:B.seq}}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),xs(se.current,G.history.entries),ei(me.current,G.history.entries)),e&&Ke.getState().resolveHeldFromServer(e,G.history.entries,Ze),performance.mark("lop:open:seed:start"),rt=Dw(rt,G.frontend.snapshot,Be,{epoch:B.epoch,seq:B.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const Kt=bl(x.frontend??x.heldFrontend,G.frontend.snapshot,G.cold===!0||G.attaching===!0);x={...x,contextCarried:Object.keys(Kt).length>0,subagentPulses:T0(G.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...G.frontend.snapshot,...Kt,attention:wn(x.frontend?.attention,G.frontend.snapshot.attention,e)},history:xe?x.history:G.history,cold:G.cold,ownerEpoch:G.frontend.epoch,failure:null,hydrated:x.hydrated||Ze&&G.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:rt},ce=!0,ue=null}continue}if(B.type==="attention"){x.frontend&&(x={...x,frontend:{...x.frontend,attention:wn(x.frontend.attention,B.payload,e)}});continue}if(B.type==="frontend.update"){const ne=B.payload,xe=ne.changes??{};if((ne.degraded===!0||ne.paused===!0)&&(x={...x,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!x.frontend)continue;const G=ne.epoch!==x.ownerEpoch&&xe.epoch===ne.epoch,Ze=ne.changes!==void 0&&xe.epoch===ne.epoch;(G||ne.epoch===x.ownerEpoch&&(x.frontend.sequence<ne.sequence||x.frontend.sequence===ne.sequence&&Ze))&&(x={...x,contextCarried:!1,ownerEpoch:G?ne.epoch:x.ownerEpoch,frontend:{...x.frontend,...xe,...xe.jobs==null&&ne.job_deltas?{jobs:S_(x.frontend.jobs??[],ne.job_deltas)}:{},attention:wn(x.frontend.attention,xe.attention,e),sequence:ne.sequence},...typeof ne.cold=="boolean"?{cold:ne.cold}:{}},Ze&&x.liveUpdatesNotice==="update"&&x.liveUpdatesPaused&&(x={...x,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(B.type==="frontend.replace"){if(x.frontend&&Qg(jt,e,B)){const ne=B.payload.frontend,xe=bl(x.frontend,ne.snapshot,B.payload.cold===!0);x={...x,contextCarried:Object.keys(xe).length>0,frontend:{...ne.snapshot,...xe,attention:wn(x.frontend.attention,ne.snapshot.attention,e)},ownerEpoch:ne.epoch,cold:B.payload.cold,...x.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(B.type==="event"){const ne=String(B.payload.type??"");if(B.payload.action==="reload"){x={...x,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}j0.has(ne)&&(x={...x,terminal:ne}),Sl.has(ne)&&(x={...x,turnsCompleted:x.turnsCompleted+1});const xe=oo(x.transcript,B.payload,Be,{frame:{epoch:B.epoch,seq:B.seq},userStoppedAt:e?Ke.getState().stoppedTurns[e]??null:null,queuedAskEngine:Zu(x.frontend)});xe!==x.transcript&&(x={...x,transcript:xe});const G=C0(x.subagentPulses,B.payload);G!==x.subagentPulses&&(x={...x,subagentPulses:G})}}if(!ce&&ue){for(const B of ue.index.keys())x.transcript.index.has(B)||se.current.add(B);x={...x,transcript:ue}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),F.current=x.transcript.index,!O0(K))return T;if(Zt.length>0){const B=new Set(x.labelPending);for(const jt of Zt)B.add(jt);x={...x,labelPending:B}}return x.frontend!==null&&x.frontend!==x.heldFrontend&&(x={...x,heldFrontend:x.frontend}),x}),Zt.length>0){for(const T of Zt)w.current.painted.add(T);for(;w.current.painted.size>Z0;){const T=w.current.painted.values().next().value;if(T===void 0)break;w.current.painted.delete(T)}}const bt=Ne||oe,pn=Ur.length>0&&We.length===0&&nt.length===0&&!bt&&!Ae;if(bt||Pt.length>0||Ae){const T=new Set(Pt),x=w.current.order;$r(P,ze,Pt.length>0?{targets:T,order:x,starts:w.current.starts,waiting:w.current.waiting,every:new Set([...x,...T]),found:new Set(ys(K.flatMap(ce=>ce.type==="snapshot"?ce.payload.history.entries:[]),new Set(x))),pending:Zt}:Il,1,pn?ce=>{w.current.settleRows+=ce}:void 0,V,Y)}},$n=()=>{const K=Z;if(Z=null,f.current=null,p.current+=1,g.current&&(window.clearTimeout(g.current),g.current=0),y.current+=1,!!K){Fe=!0;try{K()}finally{Fe=!1}}},Un=()=>{const K=Qs(O.current.transcript),V=++Ea.current;Se(),ge=window.setTimeout(()=>{ge=0,et.current===P&&($n(),C(Y=>({...Y,subscriptionId:null,status:"unavailable",failure:yl(tr.ended),...Y.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ie&&(Ie=!0,he=window.setTimeout(()=>{he=0,et.current===P&&La()},L0)))},N0);const ie=_();Z=u_({sessionId:e,epoch:Ce.current.epoch,afterSeq:Ce.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:ut(O.current.transcript).slice(0,512),...ie?{peerJournalSource:!0}:{}}:{}},Y=>{if(et.current===P&&Ea.current===V){if(Y.kind==="error"||Y.kind==="end"){if(Fe)return;if(Se(),$n(),Y.kind==="error"&&Y.status===404){if(!n){e&&Ke.getState().retireDraftWarm(e),C(oe=>({...oe,subscriptionId:null}));return}e&&(f0(e),_0(e),w0(e),Ke.getState().retireDraftsForSession(e)),C(oe=>({...oe,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...oe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const de=Y.kind==="error"?Y.detail??h("ui.common.errors.event_stream_failed"):h("ui.common.errors.event_stream_closed");if(C(oe=>({...oe,subscriptionId:null})),Oe>=D0){C(oe=>({...oe,status:"unavailable",failure:yl(de),...oe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}Oe+=1;const _e=q.current;_e&&(Ce.current={epoch:_e.epoch,afterSeq:_e.seq}),C(oe=>oe.status==="unavailable"&&Oe>1?oe:{...oe,status:"reconnecting",failure:null}),D=window.setTimeout(()=>{D=0,et.current===P&&Un()},vl(Oe));return}if(Y.data!==void 0)try{const de=Y.data,_e=de.length>=B0;_e&&performance.mark("lop:open:parse:start");const oe=JSON.parse(de);oe.type==="snapshot"&&z.set(oe,K),_e&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),oe.type==="snapshot"&&(Oe=0,Se(),Ie=!1),N.current.push(oe),Ee||(Ee=requestAnimationFrame(Da)),ae||(ae=window.setTimeout(Da,F0))}catch{}}}),f.current={sessionId:e,peer:ie},p.current+=1},Na=()=>{D!==0&&(window.clearTimeout(D),D=0),Ce.current={},q.current=null,$n(),Un()},La=()=>{Oe=0,he&&(window.clearTimeout(he),he=0),D&&(window.clearTimeout(D),D=0),pe&&(window.clearTimeout(pe),pe=0),C(K=>({...K,failure:null,status:K.status==="unavailable"?"connecting":K.status,transcript:Jr(K.transcript,!1)})),O.current.hydrated||$r(P,new Set(O.current.transcript.index.keys())),!Z&&Un()};Un(),Bi.current=La,Gi.current=()=>{O.current.liveUpdatesReloading||(C(K=>({...K,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Oe=0,D&&(window.clearTimeout(D),D=0),he&&(window.clearTimeout(he),he=0),Na())},Hi.current=()=>{!O.current.hydrated&&Dn.current===0&&$r(P,new Set(O.current.transcript.index.keys()))};const op=Y0(e,Na),$a=()=>{if(!t||!e||m.current===e)return;const K=f.current;K===null||K.sessionId!==e||K.peer||_()&&(m.current=e,$n(),Un())};b.current=$a;const ap=Ke.subscribe(()=>{$a()});return()=>{et.current+=1,Bi.current=null,Hi.current=null,Gi.current=null,b.current=null,ap(),g.current&&(window.clearTimeout(g.current),g.current=0),op(),$n(),Ee&&cancelAnimationFrame(Ee),ae&&clearTimeout(ae),D&&clearTimeout(D),pe&&clearTimeout(pe),tt.current&&(window.clearTimeout(tt.current),tt.current=0),yt.current&&(window.clearTimeout(yt.current),yt.current=0),he&&window.clearTimeout(he),Se(),N.current=[]}},[C,e,t,n,a,_,k,E]),S.useEffect(()=>{!e||!t||b.current?.()},[e,t,d]),S.useEffect(()=>{Ce.current={},q.current=null,F.current=st.index;const P=iS(I.current,e,n);I.current=e;const z=e?sf(e):null;F.current=P?O.current.transcript.index:(z?.transcript??st).index;const ee=new Set(P?se.current:[]);for(const Z of z?.replayBorn??[])ee.add(Z);const ve=P?O.current.transcript.index:(z?.transcript??st).index;for(const Z of ee)ve.has(Z)||ee.delete(Z);se.current=ee,P||(me.current=new Set),C(Z=>({...Z,frontend:null,heldFrontend:P?Z.heldFrontend:null,contextCarried:P?Z.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:P?Z.turnsCompleted:0,transcript:P?Z.transcript:z?.transcript??st,stale:P?Z.stale:z!==null,missing:P?Z.missing:!1,status:"connecting",subagentPulses:{},labelPending:z?.owedLabels??Qt,labelMarked:z?.markLabels??Jn,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),w.current=Rl(e)},[e,n]),S.useEffect(()=>{if(e)return()=>{const P=O.current.transcript;P.records.length>0&&u0(e,{transcript:P,owedLabels:new Set([...O.current.labelPending].filter(z=>Is(w.current,O.current.transcript.argsByCall,z,Es(O.current)))),markLabels:new Set(O.current.labelMarked),replayBorn:new Set(se.current)});for(const z of le.current)w.current.inFlight.delete(z);le.current.clear()}},[e]);const tt=S.useRef(0);S.useEffect(()=>{if(A.labelPending.size===0&&A.labelMarked.size===0){tt.current&&(window.clearTimeout(tt.current),tt.current=0);return}if(tt.current)return;const P=()=>{tt.current=0;const z=O.current.labelPending,ee=O.current.labelMarked;if(z.size===0&&ee.size===0)return;const ve=w.current;for(const Z of z)if(ve.inFlight.has(Z)){tt.current=window.setTimeout(P,ks);return}for(const Z of ee)if(ve.inFlight.has(Z)){tt.current=window.setTimeout(P,ks);return}C(Z=>Z.labelPending.size===0&&Z.labelMarked.size===0?Z:{...Z,labelPending:Qt,labelMarked:Jn})};tt.current=window.setTimeout(P,ks)},[C,A.labelPending,A.labelMarked]);const yt=S.useRef(0);S.useEffect(()=>{if(A.labelPending.size===0){yt.current&&(window.clearTimeout(yt.current),yt.current=0),C(P=>P.labelHoldLate?{...P,labelHoldLate:!1}:P);return}A.labelHoldLate||yt.current||(yt.current=window.setTimeout(()=>{yt.current=0,C(P=>P.labelPending.size===0||P.labelHoldLate?P:{...P,labelHoldLate:!0})},z0))},[C,A.labelPending,A.labelHoldLate]);const Ct=S.useRef(e);Ct.current=e;const Nn=S.useRef({id:e,epoch:0});Nn.current.id!==e&&(Nn.current={id:e,epoch:Nn.current.epoch+1});const zi=S.useRef(null);zi.current===null&&(zi.current=S0());const Wi=S.useRef(!1),Ln=S.useRef(null),[Ia,np]=S.useState(0);S.useEffect(()=>{const P=A.transcript,z=ut(P);if(!e||!a||!P.orderNeedsReconcile&&(!P.journalGeneration||z.length===0)||Wi.current)return;const ee=D=>({fields:JSON.stringify([Ia,e,D.viewEpoch,Xe(D),D.orderNeedsReconcile,D.orderWantedGeneration,ut(D)]),demand:D.orderDemand}),ve=ee(P);if(Ln.current?.fields===ve.fields&&Ln.current.demand===ve.demand)return;Ln.current=ve;const Z=e,Fe=P.viewEpoch;Wi.current=!0;let Ee=null,ae=P;const Oe=D=>{if(!D.peer||Ct.current!==Z||O.current.transcript.viewEpoch!==Fe||p.current!==D.streamEpoch)return;const pe=D.kind==="authority"?D.frame.payload.history:D.page,ge=pe.journal_order_state;if(ge==="ready"){g.current&&(window.clearTimeout(g.current),g.current=0),C(Ie=>{const Se=Jr(Ie.transcript,!1);return Se===Ie.transcript?Ie:{...Ie,transcript:Se}});return}if(ge==="unavailable"){if(g.current&&(window.clearTimeout(g.current),g.current=0),pe.reconcile===!0)return;C(Ie=>{const Se=Jr(Ie.transcript,!0);return Se===Ie.transcript?Ie:{...Ie,transcript:Se}});return}if(ge!=="building")return;g.current&&(window.clearTimeout(g.current),g.current=0);const he=++y.current;g.current=window.setTimeout(()=>{g.current=0,y.current===he&&Ct.current===Z&&O.current.transcript.viewEpoch===Fe&&p.current===D.streamEpoch&&C(Ie=>{const Se=Jr(Ie.transcript,!0);return Se===Ie.transcript?Ie:{...Ie,transcript:Se}})},$0)};R_({getTranscript:()=>O.current.transcript,isCurrent:()=>Ct.current===Z&&O.current.transcript.viewEpoch===Fe,sweep:(D,pe)=>{if(!k())return;if(D.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${Z}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const ge=D.journalGeneration;if(typeof ge!="string"||ge.length===0)return{kind:"none",path:`/v1/desktop/sessions/${Z}/history`,query:new URLSearchParams};if(Fd(D,pe?.("lookup")).length>0){const Se=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:ge});return{kind:"lookup",path:`/v1/desktop/sessions/${Z}/history`,query:Se}}if(Do(D).length>0){const Se=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:ge});return{kind:"payload",path:`/v1/desktop/sessions/${Z}/history`,query:Se}}return{kind:"none",path:`/v1/desktop/sessions/${Z}/history`,query:new URLSearchParams}},read:async(D,pe)=>{ae=O.current.transcript,Ln.current=ee(ae);const ge=k(),he=p.current;if(pe==="lookup"||pe==="payload"){const Se=O.current.transcript.journalGeneration,Lr=await Re({op:"sessions.history",sessionId:Z,limit:100,journalOrder:!0,orderIds:D,peerJournalSource:!0,sourceRead:pe==="payload"?"payload":"metadata",...typeof Se=="string"&&Se.length>0?{expectedJournalGeneration:Se}:{}});return pe==="payload"?{kind:"payload",page:Lr,peer:ge,streamEpoch:he}:{kind:"lookup",page:Lr,peer:ge,streamEpoch:he}}return{kind:"authority",frame:await Re({op:"sessions.get",sessionId:Z,journalOrder:!0,orderIds:D,...ge?{peerJournalSource:!0}:{}}),peer:ge,streamEpoch:he}},page:D=>D.kind==="authority"?D.frame.payload.history:D.page,lookupPath:`/v1/desktop/sessions/${Z}`,commit:(D,pe,ge)=>{D.peer&&p.current!==D.streamEpoch||(C(he=>Ct.current!==Z||Xe(he.transcript)!==pe||he.transcript.viewEpoch!==Fe?he:{...he,transcript:D.kind==="authority"?D.peer?il(he.transcript,D.frame.payload.history,{authoritative:!0,orderRead:ge}):Tw(he.transcript,D.frame.payload.history,ge):D.kind==="payload"?Cw(he.transcript,D.page,ge,pe):il(he.transcript,D.page,{authoritative:!1})}),Oe(D))}}).then(D=>{Ee=D.kind==="complete"?D.transcript:null}).catch(D=>{console.warn("[canonical] source-order reconcile refused",D)}).finally(()=>{Wi.current=!1;const D=O.current.transcript,pe=Ee??ae;Ee&&Ct.current===Z&&D.viewEpoch===Fe&&!D.orderNeedsReconcile&&(Ln.current=ee(pe)),(Ct.current!==Z||D.viewEpoch!==Fe||Xe(D)!==Xe(pe)||D.orderWantedGeneration!==pe.orderWantedGeneration||D.orderNeedsReconcile!==pe.orderNeedsReconcile||D.orderDemand!==pe.orderDemand||JSON.stringify(ut(D))!==JSON.stringify(ut(pe)))&&np(ge=>ge+1)})},[C,e,a,k,A.transcript,Ia]);const Nr=S.useCallback(async()=>{const P=zi.current;if(!e||!P)return{kind:"nothing-to-load"};const z=e,ee=Nn.current.epoch,ve=()=>Nn.current.epoch===ee,Z=O.current.transcript.viewEpoch,Fe=()=>O.current.transcript.viewEpoch===Z,Ee=await P.load(`${z}#${ee}`,{getTranscript:()=>O.current.transcript,readPage:ae=>Re({op:"sessions.history",sessionId:z,beforeId:ae,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(O.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>ve()&&Fe(),commit:ae=>C(Oe=>{const D=ae(Oe.transcript);return D===Oe.transcript?Oe:{...Oe,transcript:D}}).transcript,setLoading:ae=>{ve()&&C(Oe=>Oe.loadingOlder===ae?Oe:{...Oe,loadingOlder:ae})},peerSource:E});return ve()&&(Ee.kind==="failed"?C(ae=>ae.olderFailed?ae:{...ae,olderFailed:!0}):Ee.kind==="applied"&&C(ae=>ae.olderFailed?{...ae,olderFailed:!1}:ae)),Ee},[C,e,k,E]),xa=S.useCallback(async()=>(await Nr()).kind==="applied",[Nr]),Zi=S.useRef(!1),Ra=S.useCallback(async(P,z)=>{if(!e||Zi.current)return!1;const ee=e;Zi.current=!0;const ve=Xe(O.current.transcript),Z=q.current,Fe=Z?{epoch:Z.epoch,seq:Z.seq}:null;try{const Ee=await Re({op:"sessions.history",sessionId:ee,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(O.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}});return Ct.current!==ee||Xe(O.current.transcript)!==ve||O.current.transcript.viewEpoch!==z?!1:(C(ae=>Xe(ae.transcript)!==ve?ae:{...ae,transcript:ir(ae.transcript,Ee,{keepPaging:!0,peerSource:E(),readWitness:Fe})}),xs(se.current,Ee.entries),ei(me.current,Ee.entries),Jw(Ee.entries,P))}catch{return!1}finally{Zi.current=!1}},[C,e,k,E]);S.useEffect(()=>r?nS(r,z=>{C(ee=>{const ve=z(ee.transcript);return ve===ee.transcript?ee:{...ee,transcript:ve}})}):void 0,[C,r]),S.useEffect(()=>{r&&tS(r,A.transcript)},[r,A.transcript]);const Ta=S.useCallback(()=>{C(P=>({...P,transcript:Zw(P.transcript),olderFailed:!1,heldFrontend:null}))},[C]),Ca=S.useCallback(()=>{Bi.current?.()},[]),Aa=S.useCallback(()=>{Gi.current?.()},[]),Oa=S.useCallback(()=>{Hi.current?.()},[]),Pa=S.useCallback((P,z="info")=>{C(ee=>({...ee,transcript:Yw(ee.transcript,P,z)}))},[C]),ja=S.useCallback(P=>{C(z=>({...z,pendingModel:P}))},[C]),Ma=S.useCallback(()=>{C(P=>P.pendingModel===null?P:{...P,pendingModel:null})},[C]);return S.useEffect(()=>{const P=A.pendingModel;if(!P)return;const z=bs(P);if(!z)return;const ee=A.frontend;(bs(ee?.selected_model)===z||bs(ee?.effective_model)===z)&&C(ve=>({...ve,pendingModel:null}))},[C,A.frontend,A.pendingModel]),S.useEffect(()=>{if(!A.pendingModel)return;const P=window.setTimeout(()=>C(z=>({...z,pendingModel:null})),M0);return()=>window.clearTimeout(P)},[C,A.pendingModel]),S.useMemo(()=>({...A,awaitingHydration:t&&!!e&&n&&!A.hydrated,loadOlder:xa,loadOlderDetailed:Nr,refreshTail:Ra,clearView:Ta,addNote:Pa,paintPendingModel:ja,clearPendingModel:Ma,retry:Ca,rehydrate:Oa,reloadFromHistory:Aa}),[A,t,e,n,xa,Nr,Ra,Ta,Pa,ja,Ma,Ca,Oa,Aa])}function Pi(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
41
41
 
42
42
  `)?e:`${t}
43
43
 
44
- ${e}`}const Rs={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function si(e,t,n){const r=[...e.attachments??[]],i=[],s=[],a=new Set;for(const p of t.attachments){const g=r.find(m=>m.path===p&&!a.has(m.id));if(g){a.add(g.id),s.push(g.id);continue}const y={id:n(),path:p};i.push(y),s.push(y.id)}const c=[...e.replies??[]],l=t.replies.filter(p=>!c.some(g=>g.id===p.id)),d=t.text,u=[...i,...r],f=[...l,...c];return{...e,attachments:u,replies:f,textRevision:(e.textRevision??0)+1,volatilePendingText:e.volatilePendingText===!0||t.volatileText===!0,pendingText:d===""?e.pendingText:Pi(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:s,replyIds:t.replies.map(p=>f.find(g=>g.id===p.id)?.id).filter(p=>p!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function iS(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 i=0;i+r<=n.length;i++)if(t.includes(n.slice(i,i+r)))return!0;return!1}function sS(e){return{text:Pi(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function oS(e,t){if(!e||!t)return!1;const n=sS(e),r=e.attachments??[],i=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((s,a)=>s.id===t.chipIds[a])&&i.length===t.replyIds.length&&i.every((s,a)=>s.id===t.replyIds[a])}function aS(e,t=()=>crypto.randomUUID()){const n={};for(const[r,i]of Object.entries(e??{}))n[r]=i.inFlight?si(i,i.inFlight,t):i;return n}function cS(e,t){const n=t.text,r=Pi(e.currentInput??"",e.pendingText??"");let i=r,s="overlap";n===""?s="draft-only":r.startsWith(n)&&(i=r.slice(n.length).replace(/^\n+/,""),s="draft-only");const a=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:i,pendingText:void 0,attachments:(e.attachments??[]).filter(l=>!a.has(l.id)),replies:(e.replies??[]).filter(l=>!c.has(l.id)),unredactedChars:n===""?e.unredactedChars??0:0},box:s}}const Le=Ar()(Ti((e,t)=>({inputByConversation:{},addReply:(n,r)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=Array.isArray(i.replies)?i.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...i,replies:[...s,r]}}})},removeReply:(n,r)=>{const i=t().inputByConversation[n];i&&e({inputByConversation:{...t().inputByConversation,[n]:{...i,replies:i.replies.filter(s=>s.id!==r)}}})},clearReplies:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:[]}}})},addAttachment:(n,r)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=Array.isArray(i.attachments)?i.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...i,attachments:[...s,r]}}})},removeAttachment:(n,r)=>{const i=t().inputByConversation[n];i&&e({inputByConversation:{...t().inputByConversation,[n]:{...i,attachments:i.attachments.filter(s=>s.id!==r)}}})},clearAttachments:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[]}}})},setCurrentInput:(n,r,i=0)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...s,lateDelivered:s.lateDelivered==="overlap"&&!iS(s,r)?void 0:s.lateDelivered,currentInput:r,unredactedChars:r?i:0}}})},getUnredactedChars:n=>t().inputByConversation[n]?.unredactedChars||0,getCurrentInput:n=>t().inputByConversation[n]?.currentInput||"",addSubmittedMessage:(n,r)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=i.submittedMessages[i.submittedMessages.length-1],a=r&&r!==s?[...i.submittedMessages.slice(-19),r]:i.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...i,submittedMessages:a}}})},getSubmittedMessages:n=>t().inputByConversation[n]?.submittedMessages||[],clearSubmittedMessages:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,submittedMessages:[]}}})},getCurrentHistoryIndex:n=>t().inputByConversation[n]?.currentHistoryIndex??null,setCurrentHistoryIndex:(n,r)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=i.submittedMessages;let a=null;typeof r=="number"&&s.length>0&&(a=Math.max(0,Math.min(r,s.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...i,currentHistoryIndex:a}}})},resetCurrentHistoryIndex:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentHistoryIndex:null}}})},clearAll:n=>{const{[n]:r,...i}=t().inputByConversation;e({inputByConversation:i})},restoreRow:(n,r)=>{e({inputByConversation:{...t().inputByConversation,[n]:{...r,textRevision:(r.textRevision??0)+1}}})},beginInFlight:(n,r,i=!0)=>{const s=t().inputByConversation[n]??Rs,a=new Set(r.attachments.map(d=>d.id)),c=new Set(r.replies.map(d=>d.id)),l=s.currentInput===r.text;e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:l?"":s.currentInput,unredactedChars:l?0:s.unredactedChars,textRevision:l?(s.textRevision??0)+1:s.textRevision,attachments:(s.attachments??[]).filter(d=>!a.has(d.id)),replies:(s.replies??[]).filter(d=>!c.has(d.id)),inFlight:i?{text:r.text,attachments:r.attachments.map(d=>d.path),replies:[...r.replies],unredactedChars:l?s.unredactedChars:0,volatileText:r.volatileText}:s.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const r={...t().inputByConversation};let i=!1;for(const s of n){const a=r[s];!a||!a.inFlight&&!a.returned||(r[s]={...a,inFlight:void 0,returned:void 0},i=!0)}i&&e({inputByConversation:r})},returnInFlight:(n,r)=>{const i={...t().inputByConversation},s=i[n],a=s?.inFlight??i[r]?.inFlight;let c=i[r]??Rs;n!==r&&s&&(c=si(c,{text:s.currentInput??"",attachments:(s.attachments??[]).map(l=>l.path),replies:s.replies??[],unredactedChars:s.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:i[r]?.returned},delete i[n]),a&&(c=si(c,a,()=>crypto.randomUUID())),!(!a&&n===r)&&(i[r]=c,e({inputByConversation:i}))},adoptReturnedText:n=>{const r=t().inputByConversation[n];if(r?.pendingText===void 0)return null;const i=Pi(r.currentInput??"",r.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:i,pendingText:void 0,textRevision:(r.textRevision??0)+1}}}),i},returnPayload:(n,r)=>{const i=t().inputByConversation[n]??Rs;i.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:si(i,r,()=>crypto.randomUUID())}})},reconcileDelivered:n=>{const r=t().inputByConversation[n];if(!r)return;const i=f=>(f.currentInput??"")===""&&(f.attachments??[]).length===0&&(f.replies??[]).length===0,s=r.returned!==void 0||r.inFlight!==void 0,a=r.returned?oS(r,r.returned):i(r),c=r.returned?cS(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&&!i(c.row)?{...c.row,returned:void 0,inFlight:void 0,volatilePendingText:d?void 0:r.volatilePendingText,lateDelivered:c.box==="overlap"&&d?"draft-only":c.box,lateDeliveredText:c.box==="overlap"&&!d?r.returned?.text:void 0,textRevision:(r.textRevision??0)+1}:{...r,returned:void 0,inFlight:void 0,lateDelivered:s&&r.returned?.text?"overlap":s?"delivered":void 0,lateDeliveredText:s?r.returned?.text:void 0};e({inputByConversation:{...t().inputByConversation,[n]:a||c!==null&&i(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 i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...i,currentInput:r,unredactedChars:i.unredactedChars??0,textRevision:(i.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:aS(e?.inputByConversation)})}));function lf(e){if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null}function hT(e,t){return t?e.filter(n=>n.session_id===t&&df(n)).length:0}function df(e){if(lf(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function lS(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function mT(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 gT={cwd:""};function dS(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,lS(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function uS(e){return(await Re({op:"sessions.preview",requestId:crypto.randomUUID(),cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}})).frontend}function _T(e,t){const n=e.trim();if(!n)return{checked:!0,rung:null,confirmation:i=>`This conversation will run ${i}.`};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(i=>i.trim().toLowerCase()===n.toLowerCase());return r?{checked:!0,rung:r,confirmation:i=>`This conversation will run ${i} at ${r} effort.`}:{checked:!0,rung:null,confirmation:i=>t.level?`This conversation will run ${i}. Its effort is now ${t.level}, because ${n} is not one of that model's levels.`:`This conversation will run ${i}. No effort level is set on it, because ${n} is not one of that model's levels.`}}function yT(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 bT="Fast mode is off: this version of the Local Operator service cannot carry it.",vT="fast_unavailable";function ia(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function wT(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function ST(e){const t=e instanceof ye?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 kT(e,t){const n={...e,model:ia(e.model,t)};return{queryKey:dS(n),queryFn:()=>uS(n),placeholderData:hp,staleTime:3e4,retry:!1}}function Q(e){return typeof e=="string"?e.trim():""}function yn(e){const t=Q(e);return t||null}function Wt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function qn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function uf(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function sn(e,t){return typeof e=="boolean"?e:t}function po(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function jn(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 jn(t)}return[]}function fS(e){if(!Lt(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:uf(e.attempts),last_frame_at:Wt(e.last_frame_at),next_retry_at:Wt(e.next_retry_at),last_error:Q(e.last_error)}}function Lt(e){return typeof e=="object"&&e!==null}const pS=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function hS(e,t){const n=Q(e);return pS.includes(n)?n:t?"reachable":"unreachable_legacy"}const mS=["running","not_listening","unknown"];function gS(e){const t=Q(e);return mS.includes(t)?t:void 0}function _S(e){if(Array.isArray(e))return e.filter(Lt).map(t=>({endpoint:Q(t.endpoint),connected:t.connected===!0,detail:Q(t.detail),latency_ms:Wt(t.latency_ms)})).filter(t=>t.endpoint!=="")}function ET(e){const t=new Set,n=[];for(const a of jn(e)){const c=Q(a.device_id);if(!c||t.has(c)||typeof a.reachable!="boolean")continue;t.add(c);const l=gS(a.remote_relay),d=_S(a.attempts),u=a.reachable?void 0:fS(a.redial);n.push({device_id:c,name:Q(a.name),reachable:a.reachable,link_state:hS(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:yn(a.unreachable_reason??a.reason),last_seen_at:Wt(a.last_seen_at),session_count:qn(a.session_count),rtt_ms:Wt(a.rtt_ms)})}const r=Lt(e)?e:{},i=Q(r.self_device_id),s=po(r.degraded);return{peers:n,...i?{self_device_id:i}:{},...s.length?{degraded:s}:{}}}function yS(e){const t=Q(e.device_id);return t?{device_id:t,name:Q(e.name),role:Q(e.role),capabilities:po(e.capabilities),active:sn(e.active,!0),suspect:sn(e.suspect,!1),endpoints:po(e.endpoints),last_seen_at:Wt(e.last_seen_at),reachable:sn(e.reachable,!0),reason:Q(e.reason??e.unreachable_reason),scope:Q(e.scope)}:null}function bS(e){const t=Q(e.network_id);return t?{network_id:t,name:Q(e.name),epoch:uf(e.epoch),trust:Q(e.trust),members:jn(e.members).map(yS).filter(n=>n!==null)}:null}function IT(e){const t=Lt(e)?e:{},n=Q(t.self_device_id);return{networks:jn(t.networks).map(bS).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function vS(e){return e.live_state.trim().toLowerCase()==="busy"}function xT(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const i of jn(r)){const s=Q(i.id);if(!s||n.has(s))continue;const a=i.locality==="remote"?"remote":Q(i.locality)==="local"?"local":null;if(!a)continue;n.add(s);const c=Lt(i.status)?{code:Q(i.status.code),label:Q(i.status.label)}:null,l=Lt(i.binding)?{agent:yn(i.binding.agent),team:yn(i.binding.team)}:null,d=Lt(i.opened_by)?{agent:yn(i.opened_by.agent),label:yn(i.opened_by.label),session:yn(i.opened_by.session)}:null;t.push({id:s,name:Q(i.name),mtime:Wt(i.mtime)??0,locality:a,owner_device:Q(i.owner_device),owner_device_name:Q(i.owner_device_name),reachable:sn(i.reachable,!0),unreachable_reason:Q(i.unreachable_reason),live_state:Q(i.live_state),archived:sn(i.archived,!1),created_at:Wt(i.created_at),pinned:sn(i.pinned,!1),...typeof i.active=="boolean"?{active:i.active}:{},waiting_on:qn(i.waiting_on),jobs_running:qn(i.jobs_running),subagents_running:qn(i.subagents_running),subagents_queued:qn(i.subagents_queued),...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function RT(e){const{id:t,name:n,mtime:r,...i}=e;return{...i,session_id:t,title:n,updated_at:r}}function TT(e){if(!Lt(e))return null;const t=Q(e.session_id);if(!t)return null;const n=e.mode==="keep"?"keep":"move",r=Q(e.new_session_id)||(n==="move"?t:"");return r?{locality:e.locality==="local"?"local":"remote",owner_device:Q(e.owner_device),source_retired:sn(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:jn(e.phases).map(i=>({phase:Q(i.phase),peer:Q(i.peer),progress:typeof i.progress=="number"?i.progress:0}))}:null}const wS=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function CT(e){const t=e,n=Q(t?.code)||"move_refused",r=typeof t?.status=="number"?t.status:null;return{code:n,sentence:Q(t?.message)||h("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||wS.has(n)}}function AT(e){const t=Q(e.name);return t||h("ui.mesh.mesh_types.device_suffix",{suffix:Q(e.device_id).slice(-6)})}function SS(e){const t=Q(e.name);return t?JSON.stringify(t):h("ui.mesh.mesh_types.unnamed_device")}function kS(e,t){const n=Q(e);if(!t)return n;const r=t.map(Q).filter(s=>s.length>0&&s!==n);let i=Math.min(10,n.length);for(;i<n.length&&r.some(s=>s.startsWith(n.slice(0,i)));)i+=1;return i<n.length?`${n.slice(0,i)}…`:n}function OT(e,t,n=!1){const r=n?kS(e.id,t):Q(e.id);return`${SS(e)} ${r}`}function PT(e){const t=Q(e.name);return t||h("ui.mesh.mesh_types.network_suffix",{suffix:Q(e.network_id).slice(-6)})}const ES=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function IS(e){const t=e.trim();return t!==""&&ES.includes(t)}function ff(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"||IS(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const jT=()=>h("ui.mesh.mesh_graph.identity_suspect");function pf(e){switch(e){case"self":return h("ui.mesh.mesh_drop.this_device");case"reached":return h("ui.mesh.mesh_reach.reached");case"relay-down":return h("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return h("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return h("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return h("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return h("ui.mesh.mesh_reach.not_a_member");case"unanswered":return h("ui.mesh.mesh_reach.no_answer");case"not-attempted":return h("ui.mesh.mesh_reach.not_asked");default:return h("ui.mesh.mesh_reach.unknown")}}function MT(e){const t=ff(e),n=pf(t);return e.reason?`${n} — ${e.reason}`:n}const DT={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"},NT={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function LT(e){const t=e.trim();switch(t){case"ok":return h("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return h("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return h("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return h("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return h("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?h("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function $T(e){return e.reachable?"":e.remoteRelay==="not_listening"?h("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?h("ui.mesh.mesh_reach.peer_closed_handshake"):""}function UT(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>vS(r))?"working":"idle",source:"derived"}}function xS(e,t){const n={...e};for(const[r,i]of Object.entries(t))(!n[r]||i.at>=n[r].at)&&(n[r]=i);return n}function RS(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=ff({state:"unreachable",reachable:n.reachable,reason:n.reason??"",sessionCount:n.session_count??null}),i=r==="unanswered",s=i&&n.redial_state==="reconnecting";return e.peer_reach===r&&e.link_down===i&&(e.link_reconnecting??!1)===s&&e.reachable===n.reachable&&e.last_seen_at===n.last_seen_at&&e.link_down_reason===n.reason?e:{...e,reachable:n.reachable,link_down:i,link_reconnecting:s,peer_reach:r,last_seen_at:n.last_seen_at,link_down_reason:n.reason}}function FT(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${h("ui.chat.canonical.transcript.reconnecting")} · ${ho(n,t)}`:h("ui.presence.link_down_last_seen",{age:ho(n,t)})}function ho(e,t){if(e===null)return h("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?h("ui.presence.just_now"):n<3600?h("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?h("ui.presence.hours_ago",{count:Math.floor(n/3600)}):h("ui.presence.days_ago",{count:Math.floor(n/86400)})}function BT(e,t){if(e.link_reconnecting===!0)return h("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return h("ui.presence.link_down_compact",{age:ho(n,t)})}function TS(e,t,n,r){if(r<=n)return{facts:e,watermark:n,removed:[]};const i=Object.fromEntries(Object.entries(e).filter(([,s])=>s.at>r));for(const[s,a]of Object.entries(t))(!i[s]||a.at>=i[s].at)&&(i[s]=a);return{facts:i,watermark:r,removed:Object.keys(e).filter(s=>!i[s])}}function GT(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?pf(e.peer_reach):null}function HT(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?h("ui.chat.canonical.untitled"):n==="this chat"?h("ui.chat.canonical.this_chat"):n:t==="this_chat"?h("ui.chat.canonical.this_chat"):h("ui.chat.canonical.untitled")}function mo(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 ti=(e,t)=>e instanceof ye?jo(e,t):e instanceof Error?e.message:t,ji="session_unvalidated",CS=()=>h("ui.common.errors.session_unvalidated"),ki="leading_slash_message",hf=()=>h("ui.common.errors.leading_slash_message");function AS(e,t){return e instanceof ye&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const mf="attachment_read_failed",gf="store_out_of_space",_f="store_unavailable";function Al(e){return e===gf||e===_f}const OS="answer_not_sent",yf="aside_not_answered",bf="aside_still_answering";function er(e){return e===ki||e===mf||e===gf||e===_f||e===OS||e===yf||e===bf||e===ji||e===xi}function PS(e){return e instanceof ye&&e.status===409&&sa(e)===void 0}function vf(e,t=!1){return DS(e)||PS(e)&&!t?"not_sent":e instanceof ye&&e.status===404?"gone":"unknown"}function sa(e){if(e instanceof ye||e instanceof Ht)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const Ge={get unconfirmed(){return h("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return h("ui.chat.canonical.send_failure.unreachable")},get busy(){return h("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return h("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return h("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return h("ui.chat.canonical.send_failure.retiring")},get notReady(){return h("ui.chat.canonical.send_failure.not_ready")},get generic(){return h("ui.chat.canonical.send_failure.generic")},get gone(){return h("ui.chat.canonical.send_failure.gone")},get sendLock(){return h("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return h("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return h("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return h("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return h("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return h("ui.chat.canonical.send_failure.late_delivery_overlap")}};function zT(e){return e?Ge.gateLock:Ge.sendLock}const WT=()=>h("ui.common.actions.retry"),ZT=()=>h("ui.common.actions.clear");function jS(e,t,n=!1){const r=vf(e,n),i=t??sa(e),s=jo(e,Ge.generic);return r==="gone"?{message:Ge.gone,retry:!1,code:i}:r==="not_sent"?i===xi?{message:Ge.busy,retry:!0,code:i}:i===vd?{message:Ge.retiring,retry:!0,code:i}:i===ji?{message:Ge.notReady,retry:!er(i),code:i}:i===yf?{message:Ge.asideNotAnswered,retry:!1,code:i}:i===bf?{message:Ge.asideStillAnswering,retry:!1,code:i}:i===ki?{message:hf(),retry:!1,code:i}:{message:s,retry:!1,code:i}:i===qe.transportFailed?{message:Ge.unreachable,retry:!0,code:i}:Ri(i)?{message:Po(i),retry:!1,code:i}:i===Oo?{message:Ge.unconfirmed,retry:!er(i),code:i}:i===cg.runtimeUnreachable?{message:Ge.unconfirmed,retry:!0,code:i}:i?{message:s,retry:!er(i),code:i}:{message:Ge.unconfirmed,retry:!er(i),code:i}}function go(e){return e.trim()}function KT(e,t){if(t.length===0)return go(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
44
+ ${e}`}const Rs={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function si(e,t,n){const r=[...e.attachments??[]],i=[],s=[],a=new Set;for(const p of t.attachments){const g=r.find(m=>m.path===p&&!a.has(m.id));if(g){a.add(g.id),s.push(g.id);continue}const y={id:n(),path:p};i.push(y),s.push(y.id)}const c=[...e.replies??[]],l=t.replies.filter(p=>!c.some(g=>g.id===p.id)),d=t.text,u=[...i,...r],f=[...l,...c];return{...e,attachments:u,replies:f,textRevision:(e.textRevision??0)+1,volatilePendingText:e.volatilePendingText===!0||t.volatileText===!0,pendingText:d===""?e.pendingText:Pi(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:s,replyIds:t.replies.map(p=>f.find(g=>g.id===p.id)?.id).filter(p=>p!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function cS(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 i=0;i+r<=n.length;i++)if(t.includes(n.slice(i,i+r)))return!0;return!1}function lS(e){return{text:Pi(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function dS(e,t){if(!e||!t)return!1;const n=lS(e),r=e.attachments??[],i=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((s,a)=>s.id===t.chipIds[a])&&i.length===t.replyIds.length&&i.every((s,a)=>s.id===t.replyIds[a])}function uS(e,t=()=>crypto.randomUUID()){const n={};for(const[r,i]of Object.entries(e??{}))n[r]=i.inFlight?si(i,i.inFlight,t):i;return n}function fS(e,t){const n=t.text,r=Pi(e.currentInput??"",e.pendingText??"");let i=r,s="overlap";n===""?s="draft-only":r.startsWith(n)&&(i=r.slice(n.length).replace(/^\n+/,""),s="draft-only");const a=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:i,pendingText:void 0,attachments:(e.attachments??[]).filter(l=>!a.has(l.id)),replies:(e.replies??[]).filter(l=>!c.has(l.id)),unredactedChars:n===""?e.unredactedChars??0:0},box:s}}const Le=Ar()(Ti((e,t)=>({inputByConversation:{},addReply:(n,r)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=Array.isArray(i.replies)?i.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...i,replies:[...s,r]}}})},removeReply:(n,r)=>{const i=t().inputByConversation[n];i&&e({inputByConversation:{...t().inputByConversation,[n]:{...i,replies:i.replies.filter(s=>s.id!==r)}}})},clearReplies:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:[]}}})},addAttachment:(n,r)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=Array.isArray(i.attachments)?i.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...i,attachments:[...s,r]}}})},removeAttachment:(n,r)=>{const i=t().inputByConversation[n];i&&e({inputByConversation:{...t().inputByConversation,[n]:{...i,attachments:i.attachments.filter(s=>s.id!==r)}}})},clearAttachments:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[]}}})},setCurrentInput:(n,r,i=0)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...s,lateDelivered:s.lateDelivered==="overlap"&&!cS(s,r)?void 0:s.lateDelivered,currentInput:r,unredactedChars:r?i:0}}})},getUnredactedChars:n=>t().inputByConversation[n]?.unredactedChars||0,getCurrentInput:n=>t().inputByConversation[n]?.currentInput||"",addSubmittedMessage:(n,r)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=i.submittedMessages[i.submittedMessages.length-1],a=r&&r!==s?[...i.submittedMessages.slice(-19),r]:i.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...i,submittedMessages:a}}})},getSubmittedMessages:n=>t().inputByConversation[n]?.submittedMessages||[],clearSubmittedMessages:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,submittedMessages:[]}}})},getCurrentHistoryIndex:n=>t().inputByConversation[n]?.currentHistoryIndex??null,setCurrentHistoryIndex:(n,r)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=i.submittedMessages;let a=null;typeof r=="number"&&s.length>0&&(a=Math.max(0,Math.min(r,s.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...i,currentHistoryIndex:a}}})},resetCurrentHistoryIndex:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentHistoryIndex:null}}})},clearAll:n=>{const{[n]:r,...i}=t().inputByConversation;e({inputByConversation:i})},restoreRow:(n,r)=>{e({inputByConversation:{...t().inputByConversation,[n]:{...r,textRevision:(r.textRevision??0)+1}}})},beginInFlight:(n,r,i=!0)=>{const s=t().inputByConversation[n]??Rs,a=new Set(r.attachments.map(d=>d.id)),c=new Set(r.replies.map(d=>d.id)),l=s.currentInput===r.text;e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:l?"":s.currentInput,unredactedChars:l?0:s.unredactedChars,textRevision:l?(s.textRevision??0)+1:s.textRevision,attachments:(s.attachments??[]).filter(d=>!a.has(d.id)),replies:(s.replies??[]).filter(d=>!c.has(d.id)),inFlight:i?{text:r.text,attachments:r.attachments.map(d=>d.path),replies:[...r.replies],unredactedChars:l?s.unredactedChars:0,volatileText:r.volatileText}:s.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const r={...t().inputByConversation};let i=!1;for(const s of n){const a=r[s];!a||!a.inFlight&&!a.returned||(r[s]={...a,inFlight:void 0,returned:void 0},i=!0)}i&&e({inputByConversation:r})},returnInFlight:(n,r)=>{const i={...t().inputByConversation},s=i[n],a=s?.inFlight??i[r]?.inFlight;let c=i[r]??Rs;n!==r&&s&&(c=si(c,{text:s.currentInput??"",attachments:(s.attachments??[]).map(l=>l.path),replies:s.replies??[],unredactedChars:s.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:i[r]?.returned},delete i[n]),a&&(c=si(c,a,()=>crypto.randomUUID())),!(!a&&n===r)&&(i[r]=c,e({inputByConversation:i}))},adoptReturnedText:n=>{const r=t().inputByConversation[n];if(r?.pendingText===void 0)return null;const i=Pi(r.currentInput??"",r.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:i,pendingText:void 0,textRevision:(r.textRevision??0)+1}}}),i},returnPayload:(n,r)=>{const i=t().inputByConversation[n]??Rs;i.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:si(i,r,()=>crypto.randomUUID())}})},reconcileDelivered:n=>{const r=t().inputByConversation[n];if(!r)return;const i=f=>(f.currentInput??"")===""&&(f.attachments??[]).length===0&&(f.replies??[]).length===0,s=r.returned!==void 0||r.inFlight!==void 0,a=r.returned?dS(r,r.returned):i(r),c=r.returned?fS(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&&!i(c.row)?{...c.row,returned:void 0,inFlight:void 0,volatilePendingText:d?void 0:r.volatilePendingText,lateDelivered:c.box==="overlap"&&d?"draft-only":c.box,lateDeliveredText:c.box==="overlap"&&!d?r.returned?.text:void 0,textRevision:(r.textRevision??0)+1}:{...r,returned:void 0,inFlight:void 0,lateDelivered:s&&r.returned?.text?"overlap":s?"delivered":void 0,lateDeliveredText:s?r.returned?.text:void 0};e({inputByConversation:{...t().inputByConversation,[n]:a||c!==null&&i(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 i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...i,currentInput:r,unredactedChars:i.unredactedChars??0,textRevision:(i.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:uS(e?.inputByConversation)})}));function df(e){if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null}function yT(e,t){return t?e.filter(n=>n.session_id===t&&uf(n)).length:0}function uf(e){if(df(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function pS(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function bT(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 vT={cwd:""};function hS(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,pS(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function mS(e){return(await Re({op:"sessions.preview",requestId:crypto.randomUUID(),cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}})).frontend}function wT(e,t){const n=e.trim();if(!n)return{checked:!0,rung:null,confirmation:i=>`This conversation will run ${i}.`};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(i=>i.trim().toLowerCase()===n.toLowerCase());return r?{checked:!0,rung:r,confirmation:i=>`This conversation will run ${i} at ${r} effort.`}:{checked:!0,rung:null,confirmation:i=>t.level?`This conversation will run ${i}. Its effort is now ${t.level}, because ${n} is not one of that model's levels.`:`This conversation will run ${i}. No effort level is set on it, because ${n} is not one of that model's levels.`}}function ST(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 kT="Fast mode is off: this version of the Local Operator service cannot carry it.",ET="fast_unavailable";function ia(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function IT(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function xT(e){const t=e instanceof ye?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 RT(e,t){const n={...e,model:ia(e.model,t)};return{queryKey:hS(n),queryFn:()=>mS(n),placeholderData:mp,staleTime:3e4,retry:!1}}function Q(e){return typeof e=="string"?e.trim():""}function yn(e){const t=Q(e);return t||null}function Wt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function qn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function ff(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function sn(e,t){return typeof e=="boolean"?e:t}function po(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function jn(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 jn(t)}return[]}function gS(e){if(!Lt(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:ff(e.attempts),last_frame_at:Wt(e.last_frame_at),next_retry_at:Wt(e.next_retry_at),last_error:Q(e.last_error)}}function Lt(e){return typeof e=="object"&&e!==null}const _S=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function yS(e,t){const n=Q(e);return _S.includes(n)?n:t?"reachable":"unreachable_legacy"}const bS=["running","not_listening","unknown"];function vS(e){const t=Q(e);return bS.includes(t)?t:void 0}function wS(e){if(Array.isArray(e))return e.filter(Lt).map(t=>({endpoint:Q(t.endpoint),connected:t.connected===!0,detail:Q(t.detail),latency_ms:Wt(t.latency_ms)})).filter(t=>t.endpoint!=="")}function TT(e){const t=new Set,n=[];for(const a of jn(e)){const c=Q(a.device_id);if(!c||t.has(c)||typeof a.reachable!="boolean")continue;t.add(c);const l=vS(a.remote_relay),d=wS(a.attempts),u=a.reachable?void 0:gS(a.redial);n.push({device_id:c,name:Q(a.name),reachable:a.reachable,link_state:yS(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:yn(a.unreachable_reason??a.reason),last_seen_at:Wt(a.last_seen_at),session_count:qn(a.session_count),rtt_ms:Wt(a.rtt_ms)})}const r=Lt(e)?e:{},i=Q(r.self_device_id),s=po(r.degraded);return{peers:n,...i?{self_device_id:i}:{},...s.length?{degraded:s}:{}}}function SS(e){const t=Q(e.device_id);return t?{device_id:t,name:Q(e.name),role:Q(e.role),capabilities:po(e.capabilities),active:sn(e.active,!0),suspect:sn(e.suspect,!1),endpoints:po(e.endpoints),last_seen_at:Wt(e.last_seen_at),reachable:sn(e.reachable,!0),reason:Q(e.reason??e.unreachable_reason),scope:Q(e.scope)}:null}function kS(e){const t=Q(e.network_id);return t?{network_id:t,name:Q(e.name),epoch:ff(e.epoch),trust:Q(e.trust),members:jn(e.members).map(SS).filter(n=>n!==null)}:null}function CT(e){const t=Lt(e)?e:{},n=Q(t.self_device_id);return{networks:jn(t.networks).map(kS).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function ES(e){return e.live_state.trim().toLowerCase()==="busy"}function AT(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const i of jn(r)){const s=Q(i.id);if(!s||n.has(s))continue;const a=i.locality==="remote"?"remote":Q(i.locality)==="local"?"local":null;if(!a)continue;n.add(s);const c=Lt(i.status)?{code:Q(i.status.code),label:Q(i.status.label)}:null,l=Lt(i.binding)?{agent:yn(i.binding.agent),team:yn(i.binding.team)}:null,d=Lt(i.opened_by)?{agent:yn(i.opened_by.agent),label:yn(i.opened_by.label),session:yn(i.opened_by.session)}:null;t.push({id:s,name:Q(i.name),mtime:Wt(i.mtime)??0,locality:a,owner_device:Q(i.owner_device),owner_device_name:Q(i.owner_device_name),reachable:sn(i.reachable,!0),unreachable_reason:Q(i.unreachable_reason),live_state:Q(i.live_state),archived:sn(i.archived,!1),created_at:Wt(i.created_at),pinned:sn(i.pinned,!1),...typeof i.active=="boolean"?{active:i.active}:{},waiting_on:qn(i.waiting_on),jobs_running:qn(i.jobs_running),subagents_running:qn(i.subagents_running),subagents_queued:qn(i.subagents_queued),...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function OT(e){const{id:t,name:n,mtime:r,...i}=e;return{...i,session_id:t,title:n,updated_at:r}}function PT(e){if(!Lt(e))return null;const t=Q(e.session_id);if(!t)return null;const n=e.mode==="keep"?"keep":"move",r=Q(e.new_session_id)||(n==="move"?t:"");return r?{locality:e.locality==="local"?"local":"remote",owner_device:Q(e.owner_device),source_retired:sn(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:jn(e.phases).map(i=>({phase:Q(i.phase),peer:Q(i.peer),progress:typeof i.progress=="number"?i.progress:0}))}:null}const IS=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function jT(e){const t=e,n=Q(t?.code)||"move_refused",r=typeof t?.status=="number"?t.status:null;return{code:n,sentence:Q(t?.message)||h("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||IS.has(n)}}function MT(e){const t=Q(e.name);return t||h("ui.mesh.mesh_types.device_suffix",{suffix:Q(e.device_id).slice(-6)})}function xS(e){const t=Q(e.name);return t?JSON.stringify(t):h("ui.mesh.mesh_types.unnamed_device")}function RS(e,t){const n=Q(e);if(!t)return n;const r=t.map(Q).filter(s=>s.length>0&&s!==n);let i=Math.min(10,n.length);for(;i<n.length&&r.some(s=>s.startsWith(n.slice(0,i)));)i+=1;return i<n.length?`${n.slice(0,i)}…`:n}function DT(e,t,n=!1){const r=n?RS(e.id,t):Q(e.id);return`${xS(e)} ${r}`}function NT(e){const t=Q(e.name);return t||h("ui.mesh.mesh_types.network_suffix",{suffix:Q(e.network_id).slice(-6)})}const TS=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function CS(e){const t=e.trim();return t!==""&&TS.includes(t)}function pf(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"||CS(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const LT=()=>h("ui.mesh.mesh_graph.identity_suspect");function hf(e){switch(e){case"self":return h("ui.mesh.mesh_drop.this_device");case"reached":return h("ui.mesh.mesh_reach.reached");case"relay-down":return h("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return h("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return h("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return h("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return h("ui.mesh.mesh_reach.not_a_member");case"unanswered":return h("ui.mesh.mesh_reach.no_answer");case"not-attempted":return h("ui.mesh.mesh_reach.not_asked");default:return h("ui.mesh.mesh_reach.unknown")}}function $T(e){const t=pf(e),n=hf(t);return e.reason?`${n} — ${e.reason}`:n}const UT={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"},FT={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function BT(e){const t=e.trim();switch(t){case"ok":return h("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return h("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return h("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return h("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return h("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?h("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function GT(e){return e.reachable?"":e.remoteRelay==="not_listening"?h("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?h("ui.mesh.mesh_reach.peer_closed_handshake"):""}function HT(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>ES(r))?"working":"idle",source:"derived"}}function AS(e,t){const n={...e};for(const[r,i]of Object.entries(t))(!n[r]||i.at>=n[r].at)&&(n[r]=i);return n}function OS(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=pf({state:"unreachable",reachable:n.reachable,reason:n.reason??"",sessionCount:n.session_count??null}),i=r==="unanswered",s=i&&n.redial_state==="reconnecting";return e.peer_reach===r&&e.link_down===i&&(e.link_reconnecting??!1)===s&&e.reachable===n.reachable&&e.last_seen_at===n.last_seen_at&&e.link_down_reason===n.reason?e:{...e,reachable:n.reachable,link_down:i,link_reconnecting:s,peer_reach:r,last_seen_at:n.last_seen_at,link_down_reason:n.reason}}function zT(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${h("ui.chat.canonical.transcript.reconnecting")} · ${ho(n,t)}`:h("ui.presence.link_down_last_seen",{age:ho(n,t)})}function ho(e,t){if(e===null)return h("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?h("ui.presence.just_now"):n<3600?h("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?h("ui.presence.hours_ago",{count:Math.floor(n/3600)}):h("ui.presence.days_ago",{count:Math.floor(n/86400)})}function WT(e,t){if(e.link_reconnecting===!0)return h("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return h("ui.presence.link_down_compact",{age:ho(n,t)})}function PS(e,t,n,r){if(r<=n)return{facts:e,watermark:n,removed:[]};const i=Object.fromEntries(Object.entries(e).filter(([,s])=>s.at>r));for(const[s,a]of Object.entries(t))(!i[s]||a.at>=i[s].at)&&(i[s]=a);return{facts:i,watermark:r,removed:Object.keys(e).filter(s=>!i[s])}}function ZT(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?hf(e.peer_reach):null}function KT(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?h("ui.chat.canonical.untitled"):n==="this chat"?h("ui.chat.canonical.this_chat"):n:t==="this_chat"?h("ui.chat.canonical.this_chat"):h("ui.chat.canonical.untitled")}function mo(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 ti=(e,t)=>e instanceof ye?jo(e,t):e instanceof Error?e.message:t,ji="session_unvalidated",jS=()=>h("ui.common.errors.session_unvalidated"),ki="leading_slash_message",mf=()=>h("ui.common.errors.leading_slash_message");function MS(e,t){return e instanceof ye&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const gf="attachment_read_failed",_f="store_out_of_space",yf="store_unavailable";function Al(e){return e===_f||e===yf}const DS="answer_not_sent",bf="aside_not_answered",vf="aside_still_answering";function er(e){return e===ki||e===gf||e===_f||e===yf||e===DS||e===bf||e===vf||e===ji||e===xi}function NS(e){return e instanceof ye&&e.status===409&&sa(e)===void 0}function wf(e,t=!1){return US(e)||NS(e)&&!t?"not_sent":e instanceof ye&&e.status===404?"gone":"unknown"}function sa(e){if(e instanceof ye||e instanceof Ht)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const Ge={get unconfirmed(){return h("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return h("ui.chat.canonical.send_failure.unreachable")},get busy(){return h("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return h("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return h("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return h("ui.chat.canonical.send_failure.retiring")},get notReady(){return h("ui.chat.canonical.send_failure.not_ready")},get generic(){return h("ui.chat.canonical.send_failure.generic")},get gone(){return h("ui.chat.canonical.send_failure.gone")},get sendLock(){return h("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return h("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return h("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return h("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return h("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return h("ui.chat.canonical.send_failure.late_delivery_overlap")}};function VT(e){return e?Ge.gateLock:Ge.sendLock}const YT=()=>h("ui.common.actions.retry"),QT=()=>h("ui.common.actions.clear");function LS(e,t,n=!1){const r=wf(e,n),i=t??sa(e),s=jo(e,Ge.generic);return r==="gone"?{message:Ge.gone,retry:!1,code:i}:r==="not_sent"?i===xi?{message:Ge.busy,retry:!0,code:i}:i===vd?{message:Ge.retiring,retry:!0,code:i}:i===ji?{message:Ge.notReady,retry:!er(i),code:i}:i===bf?{message:Ge.asideNotAnswered,retry:!1,code:i}:i===vf?{message:Ge.asideStillAnswering,retry:!1,code:i}:i===ki?{message:mf(),retry:!1,code:i}:{message:s,retry:!1,code:i}:i===qe.transportFailed?{message:Ge.unreachable,retry:!0,code:i}:Ri(i)?{message:Po(i),retry:!1,code:i}:i===Oo?{message:Ge.unconfirmed,retry:!er(i),code:i}:i===lg.runtimeUnreachable?{message:Ge.unconfirmed,retry:!0,code:i}:i?{message:s,retry:!er(i),code:i}:{message:Ge.unconfirmed,retry:!er(i),code:i}}function go(e){return e.trim()}function XT(e,t){if(t.length===0)return go(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
45
45
  `);return go(`${n}
46
- ${e}`)}function _o(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function MS(e,t,n,r){if(t.peer!==void 0||n?.locality==="remote"||r?.locality==="remote")return!1;const i=t.submittedAt;if(i===void 0||i<=0)return!1;const s=e[0]?.ts;return s===void 0||s<=0?!1:s*1e3<=i}function VT(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,s])=>_o(s,t));return(r.find(([,s])=>s.submittedText!==void 0||s.undelivered!==void 0||s.error!==void 0||s.admissionAttempted===!0||s.pending===!0)??r[0])?.[0]??`send:${t}`}function oa(e,t){return t??e??void 0}function wf(e,t,n){return e?t??void 0:n??void 0}function YT(e,t,n){return oa(e,wf(e,t,n))}function DS(e){return e instanceof ye?e.status===413||e.status===422?!0:e.code===xi||e.code===vd||e.code===qe.noCredential||Al(e.code):e instanceof Ht&&(e.code===ji||e.code===mf||Al(e.code))}function jr(e,t){const n=e.startsWith("send:")?e.slice(5):null;return oa(e.startsWith("draft:")?e:null,t??n)??e}function NS(e,t){const n=Le.getState(),r=jr(e,t),i=r===""||r===e?[e]:[e,r];n.settleInFlight(i),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function QT(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=jr(e,t.sessionId);return Le.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),Ke.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:Ge.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!er(t.heldClaimCode),heldClaimCode:void 0}),!0}function JT(e,t){if(!t)return!1;const n=t.undelivered,r=t.submittedText,i=r!==void 0&&t.error!==void 0&&t.errorRetry!==void 0;if(!n&&!i)return!1;const s=jr(e,t.sessionId);if(n){if(Tl(s,n.recordId))return!1;const c=cf(s,n.recordId);return c!=="unseen"?(c==="owner"&&Ke.getState().retractUndelivered(e,n.recordId),!1):(lo(s,{id:n.recordId,text:n.text,images:[],documents:mo(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const a=t.admissionRequestId;return Tl(s,a)?!1:(lo(s,{id:a,text:t.submittedRendered??r,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${a}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type})),documents:mo(t.submittedFiles??[],a)}),!0)}function Ol(e,t,n){tS(jr(e,t),n)}function LS(e,t,n){if(e.submittedText!==t)return!1;const r=e.submittedAttachments??[];return r.length!==n.length?!1:r.every((i,s)=>i===n[s])}function $S(e,t){return!!t&&e===t}const US=3,FS=5e3,BS=2e3;async function GS(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=US||!(n instanceof ye)||n.code!==xi)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??BS),FS);await new Promise(i=>setTimeout(i,r))}}async function HS(e){await GS(async()=>{await Re(e)})}async function XT(e,t,n,r,i){const s=Ke.getState();if($S(s.validatingSessionId,n))throw new Ht(CS(),ji);const a=s.drafts[e];if(a?.pending)return null;const c=go(t.text),l=a?.submittedText!==void 0&&LS(a,c,t.attachments),d=a??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?a?.submittedImages??t.images:t.images,f=l?a?.submittedFiles??t.files:t.files,p=l?a?.submittedMode??t.mode:t.mode,g=l&&a?a.submittedInputMode:t.inputMode,y=l&&a?a.submittedInputPath:t.inputPath,m=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),b=Date.now();s.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:m,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:p,submittedInputMode:g,submittedInputPath:y,error:void 0,errorCode:void 0,submittedAt:b});const _=oa(e.startsWith("draft:")?e:null,n??d.sessionId)??null;_&&lo(_,{id:m,submittedAt:b,text:c,images:u.map(($,O)=>({id:`${m}:${O}`,data:$.data_b64,attachment:null,mimeType:$.mime_type})),documents:mo(f??[],m),onPainted:r});let k=l,E=n??d.sessionId,A=null;try{if(!E){if(A="sessions.create",E=await s.createSession(t.cwd,d.target,d.createRequestId,ia(d.model??null,s.draftFastCarries),d.warmId,d.peer)??void 0,!E)throw new Ht(Ke.getState().error??h("ui.common.errors.chat_start_simple"));s.updateDraft(e,{sessionId:E}),_&&Q0(_,E),s.fetchSessions()}const $=l&&a?.submittedRendered!==void 0?a.submittedRendered:i?await i(E)??c:c;return k=!0,s.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:$}),E&&Y0(E,m,$),A="sessions.message",await HS({op:"sessions.message",sessionId:E,requestId:m,text:$,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:p,inputMode:g,inputPath:y}),s.finishDraft(e,E),Ke.setState({error:null}),E}catch($){Ke.setState({error:null});const O=l&&a?.admissionAttempted===!0,C=vf($,O),I=A==="sessions.message"&&AS($,c),N=I?ki:sa($),F=jS($,N,O);let se=!1;const me=E??_??void 0;if(me&&C==="unknown"&&(se=k&&cf(me,m)==="owner"),s.updateDraft(e,{pending:!1,admissionAttempted:C==="unknown"&&k,errorCode:N,error:F.message,errorRetry:F.retry}),se)return E?(s.finishDraft(e,E),E):null;const w=jr(e,E??d.sessionId),le=_&&_!==w?[_,w]:[w];throw Le.getState().settleInFlight(le),_&&_!==w&&Le.getState().returnInFlight(_,w),me&&fo(me,m),e!==me&&fo(e,m),I?new ye(422,hf(),$,ki):$}}const Sf=50,Pl="activity",zS=25,WS=500;function ZS(e){return e?Sf:WS}function jl(e,t){return`${e}:${t}`}function KS(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function VS(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function YS(e,t){const n=new Set;for(const[r,i]of Object.entries(t))i.locality==="remote"&&n.add(r);for(const r of e)r.locality==="remote"&&n.add(r.session_id);return n}function QS(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 JS(e){const t=new Set(e.tailIds),n=new Set(e.keepIds??[]),r=new Set(e.page.map(c=>c.session_id)),i=e.sessions.filter(c=>r.has(c.session_id)?!1:e.scopeIds.has(c.session_id)||n.has(c.session_id)?!0:t.has(c.session_id)),s=e.merge(e.sessions,e.page),a=new Set(s.map(c=>c.session_id));for(const c of i)a.has(c.session_id)||(a.add(c.session_id),s.push(c));return{rows:s,tailIds:e.tailIds.filter(c=>a.has(c))}}function XS(e){const t=[...e.previousIds],n=new Set(t);for(const s of e.page)n.has(s.session_id)||(n.add(s.session_id),t.push(s.session_id));const r=[...e.sessions],i=new Map(r.map((s,a)=>[s.session_id,a]));for(const s of e.page){const a=i.get(s.session_id);if(a===void 0){i.set(s.session_id,r.length),r.push(s);continue}r[a]=e.merge(r[a],s)}return{rows:r,ids:t}}function Jt(e,t){return{...e,...t,...tk(e,t),...nk(t,e),attention:wn(e?.attention,t.attention,t.session_id)}}const qT=lf,qS=e=>e.filter(df),Ml=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const i=e[r],s=wn(i.attention,n,t);if(s===i.attention)return e;const a=e.slice();return a[r]={...i,attention:s},a},ek=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function tk(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 nk(e,t){const n=typeof t?.status_epoch=="string"&&t.status_epoch===e.status_epoch,r=t?.status_revision,i=e.status_revision;return t?.status!==void 0&&n&&typeof r=="number"&&typeof i=="number"&&r>i?{status:t?.status,status_revision:t?.status_revision,status_epoch:t?.status_epoch}:{}}function rk(e,t){const n={};let r=!1;for(const[i,s]of Object.entries(e)){if(s.at<t){r=!0;continue}n[i]=s}return r?n:e}function Ts(e,t){const n={...e.archiveFacts};delete n[t];const r={...e.placementFacts};delete r[t];const i=e.answerSeq+1;return{sessions:e.sessions.filter(s=>s.session_id!==t),archiveFacts:n,placementFacts:r,answerSeq:i,forgotten:{...e.forgotten,[t]:{at:i,title:e.sessions.find(s=>s.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function kf(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 Ef(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 If(e,t,n){const r=Le.getState();if(t&&t!==e){r.adoptReturnedText(t);const i=Le.getState().inputByConversation[t];i&&i.inFlight===void 0&&((i.currentInput??"")!==""||(i.attachments?.length??0)>0)&&r.returnInFlight(t,e)}n&&r.returnPayload(e,{text:n.text,attachments:n.attachments,replies:[]})}function ik(e,t,n){const r=Le.getState(),i=n??(e?r.getCurrentInput(e):"");i&&r.setComposerText(t,i),e&&e!==t&&r.setComposerText(e,"")}function sk(e,t){let n=null;const r=[];for(const[i,s]of Object.entries(e))!s.sessionId||t[s.sessionId]===void 0||(n??={...e},n[i]=kf(s),r.push({key:i,sessionId:s.sessionId,payload:Ef(s)}));return{drafts:n??e,restored:r}}function xf(e){return e.map(({id:t,name:n,mtime:r,...i})=>({...i,session_id:t,title:n,updated_at:r}))}function Dl(e,t){return xf(e).filter(n=>t[n.session_id]===void 0)}function Cs(e){return typeof e=="string"&&e.length>0?e:null}function ok(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),i=n(t.active),s=n(t.unbound);if(r===null||i===null||s===null||!Array.isArray(t.scopes))return null;const a=[];for(const c of t.scopes){if(c===null||typeof c!="object")return null;const l=c;if(l.kind!=="team"&&l.kind!=="agent"||typeof l.name!="string"||l.name.length===0)continue;const d=n(l.total),u=n(l.active);d===null||u===null||a.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:r,active:i,unbound:s,scopes:a}}function ak(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Jt(n.get(r.session_id),r)])).values()]}let As=0,gn=null;function ck(e,t,n){const r=gn;if(r)return r.invalidated=!0,r.limit=e,r.withCounts=t,r.promise;const i={limit:e,withCounts:t,invalidated:!1,promise:null};return gn=i,i.promise=(async()=>{try{for(;;){i.invalidated=!1;let s;try{s=await n(i.limit,i.withCounts)}catch(a){if(i.invalidated)continue;throw a}if(!i.invalidated)return gn===i&&(gn=null),s}}finally{gn===i&&(gn=null)}})(),i.promise}function Rf(){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 lk(){const e=Rf();return e.kind==="session"?e.sessionId:null}function dk(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 uk(e,t){const n={...t,...e},{drafts:r,restored:i}=sk(n.drafts,n.forgotten),s=r===n.drafts?n:{...n,drafts:r};for(const l of i)If(l.key,l.sessionId,l.payload);const a=Rf();if(a.kind==="session")return{...s,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...s,activeSessionId:null};const c=dk(s);return c?{...s,...c}:s}const Ke=Ar()(Ti((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:lk(),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 i=Object.entries(r.drafts);return i.some(([,s])=>!s.sessionId)?{cwd:n,drafts:Object.fromEntries(i.map(([s,a])=>a.sessionId?[s,a]:[s,{...a,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=ZS(t().cataloguePageable),r=!1)=>{const i=++As,s=t().answerSeq+1;e({answerSeq:s}),e({loading:!0,error:null});try{const a=await ck(n,r,(l,d)=>Re({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:Pl}:{}}));if(i!==As)return;const c=xf(a.sessions);e(l=>{const d={...l.pinFacts};for(const[I,N]of Object.entries(d))N.at>=s||delete d[I];const u=new Set(c.map(I=>I.session_id));let f=!1;const p={...l.forgotten};for(const[I,N]of Object.entries(p))N.at<s&&u.has(I)&&(delete p[I],f=!0);const g=f?p:l.forgotten,y=c.filter(I=>g[I.session_id]===void 0);let m=null;for(const I of y){const N=l.placementFacts[I.session_id];if(N===void 0||N.at>=s)continue;const F=I.locality==="remote"?"remote":I.locality==="local"?"local":null;F!==null&&(m??={...l.placementFacts},m[I.session_id]={locality:F,owner_device:typeof I.owner_device=="string"?I.owner_device:"",at:l.answerSeq+1})}const b=Cs(a.next_cursor),_=b===null&&a.truncated!==!0,k=y.map(I=>I.session_id),E=l.sessions.filter(I=>g[I.session_id]===void 0&&(l.pinFacts[I.session_id]?.at??-1)>=s),A=JS({sessions:l.sessions,scopeIds:KS(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...VS(l.placementFacts)],tailIds:_?[]:l.head.tailIds,page:y,merge:ak});let $=A.rows;for(const I of E){const N=l.pinFacts[I.session_id],F=$.findIndex(se=>se.session_id===I.session_id);F===-1?$=[...$,{...I,pinned:N.pinned}]:$[F]={...$[F],pinned:N.pinned}}const O=rk(l.archiveFacts,s),C=ok(a.counts);return{sessions:$,pinFacts:d,archiveFacts:O,...m===null?{}:{placementFacts:m,answerSeq:l.answerSeq+1},forgotten:g,loading:!1,truncated:a.truncated===!0,head:{pageIds:k,tailIds:A.tailIds,nextCursor:b,tailCursor:_?null:l.head.tailStarted?l.head.tailCursor:b,tailStarted:l.head.tailStarted,complete:_,loading:!1,error:null,at:s},...C===null?{}:{counts:C},statusUnavailable:Array.isArray(a.degraded)?a.degraded.filter(I=>typeof I=="string"):[]}})}catch(a){i===As&&e({loading:!1,error:ti(a,h("ui.common.errors.chats_refresh"))})}},fetchCatalogueTail:async()=>{const n=t().head,r=n.tailCursor;if(!(r===null||n.loading)){e(i=>({head:{...i.head,loading:!0,error:null,tailStarted:!0,tailCursor:r}}));try{const i=await Re({op:"sessions.list",limit:Sf,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:Pl}:{}}),s=Dl(i.sessions,t().forgotten);e(a=>{const c=new Map(a.sessions.map((f,p)=>[f.session_id,p])),l=[...a.sessions],d=[];for(const f of s){const p=c.get(f.session_id);if(p===void 0){c.set(f.session_id,l.length),l.push(f),d.push(f.session_id);continue}l[p]=Jt(l[p],f)}const u=Cs(i.next_cursor);return{sessions:l,head:{...a.head,tailIds:[...a.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(i){e(s=>({head:{...s.head,loading:!1,error:ti(i,h("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,i=null,s=zS)=>{const a=jl(n,r);if(t().scopes[a]?.loading)return;const c=t().answerSeq+1;e({answerSeq:c}),e(l=>({scopes:{...l.scopes,[a]:{ids:l.scopes[a]?.ids??[],nextCursor:l.scopes[a]?.nextCursor??null,loading:!0,error:null,at:c}}}));try{const l=await Re({op:"sessions.list",limit:s,include_archived:!1,scope_kind:n,scope_name:r,...i===null?{}:{cursor:i}}),d=Dl(l.sessions,t().forgotten);e(u=>{const f=u.scopes[a];if(f===void 0||f.at!==c)return{};const p=i!==null&&l.cursor_missing!==!0,g=XS({sessions:u.sessions,previousIds:p?f.ids:[],page:d,merge:Jt}),y=Cs(l.next_cursor);return{sessions:g.rows,scopes:{...u.scopes,[a]:{ids:g.ids,nextCursor:y,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[a];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[a]:{...u,loading:!1,error:ti(l,h("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const i=jl(n,r);e(s=>{const a=s.scopes[i];if(a===void 0)return{};const c={...s.scopes};delete c[i];const l=s.activeSessionId,d=new Set(a.ids),u=new Set(s.head.pageIds),f=s.sessions.filter(p=>!d.has(p.session_id)||u.has(p.session_id)||l!==null&&p.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,i=r?t().drafts[r]:void 0;if(!r||!i||i.sessionId||i.warmId)return;Le.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 i={...n.drafts};for(const[a,c]of Object.entries(r.drafts))a in i||(i[a]=c);const s=Le.getState();for(const[a,c]of Object.entries(r.composer)){const l=s.inputByConversation[a];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||s.restoreRow(a,c)}return{drafts:i,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,r,i)=>{const s=t().answerSeq+1,a=t().archiveFacts[n]??null,c=i??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:s,archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:s,answered:!1}}}));try{return await Re({op:"sessions.archive",sessionId:n,archived:r}),e(l=>{const u=l.archiveFacts[n]?.at!==s;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:s,answered:!0}},archiveUndo:u?l.archiveUndo:r?{sessionId:n,title:c??void 0,archived:!0,at:s}:null,archiveFailure:l.archiveFailure?.sessionId===n?null:l.archiveFailure}}),!0}catch(l){return e(d=>{const u=d.archiveFacts[n]?.at!==s,f={...d.archiveFacts};return u||(a?.answered===!0?f[n]=a:(delete f[n],a!==null&&t().fetchSessions())),{archiveFacts:u?d.archiveFacts:f,answerSeq:d.answerSeq+1,archiveFailure:{sessionId:n,at:d.answerSeq+1,archived:r,title:c||"",detail:l instanceof ye&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await Re({op:"sessions.delete",sessionId:n,confirmed:!0}),e(r=>Ts(r,n)),t().retireDraftsForSession(n),{ok:!0}}catch(r){const i=r instanceof ye?r.status:null,s=r instanceof ye?r.code??null:null;return i===404?(e(a=>Ts(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:s==="session_delete_refused",detail:r instanceof ye&&r.message?r.message:h("ui.common.errors.conversation_delete")}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,i=crypto.randomUUID(),s,a,c)=>{try{const l=await Re({op:"sessions.create",requestId:i,cwd:n,...r?{target:r}:{},...s?{model:s}:{},...a?{draftId:a}:{},...c?{peer:c}:{}});return t().upsertSession({session_id:l.session_id,cwd:n,binding:l.binding}),c&&t().settlePlacement(l.session_id,{locality:"remote",owner_device:c}),l.session_id}catch(l){throw e({error:ti(l,h("ui.common.errors.chat_start"))}),l}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,r=Date.now())=>e(i=>({stoppedTurns:{...i.stoppedTurns,[n]:r}})),clearTurnStopped:n=>e(r=>{if(!(n in r.stoppedTurns))return r;const{[n]:i,...s}=r.stoppedTurns;return{stoppedTurns:s}}),openDraft:n=>{t().drafts[n]&&e({activeDraftKey:n,activeSessionId:null,validatingSessionId:null,error:null})},confirmSessionLive:n=>{n&&t().validatingSessionId===n&&e({validatingSessionId:null})},confirmSessionMissing:n=>{!n||t().validatingSessionId!==n||(e({validatingSessionId:null,...Ts(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:ek(r.readAckRearm,n)}))},publishReadAckNotice:(n,r,i)=>{e(s=>{const a=s.readAckNotice;return a?.sessionId===n&&a.kind===r?s:{readAckNotice:{sessionId:n,kind:r,revision:(a?.revision??0)+1,reason:i}}})},clearReadAckNotice:n=>{e(r=>r.readAckNotice?.sessionId===n?{readAckNotice:null}:r)},applyAttention:(n,r)=>{e(i=>{const s=Ml(i.sessions,n,r);return s===i.sessions?i:{...i,sessions:s}})},applyAttentionMany:n=>{e(r=>{let i=r.sessions;for(const s of n){const a=s?.conversation_id;typeof a!="string"||!a.startsWith("session/")||(i=Ml(i,a.slice(8),s))}return i===r.sessions?r:{...r,sessions:i}})},markAllRead:async()=>{const n=qS(t().sessions).map(a=>({sessionId:a.session_id,completionToken:a.attention?.completion_token}));if(n.length===0)return{attempted:0,cleared:0,superseded:0,unknown:0,deferred:0};const r=await Re({op:"attention.seen",items:n});t().applyAttentionMany(r.read);const i=YS(t().sessions,t().placementFacts),s=r.unknown.filter(a=>i.has(a)).length;return{attempted:n.length,cleared:r.read.length,superseded:r.superseded.length,unknown:r.unknown.length,deferred:s}},applySessionStatus:(n,r,i,s)=>{e(a=>{const c=a.sessions.findIndex(p=>p.session_id===n);let l=!1;const d=a.sessions.map(p=>{if(p.status_epoch===void 0&&p.status_revision===void 0||p.status_epoch===s)return p;l=!0;const{status_revision:g,status_epoch:y,...m}=p;return m});if(c<0)return l?{...a,sessions:d}:a;const u=d[c],f=u.status?.code===r.code&&u.status?.label===r.label&&u.status_revision===i&&u.status_epoch===s;return f&&!l?a:(f||(d[c]={...u,status:r,status_revision:i,status_epoch:s}),{...a,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 s=(!r&&n?`draft:${n.kind}:${n.name}`:null)??`draft:${crypto.randomUUID()}`,a=t().drafts[s],c=wf(t().activeDraftKey,t().activeDraftKey?t().drafts[t().activeDraftKey]?.sessionId:void 0,t().activeSessionId);if(a?.sessionId&&!a.pending&&a.sessionId!==c){const d=t().drafts[`send:${a.sessionId}`]?`draft:${crypto.randomUUID()}`:`send:${a.sessionId}`;e(u=>{const f={...u.drafts};return delete f[s],f[d]={...a,key:d},{drafts:f}})}const l=t().drafts[s];return e(d=>({activeDraftKey:s,validatingSessionId:null,error:null,drafts:{...d.drafts,[s]:l??{key:s,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),s},restageDraft:(n,r)=>{const i=t().activeDraftKey,s=t().stageDraft(n);return ik(i,s,r),s},startNewChat:n=>{const r=t().stageDraft();return e({activeSessionId:null,validatingSessionId:null}),n&&(Le.getState().adoptReturnedText(n),Le.getState().inputByConversation[n]?.pendingText===void 0&&Le.getState().returnInFlight(n,r)),r},updateDraft:(n,r)=>e(i=>{const s=i.drafts[n],a=r.key!==void 0&&r.createRequestId!==void 0&&r.admissionRequestId!==void 0;return!s&&!a?{}:{drafts:{...i.drafts,[n]:{...i.drafts[n],...r}}}}),setDraftPeer:(n,r)=>e(i=>{const s=i.drafts[n];if(!s)return{};const a=r??void 0;return(s.peer??void 0)===a?{}:{drafts:{...i.drafts,[n]:{...s,peer:a,...s.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}}),setDraftModel:(n,r)=>e(i=>{const s=i.drafts[n];return s?{drafts:{...i.drafts,[n]:{...s,model:r,...s.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}:{}}),ensureDraftWarm:n=>{const r=t();if(!r.draftWarmable)return;const i=r.drafts[n];if(!i||i.sessionId||i.warmId||!r.cwd||i.peer)return;const s=i.draftRequestId??crypto.randomUUID();i.draftRequestId||t().updateDraft(n,{draftRequestId:s});const a=ia(i.model??null,r.draftFastCarries);Re({op:"sessions.draft",requestId:s,cwd:r.cwd,...i.target?{target:i.target}:{},...a?{model:a}:{}}).then(c=>{const l=t().drafts[n];l&&!l.warmId&&!l.sessionId&&l.draftRequestId===s&&t().updateDraft(n,{warmId:c.draft_id})}).catch(()=>{})},finishDraft:(n,r)=>e(i=>{NS(n,r);const s={...i.drafts};return delete s[n],{drafts:s,...i.activeDraftKey===n?{activeDraftKey:null,activeSessionId:r}:{}}}),retireDraftSession:n=>{const r=t().drafts[n];if(!r?.sessionId||r.pending)return;const i=r.sessionId,s=Ef(r);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:kf(c)}}}),If(n,i,s)},retireDraftsForSession:n=>{for(const[r,i]of Object.entries(t().drafts))r.startsWith("draft:")&&i.sessionId===n&&t().retireDraftSession(r)},retireDraftWarm:n=>{const r=Object.entries(t().drafts).filter(([i,s])=>i.startsWith("draft:")&&s.warmId===n&&!s.sessionId);r.length!==0&&e(i=>{const s={...i.drafts};for(const[a]of r){const c=s[a];!c||c.warmId!==n||c.sessionId||(s[a]={...c,warmId:void 0,draftRequestId:crypto.randomUUID()})}return{drafts:s}})},discardDraft:n=>e(r=>{const i={...r.drafts},s=i[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),a=i[n],c=Le.getState().inputByConversation[n];qr(n),s&&s!==n&&qr(s),delete i[n],Le.getState().clearAll(n);const l=a?{at:r.answerSeq+1,keys:[n],drafts:{[n]:a},composer:c?{[n]:c}:{}}:null;return{drafts:i,...l?{answerSeq:l.at,draftsUndo:l}:{},...r.activeDraftKey===n?{activeDraftKey:null}:{}}}),discardDrafts:n=>e(r=>{const i={...r.drafts};let s=!1;const a=[],c={},l={};for(const u of n){if(!(u in i))continue;const f=i[u];if(!f)continue;const p=f.sessionId??(u.startsWith("send:")?u.slice(5):void 0);qr(u),p&&p!==u&&qr(p),a.push(u),c[u]=f;const g=Le.getState().inputByConversation[u];g&&(l[u]=g),delete i[u],Le.getState().clearAll(u),r.activeDraftKey===u&&(s=!0)}if(a.length===0)return{};const d=r.answerSeq+1;return{drafts:i,answerSeq:d,draftsUndo:{at:d,keys:a,drafts:c,composer:l},...s?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,r,i)=>e(s=>{const a=r.map(F=>F.id),c=Object.entries(s.drafts).filter(([,F])=>_o(F,n)&&F.undelivered!==void 0&&a.includes(F.undelivered.recordId));let l=s.drafts;if(c.length>0){l={...l};for(const[F,se]of c){const me=se.undelivered?.recordId,{undelivered:w,...le}=se;l[F]=le,me!==void 0&&Ol(F,se.sessionId,me)}}const d=Object.entries(l).find(([,F])=>_o(F,n)&&F.admissionAttempted===!0&&F.pending!==!0&&F.submittedText!==void 0);if(!d)return c.length>0?{drafts:l}:{};const[u,f]=d,p=f.admissionRequestId,g=a.includes(p);if(!g&&!i)return c.length>0?{drafts:l}:{};if(!g&&!MS(r,f,s.placementFacts[n],s.sessions.find(F=>F.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:y,submittedText:m,submittedAttachments:b,submittedImages:_,submittedMode:k,submittedInputMode:E,submittedInputPath:A,heldClaimCode:$,error:O,errorCode:C,errorRetry:I,...N}=f;return g||fo(n,p),{drafts:{...l,[u]:{...N,...g?{}:{undelivered:{recordId:p,text:m??"",attachments:b??[]}},admissionRequestId:crypto.randomUUID()}}}}),retractUndelivered:(n,r)=>{const i=t().drafts[n];!i||i.undelivered?.recordId!==r||(e(s=>{const{undelivered:a,...c}=s.drafts[n];return{drafts:{...s.drafts,[n]:c}}}),Ol(n,i.sessionId,r))},bindSession:(n,r)=>t().setActiveSession(r),beginAnswer:()=>{const n=t().answerSeq+1;return e({answerSeq:n}),n},applySearchAnswer:(n,r)=>e(i=>{let s=null,a=null,c=null;for(const l of r){const d=i.archiveFacts[l.id];if(d!==void 0&&d.at<n&&(c=c??{...i.archiveFacts},delete c[l.id]),!(d!==void 0&&d.at>=n)&&typeof l.archived=="boolean"&&i.sessions.some(f=>f.session_id===l.id&&f.archived!==l.archived)){a=a??i.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.archived=l.archived===!0)}if(typeof l.pinned!="boolean")continue;const u=i.pinFacts[l.id];if(!(u!==void 0&&u.at>=n)&&(u!==void 0&&(s=s??{...i.pinFacts},delete s[l.id]),i.sessions.some(f=>f.session_id===l.id&&f.pinned!==l.pinned))){a=a??i.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return s===null&&a===null&&c===null?{}:{...s===null?{}:{pinFacts:s},...a===null?{}:{sessions:a},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,r,i)=>{const s=t().sessions.find(p=>p.session_id===n),a=t().pinFacts[n]??null,c=s===void 0?a?.pinned??!1:s.pinned===!0,l=s===void 0&&i!==void 0?{session_id:n,title:i.title||"",updated_at:i.updated_at,pinned:r}:null,d=t().beginAnswer(),u=s?.title??i?.title,f=s?.updated_at??i?.updated_at;e(p=>({sessions:l===null?p.sessions.map(g=>g.session_id===n?{...g,pinned:r}:g):[...p.sessions,l],pinFacts:{...p.pinFacts,[n]:{pinned:r,at:d,title:u,updated_at:f}},pinFailure:null}));try{const p=await Re({op:"sessions.pin",sessionId:n,pinned:r});let g=!1;return e(y=>{const m=y.pinFacts[n];return m===void 0||m.at!==d?{}:(g=!0,{sessions:y.sessions.map(b=>b.session_id===n?{...b,pinned:p.pinned===!0}:b),pinFacts:{...y.pinFacts,[n]:{...m,pinned:p.pinned===!0}}})}),g}catch(p){return e(g=>{const y=g.pinFacts[n];if(y!==void 0&&y.at!==d)return{};const m={...g.pinFacts};return a===null&&s===void 0?delete m[n]:m[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:g.sessions.map(b=>b.session_id===n?{...b,pinned:c}:b),pinFacts:m,pinFailure:{sessionId:n,pinned:r,title:s?.title||"",detail:jo(p,"")}}}),!1}},upsertSession:n=>e(r=>({sessions:r.sessions.some(s=>s.session_id===n.session_id)?r.sessions.map(s=>s.session_id===n.session_id?Jt(s,n):s):[...r.sessions,n]})),settlePlacement:(n,r)=>{const i=t().beginAnswer();e(s=>({sessions:s.sessions.map(a=>a.session_id===n?Jt(a,{session_id:n,locality:r.locality,owner_device:r.owner_device}):a),placementFacts:{...s.placementFacts,[n]:{locality:r.locality,owner_device:r.owner_device,at:i}}}))},settlePeerCatalogue:(n,r,i={},s=void 0)=>{e(a=>{const c={...a.forgotten};for(const I of n)c[I.session_id]?.at<r&&delete c[I.session_id];const l=n.filter(I=>{if(c[I.session_id]||I.locality==="remote"&&a.peerDeviceSnapshotAt>r&&typeof I.owner_device=="string"&&!a.peerDeviceFacts[I.owner_device])return!1;const N=a.placementFacts[I.session_id];return!N||N.at<r}),d={...a.placementFacts},u=new Set;let f=!1,p=0;for(const I of l){const N=I.locality==="remote"?"remote":I.locality==="local"?"local":null;if(N===null)continue;const F=a.placementFacts[I.session_id];if(F!==void 0){if(F.at>=r)continue}else if(N!=="remote")continue;p=p===0?a.answerSeq+1:p,u.add(I.session_id),d[I.session_id]={locality:N,owner_device:N==="remote"&&typeof I.owner_device=="string"?I.owner_device:"",at:p},f=!0}const g=s===void 0?null:TS(a.peerDeviceFacts,i,a.peerDeviceSnapshotAt,s),y=g?.facts??xS(a.peerDeviceFacts,Object.fromEntries(Object.entries(i).filter(([,I])=>I.at>a.peerDeviceSnapshotAt))),m=l.filter(I=>I.locality==="remote");let b=a.sessions,_=!1;const k=[],E=new Map;for(let I=0;I<b.length;I+=1)E.set(b[I].session_id,I);for(const I of m){const N=E.get(I.session_id);if(N===void 0){k.push(I);continue}b[N]!==I&&(_||(b=b.slice(),_=!0),b[N]=Jt(b[N],I))}k.length>0&&(b=[...b,...k]);for(const I of l){if(I.locality==="remote"||!u.has(I.session_id))continue;const N=E.get(I.session_id);N===void 0||b[N]===I||(_||(b=b.slice(),_=!0),b[N]=Jt(b[N],I))}const A=new Set(l.map(I=>I.session_id)),$=new Set;for(const I of l)I.locality==="remote"&&typeof I.owner_device=="string"&&I.owner_device!==""&&I.reachable!==!1&&$.add(I.owner_device);const O=new Set;for(const I of b){if(I.locality!=="remote"||typeof I.owner_device!="string"||!g?.removed.includes(I.owner_device))continue;const N=a.placementFacts[I.session_id];N&&N.at>=(s??0)||(O.add(I.session_id),delete d[I.session_id])}for(const[I,N]of Object.entries(a.placementFacts))N.locality==="remote"&&(A.has(I)||N.at>=r||y[N.owner_device]?.reachable!==!1&&(N.owner_device===""||!$.has(N.owner_device)||(O.add(I),delete d[I])));O.size>0&&(b=b.filter(I=>!O.has(I.session_id)));const C=b.map(I=>RS(I,y));return C.some((I,N)=>I!==b[N])&&(b=C,_=!0),!f&&k.length===0&&!_&&O.size===0&&Object.keys(i).length===0&&s===void 0?{}:{sessions:b,placementFacts:d,peerDeviceFacts:y,peerDeviceSnapshotAt:g?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:uk,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 eC(e,t){return t?e.filter(n=>n.archived!==!0):e}function tC(e,t){let n=!1;const r=e.map(i=>{const s=t[i.session_id];return s===void 0||!s.answered||i.archived===s.archived?i:(n=!0,{...i,archived:s.archived})});return n?r:e}function nC(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function rC(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const iC="This backend cannot archive conversations. Update the backend and try again.",sC="This conversation is already archived. Use /unarchive to restore it.",oC="This conversation is not archived, so there is nothing to restore.",aC="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 cC(e,t,n){return n&&e&&t.trim().length>0}function lC(e,t){return t===e}/**
46
+ ${e}`)}function _o(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function $S(e,t,n,r){if(t.peer!==void 0||n?.locality==="remote"||r?.locality==="remote")return!1;const i=t.submittedAt;if(i===void 0||i<=0)return!1;const s=e[0]?.ts;return s===void 0||s<=0?!1:s*1e3<=i}function JT(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,s])=>_o(s,t));return(r.find(([,s])=>s.submittedText!==void 0||s.undelivered!==void 0||s.error!==void 0||s.admissionAttempted===!0||s.pending===!0)??r[0])?.[0]??`send:${t}`}function oa(e,t){return t??e??void 0}function Sf(e,t,n){return e?t??void 0:n??void 0}function qT(e,t,n){return oa(e,Sf(e,t,n))}function US(e){return e instanceof ye?e.status===413||e.status===422?!0:e.code===xi||e.code===vd||e.code===qe.noCredential||Al(e.code):e instanceof Ht&&(e.code===ji||e.code===gf||Al(e.code))}function jr(e,t){const n=e.startsWith("send:")?e.slice(5):null;return oa(e.startsWith("draft:")?e:null,t??n)??e}function FS(e,t){const n=Le.getState(),r=jr(e,t),i=r===""||r===e?[e]:[e,r];n.settleInFlight(i),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function eC(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=jr(e,t.sessionId);return Le.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),Ke.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:Ge.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!er(t.heldClaimCode),heldClaimCode:void 0}),!0}function tC(e,t){if(!t)return!1;const n=t.undelivered,r=t.submittedText,i=r!==void 0&&t.error!==void 0&&t.errorRetry!==void 0;if(!n&&!i)return!1;const s=jr(e,t.sessionId);if(n){if(Tl(s,n.recordId))return!1;const c=lf(s,n.recordId);return c!=="unseen"?(c==="owner"&&Ke.getState().retractUndelivered(e,n.recordId),!1):(lo(s,{id:n.recordId,text:n.text,images:[],documents:mo(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const a=t.admissionRequestId;return Tl(s,a)?!1:(lo(s,{id:a,text:t.submittedRendered??r,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${a}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type})),documents:mo(t.submittedFiles??[],a)}),!0)}function Ol(e,t,n){sS(jr(e,t),n)}function BS(e,t,n){if(e.submittedText!==t)return!1;const r=e.submittedAttachments??[];return r.length!==n.length?!1:r.every((i,s)=>i===n[s])}function GS(e,t){return!!t&&e===t}const HS=3,zS=5e3,WS=2e3;async function ZS(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=HS||!(n instanceof ye)||n.code!==xi)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??WS),zS);await new Promise(i=>setTimeout(i,r))}}async function KS(e){await ZS(async()=>{await Re(e)})}async function nC(e,t,n,r,i){const s=Ke.getState();if(GS(s.validatingSessionId,n))throw new Ht(jS(),ji);const a=s.drafts[e];if(a?.pending)return null;const c=go(t.text),l=a?.submittedText!==void 0&&BS(a,c,t.attachments),d=a??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?a?.submittedImages??t.images:t.images,f=l?a?.submittedFiles??t.files:t.files,p=l?a?.submittedMode??t.mode:t.mode,g=l&&a?a.submittedInputMode:t.inputMode,y=l&&a?a.submittedInputPath:t.inputPath,m=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),b=Date.now();s.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:m,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:p,submittedInputMode:g,submittedInputPath:y,error:void 0,errorCode:void 0,submittedAt:b});const _=oa(e.startsWith("draft:")?e:null,n??d.sessionId)??null;_&&lo(_,{id:m,submittedAt:b,text:c,images:u.map(($,O)=>({id:`${m}:${O}`,data:$.data_b64,attachment:null,mimeType:$.mime_type})),documents:mo(f??[],m),onPainted:r});let k=l,E=n??d.sessionId,A=null;try{if(!E){if(A="sessions.create",E=await s.createSession(t.cwd,d.target,d.createRequestId,ia(d.model??null,s.draftFastCarries),d.warmId,d.peer)??void 0,!E)throw new Ht(Ke.getState().error??h("ui.common.errors.chat_start_simple"));s.updateDraft(e,{sessionId:E}),_&&eS(_,E),s.fetchSessions()}const $=l&&a?.submittedRendered!==void 0?a.submittedRendered:i?await i(E)??c:c;return k=!0,s.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:$}),E&&q0(E,m,$),A="sessions.message",await KS({op:"sessions.message",sessionId:E,requestId:m,text:$,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:p,inputMode:g,inputPath:y}),s.finishDraft(e,E),Ke.setState({error:null}),E}catch($){Ke.setState({error:null});const O=l&&a?.admissionAttempted===!0,C=wf($,O),I=A==="sessions.message"&&MS($,c),N=I?ki:sa($),F=LS($,N,O);let se=!1;const me=E??_??void 0;if(me&&C==="unknown"&&(se=k&&lf(me,m)==="owner"),s.updateDraft(e,{pending:!1,admissionAttempted:C==="unknown"&&k,errorCode:N,error:F.message,errorRetry:F.retry}),se)return E?(s.finishDraft(e,E),E):null;const w=jr(e,E??d.sessionId),le=_&&_!==w?[_,w]:[w];throw Le.getState().settleInFlight(le),_&&_!==w&&Le.getState().returnInFlight(_,w),me&&fo(me,m),e!==me&&fo(e,m),I?new ye(422,mf(),$,ki):$}}const kf=50,Pl="activity",VS=25,YS=500;function QS(e){return e?kf:YS}function jl(e,t){return`${e}:${t}`}function XS(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function JS(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function qS(e,t){const n=new Set;for(const[r,i]of Object.entries(t))i.locality==="remote"&&n.add(r);for(const r of e)r.locality==="remote"&&n.add(r.session_id);return n}function ek(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 tk(e){const t=new Set(e.tailIds),n=new Set(e.keepIds??[]),r=new Set(e.page.map(c=>c.session_id)),i=e.sessions.filter(c=>r.has(c.session_id)?!1:e.scopeIds.has(c.session_id)||n.has(c.session_id)?!0:t.has(c.session_id)),s=e.merge(e.sessions,e.page),a=new Set(s.map(c=>c.session_id));for(const c of i)a.has(c.session_id)||(a.add(c.session_id),s.push(c));return{rows:s,tailIds:e.tailIds.filter(c=>a.has(c))}}function nk(e){const t=[...e.previousIds],n=new Set(t);for(const s of e.page)n.has(s.session_id)||(n.add(s.session_id),t.push(s.session_id));const r=[...e.sessions],i=new Map(r.map((s,a)=>[s.session_id,a]));for(const s of e.page){const a=i.get(s.session_id);if(a===void 0){i.set(s.session_id,r.length),r.push(s);continue}r[a]=e.merge(r[a],s)}return{rows:r,ids:t}}function Xt(e,t){return{...e,...t,...sk(e,t),...ok(t,e),attention:wn(e?.attention,t.attention,t.session_id)}}const rC=df,rk=e=>e.filter(uf),Ml=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const i=e[r],s=wn(i.attention,n,t);if(s===i.attention)return e;const a=e.slice();return a[r]={...i,attention:s},a},ik=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function sk(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 ok(e,t){const n=typeof t?.status_epoch=="string"&&t.status_epoch===e.status_epoch,r=t?.status_revision,i=e.status_revision;return t?.status!==void 0&&n&&typeof r=="number"&&typeof i=="number"&&r>i?{status:t?.status,status_revision:t?.status_revision,status_epoch:t?.status_epoch}:{}}function ak(e,t){const n={};let r=!1;for(const[i,s]of Object.entries(e)){if(s.at<t){r=!0;continue}n[i]=s}return r?n:e}function Ts(e,t){const n={...e.archiveFacts};delete n[t];const r={...e.placementFacts};delete r[t];const i=e.answerSeq+1;return{sessions:e.sessions.filter(s=>s.session_id!==t),archiveFacts:n,placementFacts:r,answerSeq:i,forgotten:{...e.forgotten,[t]:{at:i,title:e.sessions.find(s=>s.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function Ef(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 If(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 xf(e,t,n){const r=Le.getState();if(t&&t!==e){r.adoptReturnedText(t);const i=Le.getState().inputByConversation[t];i&&i.inFlight===void 0&&((i.currentInput??"")!==""||(i.attachments?.length??0)>0)&&r.returnInFlight(t,e)}n&&r.returnPayload(e,{text:n.text,attachments:n.attachments,replies:[]})}function ck(e,t,n){const r=Le.getState(),i=n??(e?r.getCurrentInput(e):"");i&&r.setComposerText(t,i),e&&e!==t&&r.setComposerText(e,"")}function lk(e,t){let n=null;const r=[];for(const[i,s]of Object.entries(e))!s.sessionId||t[s.sessionId]===void 0||(n??={...e},n[i]=Ef(s),r.push({key:i,sessionId:s.sessionId,payload:If(s)}));return{drafts:n??e,restored:r}}function Rf(e){return e.map(({id:t,name:n,mtime:r,...i})=>({...i,session_id:t,title:n,updated_at:r}))}function Dl(e,t){return Rf(e).filter(n=>t[n.session_id]===void 0)}function Cs(e){return typeof e=="string"&&e.length>0?e:null}function dk(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),i=n(t.active),s=n(t.unbound);if(r===null||i===null||s===null||!Array.isArray(t.scopes))return null;const a=[];for(const c of t.scopes){if(c===null||typeof c!="object")return null;const l=c;if(l.kind!=="team"&&l.kind!=="agent"||typeof l.name!="string"||l.name.length===0)continue;const d=n(l.total),u=n(l.active);d===null||u===null||a.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:r,active:i,unbound:s,scopes:a}}function uk(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Xt(n.get(r.session_id),r)])).values()]}let As=0,gn=null;function fk(e,t,n){const r=gn;if(r)return r.invalidated=!0,r.limit=e,r.withCounts=t,r.promise;const i={limit:e,withCounts:t,invalidated:!1,promise:null};return gn=i,i.promise=(async()=>{try{for(;;){i.invalidated=!1;let s;try{s=await n(i.limit,i.withCounts)}catch(a){if(i.invalidated)continue;throw a}if(!i.invalidated)return gn===i&&(gn=null),s}}finally{gn===i&&(gn=null)}})(),i.promise}function Tf(){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 pk(){const e=Tf();return e.kind==="session"?e.sessionId:null}function hk(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 mk(e,t){const n={...t,...e},{drafts:r,restored:i}=lk(n.drafts,n.forgotten),s=r===n.drafts?n:{...n,drafts:r};for(const l of i)xf(l.key,l.sessionId,l.payload);const a=Tf();if(a.kind==="session")return{...s,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...s,activeSessionId:null};const c=hk(s);return c?{...s,...c}:s}const Ke=Ar()(Ti((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:pk(),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 i=Object.entries(r.drafts);return i.some(([,s])=>!s.sessionId)?{cwd:n,drafts:Object.fromEntries(i.map(([s,a])=>a.sessionId?[s,a]:[s,{...a,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=QS(t().cataloguePageable),r=!1)=>{const i=++As,s=t().answerSeq+1;e({answerSeq:s}),e({loading:!0,error:null});try{const a=await fk(n,r,(l,d)=>Re({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:Pl}:{}}));if(i!==As)return;const c=Rf(a.sessions);e(l=>{const d={...l.pinFacts};for(const[I,N]of Object.entries(d))N.at>=s||delete d[I];const u=new Set(c.map(I=>I.session_id));let f=!1;const p={...l.forgotten};for(const[I,N]of Object.entries(p))N.at<s&&u.has(I)&&(delete p[I],f=!0);const g=f?p:l.forgotten,y=c.filter(I=>g[I.session_id]===void 0);let m=null;for(const I of y){const N=l.placementFacts[I.session_id];if(N===void 0||N.at>=s)continue;const F=I.locality==="remote"?"remote":I.locality==="local"?"local":null;F!==null&&(m??={...l.placementFacts},m[I.session_id]={locality:F,owner_device:typeof I.owner_device=="string"?I.owner_device:"",at:l.answerSeq+1})}const b=Cs(a.next_cursor),_=b===null&&a.truncated!==!0,k=y.map(I=>I.session_id),E=l.sessions.filter(I=>g[I.session_id]===void 0&&(l.pinFacts[I.session_id]?.at??-1)>=s),A=tk({sessions:l.sessions,scopeIds:XS(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...JS(l.placementFacts)],tailIds:_?[]:l.head.tailIds,page:y,merge:uk});let $=A.rows;for(const I of E){const N=l.pinFacts[I.session_id],F=$.findIndex(se=>se.session_id===I.session_id);F===-1?$=[...$,{...I,pinned:N.pinned}]:$[F]={...$[F],pinned:N.pinned}}const O=ak(l.archiveFacts,s),C=dk(a.counts);return{sessions:$,pinFacts:d,archiveFacts:O,...m===null?{}:{placementFacts:m,answerSeq:l.answerSeq+1},forgotten:g,loading:!1,truncated:a.truncated===!0,head:{pageIds:k,tailIds:A.tailIds,nextCursor:b,tailCursor:_?null:l.head.tailStarted?l.head.tailCursor:b,tailStarted:l.head.tailStarted,complete:_,loading:!1,error:null,at:s},...C===null?{}:{counts:C},statusUnavailable:Array.isArray(a.degraded)?a.degraded.filter(I=>typeof I=="string"):[]}})}catch(a){i===As&&e({loading:!1,error:ti(a,h("ui.common.errors.chats_refresh"))})}},fetchCatalogueTail:async()=>{const n=t().head,r=n.tailCursor;if(!(r===null||n.loading)){e(i=>({head:{...i.head,loading:!0,error:null,tailStarted:!0,tailCursor:r}}));try{const i=await Re({op:"sessions.list",limit:kf,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:Pl}:{}}),s=Dl(i.sessions,t().forgotten);e(a=>{const c=new Map(a.sessions.map((f,p)=>[f.session_id,p])),l=[...a.sessions],d=[];for(const f of s){const p=c.get(f.session_id);if(p===void 0){c.set(f.session_id,l.length),l.push(f),d.push(f.session_id);continue}l[p]=Xt(l[p],f)}const u=Cs(i.next_cursor);return{sessions:l,head:{...a.head,tailIds:[...a.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(i){e(s=>({head:{...s.head,loading:!1,error:ti(i,h("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,i=null,s=VS)=>{const a=jl(n,r);if(t().scopes[a]?.loading)return;const c=t().answerSeq+1;e({answerSeq:c}),e(l=>({scopes:{...l.scopes,[a]:{ids:l.scopes[a]?.ids??[],nextCursor:l.scopes[a]?.nextCursor??null,loading:!0,error:null,at:c}}}));try{const l=await Re({op:"sessions.list",limit:s,include_archived:!1,scope_kind:n,scope_name:r,...i===null?{}:{cursor:i}}),d=Dl(l.sessions,t().forgotten);e(u=>{const f=u.scopes[a];if(f===void 0||f.at!==c)return{};const p=i!==null&&l.cursor_missing!==!0,g=nk({sessions:u.sessions,previousIds:p?f.ids:[],page:d,merge:Xt}),y=Cs(l.next_cursor);return{sessions:g.rows,scopes:{...u.scopes,[a]:{ids:g.ids,nextCursor:y,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[a];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[a]:{...u,loading:!1,error:ti(l,h("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const i=jl(n,r);e(s=>{const a=s.scopes[i];if(a===void 0)return{};const c={...s.scopes};delete c[i];const l=s.activeSessionId,d=new Set(a.ids),u=new Set(s.head.pageIds),f=s.sessions.filter(p=>!d.has(p.session_id)||u.has(p.session_id)||l!==null&&p.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,i=r?t().drafts[r]:void 0;if(!r||!i||i.sessionId||i.warmId)return;Le.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 i={...n.drafts};for(const[a,c]of Object.entries(r.drafts))a in i||(i[a]=c);const s=Le.getState();for(const[a,c]of Object.entries(r.composer)){const l=s.inputByConversation[a];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||s.restoreRow(a,c)}return{drafts:i,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,r,i)=>{const s=t().answerSeq+1,a=t().archiveFacts[n]??null,c=i??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:s,archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:s,answered:!1}}}));try{return await Re({op:"sessions.archive",sessionId:n,archived:r}),e(l=>{const u=l.archiveFacts[n]?.at!==s;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:s,answered:!0}},archiveUndo:u?l.archiveUndo:r?{sessionId:n,title:c??void 0,archived:!0,at:s}:null,archiveFailure:l.archiveFailure?.sessionId===n?null:l.archiveFailure}}),!0}catch(l){return e(d=>{const u=d.archiveFacts[n]?.at!==s,f={...d.archiveFacts};return u||(a?.answered===!0?f[n]=a:(delete f[n],a!==null&&t().fetchSessions())),{archiveFacts:u?d.archiveFacts:f,answerSeq:d.answerSeq+1,archiveFailure:{sessionId:n,at:d.answerSeq+1,archived:r,title:c||"",detail:l instanceof ye&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await Re({op:"sessions.delete",sessionId:n,confirmed:!0}),e(r=>Ts(r,n)),t().retireDraftsForSession(n),{ok:!0}}catch(r){const i=r instanceof ye?r.status:null,s=r instanceof ye?r.code??null:null;return i===404?(e(a=>Ts(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:s==="session_delete_refused",detail:r instanceof ye&&r.message?r.message:h("ui.common.errors.conversation_delete")}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,i=crypto.randomUUID(),s,a,c)=>{try{const l=await Re({op:"sessions.create",requestId:i,cwd:n,...r?{target:r}:{},...s?{model:s}:{},...a?{draftId:a}:{},...c?{peer:c}:{}});return t().upsertSession({session_id:l.session_id,cwd:n,binding:l.binding}),c&&t().settlePlacement(l.session_id,{locality:"remote",owner_device:c}),l.session_id}catch(l){throw e({error:ti(l,h("ui.common.errors.chat_start"))}),l}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,r=Date.now())=>e(i=>({stoppedTurns:{...i.stoppedTurns,[n]:r}})),clearTurnStopped:n=>e(r=>{if(!(n in r.stoppedTurns))return r;const{[n]:i,...s}=r.stoppedTurns;return{stoppedTurns:s}}),openDraft:n=>{t().drafts[n]&&e({activeDraftKey:n,activeSessionId:null,validatingSessionId:null,error:null})},confirmSessionLive:n=>{n&&t().validatingSessionId===n&&e({validatingSessionId:null})},confirmSessionMissing:n=>{!n||t().validatingSessionId!==n||(e({validatingSessionId:null,...Ts(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:ik(r.readAckRearm,n)}))},publishReadAckNotice:(n,r,i)=>{e(s=>{const a=s.readAckNotice;return a?.sessionId===n&&a.kind===r?s:{readAckNotice:{sessionId:n,kind:r,revision:(a?.revision??0)+1,reason:i}}})},clearReadAckNotice:n=>{e(r=>r.readAckNotice?.sessionId===n?{readAckNotice:null}:r)},applyAttention:(n,r)=>{e(i=>{const s=Ml(i.sessions,n,r);return s===i.sessions?i:{...i,sessions:s}})},applyAttentionMany:n=>{e(r=>{let i=r.sessions;for(const s of n){const a=s?.conversation_id;typeof a!="string"||!a.startsWith("session/")||(i=Ml(i,a.slice(8),s))}return i===r.sessions?r:{...r,sessions:i}})},markAllRead:async()=>{const n=rk(t().sessions).map(a=>({sessionId:a.session_id,completionToken:a.attention?.completion_token}));if(n.length===0)return{attempted:0,cleared:0,superseded:0,unknown:0,deferred:0};const r=await Re({op:"attention.seen",items:n});t().applyAttentionMany(r.read);const i=qS(t().sessions,t().placementFacts),s=r.unknown.filter(a=>i.has(a)).length;return{attempted:n.length,cleared:r.read.length,superseded:r.superseded.length,unknown:r.unknown.length,deferred:s}},applySessionStatus:(n,r,i,s)=>{e(a=>{const c=a.sessions.findIndex(p=>p.session_id===n);let l=!1;const d=a.sessions.map(p=>{if(p.status_epoch===void 0&&p.status_revision===void 0||p.status_epoch===s)return p;l=!0;const{status_revision:g,status_epoch:y,...m}=p;return m});if(c<0)return l?{...a,sessions:d}:a;const u=d[c],f=u.status?.code===r.code&&u.status?.label===r.label&&u.status_revision===i&&u.status_epoch===s;return f&&!l?a:(f||(d[c]={...u,status:r,status_revision:i,status_epoch:s}),{...a,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 s=(!r&&n?`draft:${n.kind}:${n.name}`:null)??`draft:${crypto.randomUUID()}`,a=t().drafts[s],c=Sf(t().activeDraftKey,t().activeDraftKey?t().drafts[t().activeDraftKey]?.sessionId:void 0,t().activeSessionId);if(a?.sessionId&&!a.pending&&a.sessionId!==c){const d=t().drafts[`send:${a.sessionId}`]?`draft:${crypto.randomUUID()}`:`send:${a.sessionId}`;e(u=>{const f={...u.drafts};return delete f[s],f[d]={...a,key:d},{drafts:f}})}const l=t().drafts[s];return e(d=>({activeDraftKey:s,validatingSessionId:null,error:null,drafts:{...d.drafts,[s]:l??{key:s,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),s},restageDraft:(n,r)=>{const i=t().activeDraftKey,s=t().stageDraft(n);return ck(i,s,r),s},startNewChat:n=>{const r=t().stageDraft();return e({activeSessionId:null,validatingSessionId:null}),n&&(Le.getState().adoptReturnedText(n),Le.getState().inputByConversation[n]?.pendingText===void 0&&Le.getState().returnInFlight(n,r)),r},updateDraft:(n,r)=>e(i=>{const s=i.drafts[n],a=r.key!==void 0&&r.createRequestId!==void 0&&r.admissionRequestId!==void 0;return!s&&!a?{}:{drafts:{...i.drafts,[n]:{...i.drafts[n],...r}}}}),setDraftPeer:(n,r)=>e(i=>{const s=i.drafts[n];if(!s)return{};const a=r??void 0;return(s.peer??void 0)===a?{}:{drafts:{...i.drafts,[n]:{...s,peer:a,...s.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}}),setDraftModel:(n,r)=>e(i=>{const s=i.drafts[n];return s?{drafts:{...i.drafts,[n]:{...s,model:r,...s.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}:{}}),ensureDraftWarm:n=>{const r=t();if(!r.draftWarmable)return;const i=r.drafts[n];if(!i||i.sessionId||i.warmId||!r.cwd||i.peer)return;const s=i.draftRequestId??crypto.randomUUID();i.draftRequestId||t().updateDraft(n,{draftRequestId:s});const a=ia(i.model??null,r.draftFastCarries);Re({op:"sessions.draft",requestId:s,cwd:r.cwd,...i.target?{target:i.target}:{},...a?{model:a}:{}}).then(c=>{const l=t().drafts[n];l&&!l.warmId&&!l.sessionId&&l.draftRequestId===s&&t().updateDraft(n,{warmId:c.draft_id})}).catch(()=>{})},finishDraft:(n,r)=>e(i=>{FS(n,r);const s={...i.drafts};return delete s[n],{drafts:s,...i.activeDraftKey===n?{activeDraftKey:null,activeSessionId:r}:{}}}),retireDraftSession:n=>{const r=t().drafts[n];if(!r?.sessionId||r.pending)return;const i=r.sessionId,s=If(r);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:Ef(c)}}}),xf(n,i,s)},retireDraftsForSession:n=>{for(const[r,i]of Object.entries(t().drafts))r.startsWith("draft:")&&i.sessionId===n&&t().retireDraftSession(r)},retireDraftWarm:n=>{const r=Object.entries(t().drafts).filter(([i,s])=>i.startsWith("draft:")&&s.warmId===n&&!s.sessionId);r.length!==0&&e(i=>{const s={...i.drafts};for(const[a]of r){const c=s[a];!c||c.warmId!==n||c.sessionId||(s[a]={...c,warmId:void 0,draftRequestId:crypto.randomUUID()})}return{drafts:s}})},discardDraft:n=>e(r=>{const i={...r.drafts},s=i[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),a=i[n],c=Le.getState().inputByConversation[n];qr(n),s&&s!==n&&qr(s),delete i[n],Le.getState().clearAll(n);const l=a?{at:r.answerSeq+1,keys:[n],drafts:{[n]:a},composer:c?{[n]:c}:{}}:null;return{drafts:i,...l?{answerSeq:l.at,draftsUndo:l}:{},...r.activeDraftKey===n?{activeDraftKey:null}:{}}}),discardDrafts:n=>e(r=>{const i={...r.drafts};let s=!1;const a=[],c={},l={};for(const u of n){if(!(u in i))continue;const f=i[u];if(!f)continue;const p=f.sessionId??(u.startsWith("send:")?u.slice(5):void 0);qr(u),p&&p!==u&&qr(p),a.push(u),c[u]=f;const g=Le.getState().inputByConversation[u];g&&(l[u]=g),delete i[u],Le.getState().clearAll(u),r.activeDraftKey===u&&(s=!0)}if(a.length===0)return{};const d=r.answerSeq+1;return{drafts:i,answerSeq:d,draftsUndo:{at:d,keys:a,drafts:c,composer:l},...s?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,r,i)=>e(s=>{const a=r.map(F=>F.id),c=Object.entries(s.drafts).filter(([,F])=>_o(F,n)&&F.undelivered!==void 0&&a.includes(F.undelivered.recordId));let l=s.drafts;if(c.length>0){l={...l};for(const[F,se]of c){const me=se.undelivered?.recordId,{undelivered:w,...le}=se;l[F]=le,me!==void 0&&Ol(F,se.sessionId,me)}}const d=Object.entries(l).find(([,F])=>_o(F,n)&&F.admissionAttempted===!0&&F.pending!==!0&&F.submittedText!==void 0);if(!d)return c.length>0?{drafts:l}:{};const[u,f]=d,p=f.admissionRequestId,g=a.includes(p);if(!g&&!i)return c.length>0?{drafts:l}:{};if(!g&&!$S(r,f,s.placementFacts[n],s.sessions.find(F=>F.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:y,submittedText:m,submittedAttachments:b,submittedImages:_,submittedMode:k,submittedInputMode:E,submittedInputPath:A,heldClaimCode:$,error:O,errorCode:C,errorRetry:I,...N}=f;return g||fo(n,p),{drafts:{...l,[u]:{...N,...g?{}:{undelivered:{recordId:p,text:m??"",attachments:b??[]}},admissionRequestId:crypto.randomUUID()}}}}),retractUndelivered:(n,r)=>{const i=t().drafts[n];!i||i.undelivered?.recordId!==r||(e(s=>{const{undelivered:a,...c}=s.drafts[n];return{drafts:{...s.drafts,[n]:c}}}),Ol(n,i.sessionId,r))},bindSession:(n,r)=>t().setActiveSession(r),beginAnswer:()=>{const n=t().answerSeq+1;return e({answerSeq:n}),n},applySearchAnswer:(n,r)=>e(i=>{let s=null,a=null,c=null;for(const l of r){const d=i.archiveFacts[l.id];if(d!==void 0&&d.at<n&&(c=c??{...i.archiveFacts},delete c[l.id]),!(d!==void 0&&d.at>=n)&&typeof l.archived=="boolean"&&i.sessions.some(f=>f.session_id===l.id&&f.archived!==l.archived)){a=a??i.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.archived=l.archived===!0)}if(typeof l.pinned!="boolean")continue;const u=i.pinFacts[l.id];if(!(u!==void 0&&u.at>=n)&&(u!==void 0&&(s=s??{...i.pinFacts},delete s[l.id]),i.sessions.some(f=>f.session_id===l.id&&f.pinned!==l.pinned))){a=a??i.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return s===null&&a===null&&c===null?{}:{...s===null?{}:{pinFacts:s},...a===null?{}:{sessions:a},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,r,i)=>{const s=t().sessions.find(p=>p.session_id===n),a=t().pinFacts[n]??null,c=s===void 0?a?.pinned??!1:s.pinned===!0,l=s===void 0&&i!==void 0?{session_id:n,title:i.title||"",updated_at:i.updated_at,pinned:r}:null,d=t().beginAnswer(),u=s?.title??i?.title,f=s?.updated_at??i?.updated_at;e(p=>({sessions:l===null?p.sessions.map(g=>g.session_id===n?{...g,pinned:r}:g):[...p.sessions,l],pinFacts:{...p.pinFacts,[n]:{pinned:r,at:d,title:u,updated_at:f}},pinFailure:null}));try{const p=await Re({op:"sessions.pin",sessionId:n,pinned:r});let g=!1;return e(y=>{const m=y.pinFacts[n];return m===void 0||m.at!==d?{}:(g=!0,{sessions:y.sessions.map(b=>b.session_id===n?{...b,pinned:p.pinned===!0}:b),pinFacts:{...y.pinFacts,[n]:{...m,pinned:p.pinned===!0}}})}),g}catch(p){return e(g=>{const y=g.pinFacts[n];if(y!==void 0&&y.at!==d)return{};const m={...g.pinFacts};return a===null&&s===void 0?delete m[n]:m[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:g.sessions.map(b=>b.session_id===n?{...b,pinned:c}:b),pinFacts:m,pinFailure:{sessionId:n,pinned:r,title:s?.title||"",detail:jo(p,"")}}}),!1}},upsertSession:n=>e(r=>({sessions:r.sessions.some(s=>s.session_id===n.session_id)?r.sessions.map(s=>s.session_id===n.session_id?Xt(s,n):s):[...r.sessions,n]})),settlePlacement:(n,r)=>{const i=t().beginAnswer();e(s=>({sessions:s.sessions.map(a=>a.session_id===n?Xt(a,{session_id:n,locality:r.locality,owner_device:r.owner_device}):a),placementFacts:{...s.placementFacts,[n]:{locality:r.locality,owner_device:r.owner_device,at:i}}}))},settlePeerCatalogue:(n,r,i={},s=void 0)=>{e(a=>{const c={...a.forgotten};for(const I of n)c[I.session_id]?.at<r&&delete c[I.session_id];const l=n.filter(I=>{if(c[I.session_id]||I.locality==="remote"&&a.peerDeviceSnapshotAt>r&&typeof I.owner_device=="string"&&!a.peerDeviceFacts[I.owner_device])return!1;const N=a.placementFacts[I.session_id];return!N||N.at<r}),d={...a.placementFacts},u=new Set;let f=!1,p=0;for(const I of l){const N=I.locality==="remote"?"remote":I.locality==="local"?"local":null;if(N===null)continue;const F=a.placementFacts[I.session_id];if(F!==void 0){if(F.at>=r)continue}else if(N!=="remote")continue;p=p===0?a.answerSeq+1:p,u.add(I.session_id),d[I.session_id]={locality:N,owner_device:N==="remote"&&typeof I.owner_device=="string"?I.owner_device:"",at:p},f=!0}const g=s===void 0?null:PS(a.peerDeviceFacts,i,a.peerDeviceSnapshotAt,s),y=g?.facts??AS(a.peerDeviceFacts,Object.fromEntries(Object.entries(i).filter(([,I])=>I.at>a.peerDeviceSnapshotAt))),m=l.filter(I=>I.locality==="remote");let b=a.sessions,_=!1;const k=[],E=new Map;for(let I=0;I<b.length;I+=1)E.set(b[I].session_id,I);for(const I of m){const N=E.get(I.session_id);if(N===void 0){k.push(I);continue}b[N]!==I&&(_||(b=b.slice(),_=!0),b[N]=Xt(b[N],I))}k.length>0&&(b=[...b,...k]);for(const I of l){if(I.locality==="remote"||!u.has(I.session_id))continue;const N=E.get(I.session_id);N===void 0||b[N]===I||(_||(b=b.slice(),_=!0),b[N]=Xt(b[N],I))}const A=new Set(l.map(I=>I.session_id)),$=new Set;for(const I of l)I.locality==="remote"&&typeof I.owner_device=="string"&&I.owner_device!==""&&I.reachable!==!1&&$.add(I.owner_device);const O=new Set;for(const I of b){if(I.locality!=="remote"||typeof I.owner_device!="string"||!g?.removed.includes(I.owner_device))continue;const N=a.placementFacts[I.session_id];N&&N.at>=(s??0)||(O.add(I.session_id),delete d[I.session_id])}for(const[I,N]of Object.entries(a.placementFacts))N.locality==="remote"&&(A.has(I)||N.at>=r||y[N.owner_device]?.reachable!==!1&&(N.owner_device===""||!$.has(N.owner_device)||(O.add(I),delete d[I])));O.size>0&&(b=b.filter(I=>!O.has(I.session_id)));const C=b.map(I=>OS(I,y));return C.some((I,N)=>I!==b[N])&&(b=C,_=!0),!f&&k.length===0&&!_&&O.size===0&&Object.keys(i).length===0&&s===void 0?{}:{sessions:b,placementFacts:d,peerDeviceFacts:y,peerDeviceSnapshotAt:g?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:mk,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 iC(e,t){return t?e.filter(n=>n.archived!==!0):e}function sC(e,t){let n=!1;const r=e.map(i=>{const s=t[i.session_id];return s===void 0||!s.answered||i.archived===s.archived?i:(n=!0,{...i,archived:s.archived})});return n?r:e}function oC(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function aC(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const cC="This backend cannot archive conversations. Update the backend and try again.",lC="This conversation is already archived. Use /unarchive to restore it.",dC="This conversation is not archived, so there is nothing to restore.",uC="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 fC(e,t,n){return n&&e&&t.trim().length>0}function pC(e,t){return t===e}/**
47
47
  * @remix-run/router v1.23.0
48
48
  *
49
49
  * Copyright (c) Remix Software Inc.
@@ -52,7 +52,7 @@ ${e}`)}function _o(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}f
52
52
  * LICENSE.md file in the root directory of this source tree.
53
53
  *
54
54
  * @license MIT
55
- */function Er(){return Er=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},Er.apply(this,arguments)}var Nt;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Nt||(Nt={}));const Nl="popstate";function dC(e){e===void 0&&(e={});function t(i,s){let{pathname:a="/",search:c="",hash:l=""}=dn(i.location.hash.substr(1));return!a.startsWith("/")&&!a.startsWith(".")&&(a="/"+a),yo("",{pathname:a,search:c,hash:l},s.state&&s.state.usr||null,s.state&&s.state.key||"default")}function n(i,s){let a=i.document.querySelector("base"),c="";if(a&&a.getAttribute("href")){let l=i.location.href,d=l.indexOf("#");c=d===-1?l:l.slice(0,d)}return c+"#"+(typeof s=="string"?s:Tf(s))}function r(i,s){aa(i.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(s)+")")}return pk(t,n,r,e)}function ke(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function aa(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function fk(){return Math.random().toString(36).substr(2,8)}function Ll(e,t){return{usr:e.state,key:e.key,idx:t}}function yo(e,t,n,r){return n===void 0&&(n=null),Er({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?dn(t):t,{state:n,key:t&&t.key||r||fk()})}function Tf(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 dn(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 pk(e,t,n,r){r===void 0&&(r={});let{window:i=document.defaultView,v5Compat:s=!1}=r,a=i.history,c=Nt.Pop,l=null,d=u();d==null&&(d=0,a.replaceState(Er({},a.state,{idx:d}),""));function u(){return(a.state||{idx:null}).idx}function f(){c=Nt.Pop;let b=u(),_=b==null?null:b-d;d=b,l&&l({action:c,location:m.location,delta:_})}function p(b,_){c=Nt.Push;let k=yo(m.location,b,_);n&&n(k,b),d=u()+1;let E=Ll(k,d),A=m.createHref(k);try{a.pushState(E,"",A)}catch($){if($ instanceof DOMException&&$.name==="DataCloneError")throw $;i.location.assign(A)}s&&l&&l({action:c,location:m.location,delta:1})}function g(b,_){c=Nt.Replace;let k=yo(m.location,b,_);n&&n(k,b),d=u();let E=Ll(k,d),A=m.createHref(k);a.replaceState(E,"",A),s&&l&&l({action:c,location:m.location,delta:0})}function y(b){let _=i.location.origin!=="null"?i.location.origin:i.location.href,k=typeof b=="string"?b:Tf(b);return k=k.replace(/ $/,"%20"),ke(_,"No window.location.(origin|href) available to create URL for href: "+k),new URL(k,_)}let m={get action(){return c},get location(){return e(i,a)},listen(b){if(l)throw new Error("A history only accepts one active listener");return i.addEventListener(Nl,f),l=b,()=>{i.removeEventListener(Nl,f),l=null}},createHref(b){return t(i,b)},createURL:y,encodeLocation(b){let _=y(b);return{pathname:_.pathname,search:_.search,hash:_.hash}},push:p,replace:g,go(b){return a.go(b)}};return m}var $l;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})($l||($l={}));function hk(e,t,n){return n===void 0&&(n="/"),mk(e,t,n)}function mk(e,t,n,r){let i=typeof t=="string"?dn(t):t,s=Of(i.pathname||"/",n);if(s==null)return null;let a=Cf(e);gk(a);let c=null;for(let l=0;c==null&&l<a.length;++l){let d=Tk(s);c=Ik(a[l],d)}return c}function Cf(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let i=(s,a,c)=>{let l={relativePath:c===void 0?s.path||"":c,caseSensitive:s.caseSensitive===!0,childrenIndex:a,route:s};l.relativePath.startsWith("/")&&(ke(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=$t([r,l.relativePath]),u=n.concat(l);s.children&&s.children.length>0&&(ke(s.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),Cf(s.children,t,u,d)),!(s.path==null&&!s.index)&&t.push({path:d,score:kk(d,s.index),routesMeta:u})};return e.forEach((s,a)=>{var c;if(s.path===""||!((c=s.path)!=null&&c.includes("?")))i(s,a);else for(let l of Af(s.path))i(s,a,l)}),t}function Af(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,i=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return i?[s,""]:[s];let a=Af(r.join("/")),c=[];return c.push(...a.map(l=>l===""?s:[s,l].join("/"))),i&&c.push(...a),c.map(l=>e.startsWith("/")&&l===""?"/":l)}function gk(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:Ek(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const _k=/^:[\w-]+$/,yk=3,bk=2,vk=1,wk=10,Sk=-2,Ul=e=>e==="*";function kk(e,t){let n=e.split("/"),r=n.length;return n.some(Ul)&&(r+=Sk),t&&(r+=bk),n.filter(i=>!Ul(i)).reduce((i,s)=>i+(_k.test(s)?yk:s===""?vk:wk),r)}function Ek(e,t){return e.length===t.length&&e.slice(0,-1).every((r,i)=>r===t[i])?e[e.length-1]-t[t.length-1]:0}function Ik(e,t,n){let{routesMeta:r}=e,i={},s="/",a=[];for(let c=0;c<r.length;++c){let l=r[c],d=c===r.length-1,u=s==="/"?t:t.slice(s.length)||"/",f=xk({path:l.relativePath,caseSensitive:l.caseSensitive,end:d},u),p=l.route;if(!f)return null;Object.assign(i,f.params),a.push({params:i,pathname:$t([s,f.pathname]),pathnameBase:Pk($t([s,f.pathnameBase])),route:p}),f.pathnameBase!=="/"&&(s=$t([s,f.pathnameBase]))}return a}function xk(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Rk(e.path,e.caseSensitive,e.end),i=t.match(n);if(!i)return null;let s=i[0],a=s.replace(/(.)\/+$/,"$1"),c=i.slice(1);return{params:r.reduce((d,u,f)=>{let{paramName:p,isOptional:g}=u;if(p==="*"){let m=c[f]||"";a=s.slice(0,s.length-m.length).replace(/(.)\/+$/,"$1")}const y=c[f];return g&&!y?d[p]=void 0:d[p]=(y||"").replace(/%2F/g,"/"),d},{}),pathname:s,pathnameBase:a,pattern:e}}function Rk(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),aa(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=[],i="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,c,l)=>(r.push({paramName:c,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),i+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?i+="\\/*$":e!==""&&e!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,t?void 0:"i"),r]}function Tk(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return aa(!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 Of(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 Ck(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:i=""}=typeof e=="string"?dn(e):e;return{pathname:n?n.startsWith("/")?n:Ak(n,t):t,search:jk(r),hash:Mk(i)}}function Ak(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(i=>{i===".."?n.length>1&&n.pop():i!=="."&&n.push(i)}),n.length>1?n.join("/"):"/"}function Os(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 Ok(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function ca(e,t){let n=Ok(e);return t?n.map((r,i)=>i===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function la(e,t,n,r){r===void 0&&(r=!1);let i;typeof e=="string"?i=dn(e):(i=Er({},e),ke(!i.pathname||!i.pathname.includes("?"),Os("?","pathname","search",i)),ke(!i.pathname||!i.pathname.includes("#"),Os("#","pathname","hash",i)),ke(!i.search||!i.search.includes("#"),Os("#","search","hash",i)));let s=e===""||i.pathname==="",a=s?"/":i.pathname,c;if(a==null)c=n;else{let f=t.length-1;if(!r&&a.startsWith("..")){let p=a.split("/");for(;p[0]==="..";)p.shift(),f-=1;i.pathname=p.join("/")}c=f>=0?t[f]:"/"}let l=Ck(i,c),d=a&&a!=="/"&&a.endsWith("/"),u=(s||a===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(d||u)&&(l.pathname+="/"),l}const $t=e=>e.join("/").replace(/\/\/+/g,"/"),Pk=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),jk=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,Mk=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function Dk(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Pf=["post","put","patch","delete"];new Set(Pf);const Nk=["get",...Pf];new Set(Nk);/**
55
+ */function Er(){return Er=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},Er.apply(this,arguments)}var Nt;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Nt||(Nt={}));const Nl="popstate";function hC(e){e===void 0&&(e={});function t(i,s){let{pathname:a="/",search:c="",hash:l=""}=dn(i.location.hash.substr(1));return!a.startsWith("/")&&!a.startsWith(".")&&(a="/"+a),yo("",{pathname:a,search:c,hash:l},s.state&&s.state.usr||null,s.state&&s.state.key||"default")}function n(i,s){let a=i.document.querySelector("base"),c="";if(a&&a.getAttribute("href")){let l=i.location.href,d=l.indexOf("#");c=d===-1?l:l.slice(0,d)}return c+"#"+(typeof s=="string"?s:Cf(s))}function r(i,s){aa(i.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(s)+")")}return _k(t,n,r,e)}function ke(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function aa(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function gk(){return Math.random().toString(36).substr(2,8)}function Ll(e,t){return{usr:e.state,key:e.key,idx:t}}function yo(e,t,n,r){return n===void 0&&(n=null),Er({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?dn(t):t,{state:n,key:t&&t.key||r||gk()})}function Cf(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 dn(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 _k(e,t,n,r){r===void 0&&(r={});let{window:i=document.defaultView,v5Compat:s=!1}=r,a=i.history,c=Nt.Pop,l=null,d=u();d==null&&(d=0,a.replaceState(Er({},a.state,{idx:d}),""));function u(){return(a.state||{idx:null}).idx}function f(){c=Nt.Pop;let b=u(),_=b==null?null:b-d;d=b,l&&l({action:c,location:m.location,delta:_})}function p(b,_){c=Nt.Push;let k=yo(m.location,b,_);n&&n(k,b),d=u()+1;let E=Ll(k,d),A=m.createHref(k);try{a.pushState(E,"",A)}catch($){if($ instanceof DOMException&&$.name==="DataCloneError")throw $;i.location.assign(A)}s&&l&&l({action:c,location:m.location,delta:1})}function g(b,_){c=Nt.Replace;let k=yo(m.location,b,_);n&&n(k,b),d=u();let E=Ll(k,d),A=m.createHref(k);a.replaceState(E,"",A),s&&l&&l({action:c,location:m.location,delta:0})}function y(b){let _=i.location.origin!=="null"?i.location.origin:i.location.href,k=typeof b=="string"?b:Cf(b);return k=k.replace(/ $/,"%20"),ke(_,"No window.location.(origin|href) available to create URL for href: "+k),new URL(k,_)}let m={get action(){return c},get location(){return e(i,a)},listen(b){if(l)throw new Error("A history only accepts one active listener");return i.addEventListener(Nl,f),l=b,()=>{i.removeEventListener(Nl,f),l=null}},createHref(b){return t(i,b)},createURL:y,encodeLocation(b){let _=y(b);return{pathname:_.pathname,search:_.search,hash:_.hash}},push:p,replace:g,go(b){return a.go(b)}};return m}var $l;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})($l||($l={}));function yk(e,t,n){return n===void 0&&(n="/"),bk(e,t,n)}function bk(e,t,n,r){let i=typeof t=="string"?dn(t):t,s=Pf(i.pathname||"/",n);if(s==null)return null;let a=Af(e);vk(a);let c=null;for(let l=0;c==null&&l<a.length;++l){let d=Pk(s);c=Ck(a[l],d)}return c}function Af(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let i=(s,a,c)=>{let l={relativePath:c===void 0?s.path||"":c,caseSensitive:s.caseSensitive===!0,childrenIndex:a,route:s};l.relativePath.startsWith("/")&&(ke(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=$t([r,l.relativePath]),u=n.concat(l);s.children&&s.children.length>0&&(ke(s.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),Af(s.children,t,u,d)),!(s.path==null&&!s.index)&&t.push({path:d,score:Rk(d,s.index),routesMeta:u})};return e.forEach((s,a)=>{var c;if(s.path===""||!((c=s.path)!=null&&c.includes("?")))i(s,a);else for(let l of Of(s.path))i(s,a,l)}),t}function Of(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,i=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return i?[s,""]:[s];let a=Of(r.join("/")),c=[];return c.push(...a.map(l=>l===""?s:[s,l].join("/"))),i&&c.push(...a),c.map(l=>e.startsWith("/")&&l===""?"/":l)}function vk(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:Tk(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const wk=/^:[\w-]+$/,Sk=3,kk=2,Ek=1,Ik=10,xk=-2,Ul=e=>e==="*";function Rk(e,t){let n=e.split("/"),r=n.length;return n.some(Ul)&&(r+=xk),t&&(r+=kk),n.filter(i=>!Ul(i)).reduce((i,s)=>i+(wk.test(s)?Sk:s===""?Ek:Ik),r)}function Tk(e,t){return e.length===t.length&&e.slice(0,-1).every((r,i)=>r===t[i])?e[e.length-1]-t[t.length-1]:0}function Ck(e,t,n){let{routesMeta:r}=e,i={},s="/",a=[];for(let c=0;c<r.length;++c){let l=r[c],d=c===r.length-1,u=s==="/"?t:t.slice(s.length)||"/",f=Ak({path:l.relativePath,caseSensitive:l.caseSensitive,end:d},u),p=l.route;if(!f)return null;Object.assign(i,f.params),a.push({params:i,pathname:$t([s,f.pathname]),pathnameBase:Nk($t([s,f.pathnameBase])),route:p}),f.pathnameBase!=="/"&&(s=$t([s,f.pathnameBase]))}return a}function Ak(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Ok(e.path,e.caseSensitive,e.end),i=t.match(n);if(!i)return null;let s=i[0],a=s.replace(/(.)\/+$/,"$1"),c=i.slice(1);return{params:r.reduce((d,u,f)=>{let{paramName:p,isOptional:g}=u;if(p==="*"){let m=c[f]||"";a=s.slice(0,s.length-m.length).replace(/(.)\/+$/,"$1")}const y=c[f];return g&&!y?d[p]=void 0:d[p]=(y||"").replace(/%2F/g,"/"),d},{}),pathname:s,pathnameBase:a,pattern:e}}function Ok(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),aa(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=[],i="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,c,l)=>(r.push({paramName:c,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),i+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?i+="\\/*$":e!==""&&e!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,t?void 0:"i"),r]}function Pk(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return aa(!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 Pf(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 jk(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:i=""}=typeof e=="string"?dn(e):e;return{pathname:n?n.startsWith("/")?n:Mk(n,t):t,search:Lk(r),hash:$k(i)}}function Mk(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(i=>{i===".."?n.length>1&&n.pop():i!=="."&&n.push(i)}),n.length>1?n.join("/"):"/"}function Os(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 Dk(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function ca(e,t){let n=Dk(e);return t?n.map((r,i)=>i===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function la(e,t,n,r){r===void 0&&(r=!1);let i;typeof e=="string"?i=dn(e):(i=Er({},e),ke(!i.pathname||!i.pathname.includes("?"),Os("?","pathname","search",i)),ke(!i.pathname||!i.pathname.includes("#"),Os("#","pathname","hash",i)),ke(!i.search||!i.search.includes("#"),Os("#","search","hash",i)));let s=e===""||i.pathname==="",a=s?"/":i.pathname,c;if(a==null)c=n;else{let f=t.length-1;if(!r&&a.startsWith("..")){let p=a.split("/");for(;p[0]==="..";)p.shift(),f-=1;i.pathname=p.join("/")}c=f>=0?t[f]:"/"}let l=jk(i,c),d=a&&a!=="/"&&a.endsWith("/"),u=(s||a===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(d||u)&&(l.pathname+="/"),l}const $t=e=>e.join("/").replace(/\/\/+/g,"/"),Nk=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Lk=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,$k=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function Uk(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const jf=["post","put","patch","delete"];new Set(jf);const Fk=["get",...jf];new Set(Fk);/**
56
56
  * React Router v6.30.0
57
57
  *
58
58
  * Copyright (c) Remix Software Inc.
@@ -61,4 +61,4 @@ ${e}`)}function _o(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}f
61
61
  * LICENSE.md file in the root directory of this source tree.
62
62
  *
63
63
  * @license MIT
64
- */function Ir(){return Ir=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},Ir.apply(this,arguments)}const da=S.createContext(null),Lk=S.createContext(null),un=S.createContext(null),Mi=S.createContext(null),Tt=S.createContext({outlet:null,matches:[],isDataRoute:!1}),jf=S.createContext(null);function uC(e,t){let{relative:n}=t===void 0?{}:t;Mn()||ke(!1);let{basename:r,navigator:i}=S.useContext(un),{hash:s,pathname:a,search:c}=Fk(e,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:$t([r,a])),i.createHref({pathname:l,search:c,hash:s})}function Mn(){return S.useContext(Mi)!=null}function Di(){return Mn()||ke(!1),S.useContext(Mi).location}function Mf(e){S.useContext(un).static||S.useLayoutEffect(e)}function $k(){let{isDataRoute:e}=S.useContext(Tt);return e?Xk():Uk()}function Uk(){Mn()||ke(!1);let e=S.useContext(da),{basename:t,future:n,navigator:r}=S.useContext(un),{matches:i}=S.useContext(Tt),{pathname:s}=Di(),a=JSON.stringify(ca(i,n.v7_relativeSplatPath)),c=S.useRef(!1);return Mf(()=>{c.current=!0}),S.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=la(d,JSON.parse(a),s,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:$t([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,a,s,e])}function fC(){let{matches:e}=S.useContext(Tt),t=e[e.length-1];return t?t.params:{}}function Fk(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=S.useContext(un),{matches:i}=S.useContext(Tt),{pathname:s}=Di(),a=JSON.stringify(ca(i,r.v7_relativeSplatPath));return S.useMemo(()=>la(e,JSON.parse(a),s,n==="path"),[e,a,s,n])}function Bk(e,t){return Gk(e,t)}function Gk(e,t,n,r){Mn()||ke(!1);let{navigator:i,static:s}=S.useContext(un),{matches:a}=S.useContext(Tt),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=Di(),f;if(t){var p;let _=typeof t=="string"?dn(t):t;d==="/"||(p=_.pathname)!=null&&p.startsWith(d)||ke(!1),f=_}else f=u;let g=f.pathname||"/",y=g;if(d!=="/"){let _=d.replace(/^\//,"").split("/");y="/"+g.replace(/^\//,"").split("/").slice(_.length).join("/")}let m=hk(e,{pathname:y}),b=Kk(m&&m.map(_=>Object.assign({},_,{params:Object.assign({},l,_.params),pathname:$t([d,i.encodeLocation?i.encodeLocation(_.pathname).pathname:_.pathname]),pathnameBase:_.pathnameBase==="/"?d:$t([d,i.encodeLocation?i.encodeLocation(_.pathnameBase).pathname:_.pathnameBase])})),a,n,r);return t&&b?S.createElement(Mi.Provider,{value:{location:Ir({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:Nt.Pop}},b):b}function Hk(){let e=Jk(),t=Dk(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return S.createElement(S.Fragment,null,S.createElement("h2",null,"Unexpected Application Error!"),S.createElement("h3",{style:{fontStyle:"italic"}},t),n?S.createElement("pre",{style:i},n):null,null)}const zk=S.createElement(Hk,null);class Wk extends S.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?S.createElement(Tt.Provider,{value:this.props.routeContext},S.createElement(jf.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function Zk(e){let{routeContext:t,match:n,children:r}=e,i=S.useContext(da);return i&&i.static&&i.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=n.route.id),S.createElement(Tt.Provider,{value:t},r)}function Kk(e,t,n,r){var i;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var s;if(!n)return null;if(n.errors)e=n.matches;else if((s=r)!=null&&s.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,c=(i=n)==null?void 0:i.errors;if(c!=null){let u=a.findIndex(f=>f.route.id&&c?.[f.route.id]!==void 0);u>=0||ke(!1),a=a.slice(0,Math.min(a.length,u+1))}let l=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u<a.length;u++){let f=a[u];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(d=u),f.route.id){let{loaderData:p,errors:g}=n,y=f.route.loader&&p[f.route.id]===void 0&&(!g||g[f.route.id]===void 0);if(f.route.lazy||y){l=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}return a.reduceRight((u,f,p)=>{let g,y=!1,m=null,b=null;n&&(g=c&&f.route.id?c[f.route.id]:void 0,m=f.route.errorElement||zk,l&&(d<0&&p===0?(qk("route-fallback"),y=!0,b=null):d===p&&(y=!0,b=f.route.hydrateFallbackElement||null)));let _=t.concat(a.slice(0,p+1)),k=()=>{let E;return g?E=m:y?E=b:f.route.Component?E=S.createElement(f.route.Component,null):f.route.element?E=f.route.element:E=u,S.createElement(Zk,{match:f,routeContext:{outlet:u,matches:_,isDataRoute:n!=null},children:E})};return n&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?S.createElement(Wk,{location:n.location,revalidation:n.revalidation,component:m,error:g,children:k(),routeContext:{outlet:null,matches:_,isDataRoute:!0}}):k()},null)}var Df=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Df||{}),Nf=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}(Nf||{});function Vk(e){let t=S.useContext(da);return t||ke(!1),t}function Yk(e){let t=S.useContext(Lk);return t||ke(!1),t}function Qk(e){let t=S.useContext(Tt);return t||ke(!1),t}function Lf(e){let t=Qk(),n=t.matches[t.matches.length-1];return n.route.id||ke(!1),n.route.id}function Jk(){var e;let t=S.useContext(jf),n=Yk(),r=Lf();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function Xk(){let{router:e}=Vk(Df.UseNavigateStable),t=Lf(Nf.UseNavigateStable),n=S.useRef(!1);return Mf(()=>{n.current=!0}),S.useCallback(function(i,s){s===void 0&&(s={}),n.current&&(typeof i=="number"?e.navigate(i):e.navigate(i,Ir({fromRouteId:t},s)))},[e,t])}const Fl={};function qk(e,t,n){Fl[e]||(Fl[e]=!0)}function pC(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function hC(e){let{to:t,replace:n,state:r,relative:i}=e;Mn()||ke(!1);let{future:s,static:a}=S.useContext(un),{matches:c}=S.useContext(Tt),{pathname:l}=Di(),d=$k(),u=la(t,ca(c,s.v7_relativeSplatPath),l,i==="path"),f=JSON.stringify(u);return S.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:i}),[d,f,i,n,r]),null}function eE(e){ke(!1)}function mC(e){let{basename:t="/",children:n=null,location:r,navigationType:i=Nt.Pop,navigator:s,static:a=!1,future:c}=e;Mn()&&ke(!1);let l=t.replace(/^\/*/,"/"),d=S.useMemo(()=>({basename:l,navigator:s,static:a,future:Ir({v7_relativeSplatPath:!1},c)}),[l,c,s,a]);typeof r=="string"&&(r=dn(r));let{pathname:u="/",search:f="",hash:p="",state:g=null,key:y="default"}=r,m=S.useMemo(()=>{let b=Of(u,l);return b==null?null:{location:{pathname:b,search:f,hash:p,state:g,key:y},navigationType:i}},[l,u,f,p,g,y,i]);return m==null?null:S.createElement(un.Provider,{value:d},S.createElement(Mi.Provider,{children:n,value:m}))}function gC(e){let{children:t,location:n}=e;return Bk(bo(t),n)}new Promise(()=>{});function bo(e,t){t===void 0&&(t=[]);let n=[];return S.Children.forEach(e,(r,i)=>{if(!S.isValidElement(r))return;let s=[...t,i];if(r.type===S.Fragment){n.push.apply(n,bo(r.props.children,s));return}r.type!==eE&&ke(!1),!r.props.index||!r.props.children||ke(!1);let a={id:r.props.id||s.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=bo(r.props.children,s)),n.push(a)}),n}const Ni=260,ua=220,fa=320,$f=56,pa=480,_C=8,ha=44,ma=400,Uf=1200;function ga(e){return Math.max(0,Math.min(Uf,e-pa))}function vo(e){return ga(e)>=ma?"docked":"overlay"}const tE=48,nE=16;function yC(e,t){if(vo(e)==="docked")return{mode:"docked",width:Math.min(t,ga(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,ma),e-tE));return e-n>=nE?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function bC({capacity:e,min:t,max:n,drawn:r}){const i=e>=t;return i?{resizable:i,value:Math.min(Math.max(r,t),e),minWidth:t,maxWidth:Math.min(n,e)}:{resizable:i,value:r,minWidth:r,maxWidth:r}}function rE(e,t=Ni,n=ha){return vo(e-Ff(t)-n)==="overlay"&&vo(e-$f-n)==="docked"}function Ff(e){return Number.isNaN(e)?Ni:Math.min(fa,Math.max(ua,e))}function iE(e,t=ha){return Math.max(0,Math.min(fa,e-pa-t))}function vC(e,t,n=Ni,r=!1,i=ha){const s=!t&&r&&rE(e,n,i),a=t||s,c=iE(e,i);return{mode:a?"strip":"docked",width:a?$f:Math.min(Ff(n),c),collapsed:a,resizable:!a&&c>=ua}}function wC(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const SC=e=>e?"⌘B":"Ctrl+B",sE="data-canvas-shortcuts",oE=`[${sE}]`,aE=e=>Bf(e,oE),cE='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',kC=e=>Bf(e,cE);function Bf(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const EC=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&aE(e.target)?"new-file":null},Gf="small",lE=["small","medium","large"],Hf="before:absolute before:-inset-0.5 before:content-['']",dE={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:Hf},medium:{px:28,className:"size-7",glyphClassName:"size-3.5",hitClassName:""},large:{px:36,className:"size-9",glyphClassName:"size-4",hitClassName:""}},uE={small:{px:4,className:"mb-1"},medium:{px:6,className:"mb-1.5"},large:{px:8,className:"mb-2"}},IC={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:Hf,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 xC(e){for(const t of lE)if(e===t)return t;return Gf}function RC(e){return dE[e].px+uE[e].px}const fE=["active","created"],TC={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"},pE=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function Li(e){return pE.has(e.status?.code??"")}const hE=new Set(["approval","answer"]);function mE(e){return hE.has(e.status?.code??"")}const gE=24*60*60*1e3,_E=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function _a(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 yE="last_user_at";function bE(e){const t=e[yE],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 vE(e,t,n){if(Li(e))return"running";const r=_a(e,n);if(r===null)return"older";const i=_E(t);return r>=i?"today":r>=i-6*gE?"week":"older"}function CC(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const i of e)r[vE(i,t,n)].push(i);return r}function zf(e,t,n){const r=_a(e,n);if(r===null)return null;const i=Math.floor(Math.max(0,t-r)/6e4);if(i<1)return{unit:"now",count:0};if(i<60)return{unit:"minute",count:i};const s=Math.floor(i/60);if(s<24)return{unit:"hour",count:s};const a=Math.floor(s/24);return a<7?{unit:"day",count:a}:a<365?{unit:"week",count:Math.floor(a/7)}:{unit:"year",count:Math.floor(a/365)}}function AC(e,t,n){const r=zf(e,t,n);return r?h("ui.chat.sidebar_view.relative_short",r):""}function OC(e,t,n){const r=zf(e,t,n);return r?n==="created"?h("ui.chat.sidebar_view.relative_created",r):h("ui.chat.sidebar_view.relative_active",r):""}const wo=["pinned","running","today","week","older","agents","teams"],PC={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 jC(e){return e==="agents"||e==="teams"}const xr=8;function wE(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function MC(e,t){return{...e,[t]:(e[t]??xr)+xr}}function DC(e,t,n,r,i){const s=!(e[n]??r);return{expanded:{...e,[n]:s},caps:!s&&!i?wE(t,n):t}}function NC(e,t,n,r){return(e||t!=="")&&(r>xr||n.trim()!=="")}const LC="Collapse, then reopen, to restore the compact list";function $C(e){return(e??xr)>xr}const UC=e=>`section-grown-hint-${e}`,SE=e=>e===1?"Show 1 more":`Show ${e} more`;function FC(e,t){return`${SE(e)} ${t}`}const bn={hidden:[],order:[...wo],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},kE=10,Zn=[25,50],EE=50,IE=500,xE=64;function Rn(e){const t=Math.max(0,Math.floor(e));return t===0?kE:t<=Zn.length?Zn[t-1]:Zn[Zn.length-1]+(t-Zn.length)*EE}function BC(e,t){const n=Rn(e+1)-Rn(e),r=Math.max(0,Math.min(n,t));return r===1?"Show 1 more chat":`Show ${r} more chats`}function GC(e,t,n){const r=Rn(t+1)-Rn(t),i=Rn(t),s=Math.min(i+r,e.length);let a=0;for(let l=i;l<s;l+=1)ya(e[l])&&(a+=1);const c=Math.max(0,s-i-a);return c>0?c:Math.max(0,Math.min(r,n))}function ya(e){return Li(e)}function RE(e){return mE(e)?0:Li(e)?1:2}function TE(e,t){return Li(e)?bE(e):_a(e,t)}function CE(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function HC(e,t,n){const r=e.map((i,s)=>({row:i,index:s,lane:t==="active-first"?RE(i):0,at:TE(i,n)}));return r.sort((i,s)=>i.lane-s.lane||CE(i.at,s.at)||i.index-s.index),r.map(i=>i.row)}function zC(e,t){const{limit:n,currentId:r,searching:i=!1}=t;if(i)return{rows:[...e],lifted:!1,remaining:0};const s=[];let a=Math.max(0,n);for(const d of e){if(a>0){s.push(d),a-=1;continue}ya(d)&&s.push(d)}const c=Math.max(0,e.length-s.length);if(!r)return{rows:s,lifted:!1,remaining:c};const l=e.find(d=>d.session_id===r)??null;return l===null||s.includes(l)?{rows:s,lifted:!1,remaining:c}:{rows:[l,...s],lifted:!0,remaining:c}}function WC(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=Rn(t.loads),r=[];let i=n;for(const l of e){if(ya(l)){r.push(l);continue}i>0&&(r.push(l),i-=1)}const s=t.currentId,a=s==null?null:e.find(l=>l.session_id===s)??null,c=a!==null&&!r.includes(a);return{rows:c&&a!==null?[a,...r]:r,lifted:c,hidden:e.length-r.length-(c?1:0),held:e.length}}function ZC(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 AE="mt-4",OE="mt-2";function KC(e){return e?AE:OE}function VC(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function YC(e,t){if(t==="section")return null;if(t==="flat")return[{key:"all",label:"",rows:[...e]}];const n=new Map;for(const s of e){const a=s.binding?.team||s.binding?.agent||"",c=a||"ungrouped",l=n.get(c)??{key:c,label:a||"Ungrouped",rows:[]};l.rows.push(s),n.set(c,l)}const r=[...n.values()],i=r.findIndex(s=>s.key==="ungrouped");return i>0&&r.push(...r.splice(i,1)),r}function PE(e,t){return!e.hidden.includes(t)}function Wf(e){return e.order.filter(t=>PE(e,t))}function QC(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function JC(e,t,n){const r=Wf(e),i=r.indexOf(t),s=r[i+n];if(i<0||s===void 0)return e;const a=e.order.indexOf(t),c=e.order.indexOf(s),l=[...e.order];return l[a]=s,l[c]=t,{...e,order:l}}const jE=["running","today","week","older"];function Bl(e){return jE.includes(e)}function XC(e,t,n,r){if(!Bl(t)||r&&!r(t))return!1;const i=Wf(e),s=i.indexOf(t);if(s<0)return!1;const a=i[s+n];return a===void 0||!Bl(a)?!1:r?r(a):!0}const ME=["section","agent","flat"],DE=["active-first","recent"];function qC(e){if(typeof e!="object"||e===null)return bn;const t=e,n=new Set(wo),r=[];if(Array.isArray(t.order))for(const p of t.order)typeof p=="string"&&n.has(p)&&(r.includes(p)||r.push(p));for(const p of wo)r.includes(p)||r.push(p);const i=[];if(Array.isArray(t.hidden))for(const p of t.hidden)typeof p=="string"&&n.has(p)&&(i.includes(p)||i.push(p));const s=ME.includes(t.groupBy)?t.groupBy:bn.groupBy,a=fE.includes(t.basis)?t.basis:bn.basis,c=DE.includes(t.orderBy)?t.orderBy:bn.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(IE,Math.floor(t.loads)):0,d=[];if(Array.isArray(t.pinnedAgents)){for(const p of t.pinnedAgents)if(typeof p=="string"&&p!==""&&!d.includes(p)){if(d.length>=xE)break;d.push(p)}}const u=[],f=new Set;if(Array.isArray(t.pins))for(const p of t.pins)typeof p=="string"&&p.length!==0&&(f.has(p)||(f.add(p),u.push(p)));return{hidden:i,order:r,groupBy:s,tagsEnabled:typeof t.tagsEnabled=="boolean"?t.tagsEnabled:!1,autoTagForks:typeof t.autoTagForks=="boolean"?t.autoTagForks:bn.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const Zf={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},NE=["recent","name","kind","modified","created","size"],LE=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function ba(e){const t=e&&typeof e=="object"?e:{};return{sort:NE.includes(t.sort??"")?t.sort:Zf.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=>[Rr,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>LE.includes(n)))]:[]}}const Rr="Attachments";function eA(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,i)=>{const s=n(r),a=n(i);if(s===null||a===null)return s===a?0:s===null?1:-1;const c=typeof s=="string"&&typeof a=="string"?s.localeCompare(a,void 0,{numeric:!0}):Number(s)-Number(a);return(t.order==="asc"?c:-c)||r.mentioned-i.mentioned})}const $E=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 tA(e,t,n,r,i=[]){const s=e.filter(l=>l.highlighted),a=e.filter(l=>!l.highlighted),c=[];if(i.length&&c.push({id:Rr,label:h("ui.canvas.files.attachments"),items:i,open:n||!r.has(Rr),highlights:!1}),s.length&&c.push({id:"Highlights",label:h("ui.canvas.finder_layout.highlights"),items:s,open:n||!r.has("Highlights"),highlights:!0}),s.length&&a.length&&(c.push({id:"Working files",label:h("ui.canvas.finder_layout.working_files"),items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return c;if(!t.group)a.length&&c.push({id:"Files",label:h("ui.canvas.finder_layout.files"),items:a,open:!0,highlights:!1});else for(const l of["Images","Videos","Sounds","Documents","Spreadsheets","Other"]){const d=a.filter(u=>$E(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const UE=32,nA=4,Kf=32,Vf=18;function rA(e){return e.height-Kf-(e.kind==="tiles"&&e.section.id===Rr?Vf:0)}function iA(e,t,n){const r=[],i=new Map,s=Math.max(136,t-16),a=Math.max(1,Math.floor((s+4)/140));let c=0;const l=(d,u,f,p,g=1)=>{p.forEach((y,m)=>i.set(y.row.document.id,{band:r.length,column:m})),r.push({section:d,kind:u,height:f,top:c,items:p,cols:g}),c+=f};for(const d of e)if(l(d,"header",UE,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(d.id===Rr){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 p=(s-4*(a-1))/a,g=Math.round((p-8)*3/4)+Kf+Vf;for(let y=0;y<f.length;y+=a)l(d,"tiles",g,f.slice(y,y+a),a)}else if(n&&d.id==="Images"){const u=(s-4*(a-1))/a,f=Math.round((u-8)*3/4)+32;for(let p=0;p<d.items.length;p+=a)l(d,"tiles",f,d.items.slice(p,p+a),a)}else if(n&&d.id==="Videos")for(const u of d.items)l(d,"video",Math.min(Math.round((s-8)*9/16),280)+32,[u]);else if(n&&d.id==="Sounds")for(const u of d.items)l(d,"audio",80,[u]);else for(const u of d.items)l(d,"compact",36,[u]);return{bands:r,height:c,columns:a,positions:i}}function sA(e,t,n,r){const i=Math.max(600,n*.75);let s=0,a=e.bands.length;for(;s<a;){const d=s+a>>>1,u=e.bands[d];u.top+u.height<t-i?s=d+1:a=d}const c=new Set;for(let d=s;d<e.bands.length&&e.bands[d].top<=t+n+i;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 oA(e,t,n,r){const i=e.positions.get(t);if(!i)return null;const s=e.bands[i.band],a=e.bands.filter(u=>u.section.id===s.section.id&&u.items.length);if(n==="Home")return a[0]?.items[0]?.row.document.id??null;if(n==="End")return a.at(-1)?.items.at(-1)?.row.document.id??null;if(n==="ArrowLeft"||n==="ArrowRight")return s.items[i.column+(n==="ArrowLeft"?-1:1)]?.row.document.id??null;const c=n==="ArrowUp"||n==="PageUp"?-1:1,l=s.top+(n.startsWith("Page")?r*c:c);let d=i.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(i.column,u.items.length-1)].row.document.id}if(n.startsWith("Page")){const u=e.bands.filter(p=>p.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 FE="both",Yf="by-turn",So=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function aA(e){for(const t of So)if(e===t.value)return t.value;return Yf}function cA(e){return So.find(t=>t.value===e)?.label??So[0].label}const lA="primary+alt+shift+space",BE=/^f([1-9]|1[0-9]|2[0-4])$/;function GE(e){return BE.test(e)}function HE(e,t){const n=zE(e,t);return t==="mac"?n.join(""):n.join("+")}function zE(e,t){const r=t==="mac"?{primary:"⌘",meta:"⌘",ctrl:"⌃",alt:"⌥",shift:"⇧"}:{primary:"Ctrl",meta:t==="win"?"Win":"Super",ctrl:"Ctrl",alt:"Alt",shift:"Shift"},i={space:"Space",backspace:"Backspace",delete:"Delete",insert:"Insert",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown",up:"Up",down:"Down",left:"Left",right:"Right"};return e.split("+").map(s=>s.trim().toLowerCase()).filter(s=>s.length>0).map(s=>s in r?r[s]:s in i?i[s]:GE(s)||s.length===1?s.toUpperCase():s)}const $i=[{id:"panel.console",get label(){return h("ui.settings.shortcuts.action.open_console")},get category(){return h("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return h("ui.settings.shortcuts.action.open_canvas")},get category(){return h("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return h("ui.settings.shortcuts.action.open_run_details")},get category(){return h("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return h("ui.settings.shortcuts.action.open_asks")},get category(){return h("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return h("ui.settings.shortcuts.action.open_browser")},get category(){return h("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return h("ui.settings.shortcuts.action.open_code_review")},get category(){return h("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],WE=new Map($i.map(e=>[e.id,e])),ZE=e=>WE.get(e),KE=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 VE 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,i]of this)t.call(n,i,r,this)}[Symbol.iterator](){return this.entries()}}const va=new VE([["primary+p",()=>h("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>h("ui.settings.shortcuts.reserved.palette_commands")],["primary+k",()=>h("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>h("ui.settings.shortcuts.reserved.new_chat")],["primary+b",()=>h("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>h("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>h("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>h("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>h("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>h("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>h("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>h("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>h("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>h("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>h("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>h("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>h("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>h("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>h("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>h("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>h("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>h("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>h("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>h("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>h("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>h("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>h("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>h("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>h("ui.settings.shortcuts.reserved.browser_last_tab"):()=>h("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>h("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>h("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>h("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>h("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>h("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>h("ui.settings.shortcuts.reserved.close")],["primary+m",()=>h("ui.settings.shortcuts.reserved.minimise")]]),YE=["primary","alt","shift"],QE={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},JE=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),XE=e=>JE.has(e)||/^[a-z0-9]$/.test(e);function wa(e){if(typeof e!="string")return null;const t=e.toLowerCase().split("+").map(s=>s.trim()).filter(s=>s.length>0);if(t.length===0)return null;const n=t[t.length-1];if(!XE(n))return null;const r=new Set;for(const s of t.slice(0,-1)){const a=QE[s];if(a===void 0)return null;r.add(a)}return[...YE.filter(s=>r.has(s)),n].join("+")}const Qf=e=>e.split("+").includes("primary");function Ui(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!va.has(n)?n:ZE(e)?.defaultChord??null}function dA(e){const t=new Map;for(const n of $i){const r=Ui(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const qE=e=>e==="mac"?h("ui.settings.shortcuts.capture.needs_modifier_mac"):h("ui.settings.shortcuts.capture.needs_modifier");function eI(e,t,n,r="linux",i=new Map){const s=e===null?null:wa(e);if(s===null)return h("ui.settings.shortcuts.capture.unbindable");if(!Qf(s))return qE(r);const a=va.get(s);if(a!==void 0)return a;const c=i.get(s);if(c!==void 0)return h("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of $i)if(l.id!==t&&Ui(l.id,n)===s)return h("ui.settings.shortcuts.capture.already_assigned",{label:l.label});return null}function tI(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const i of $i){const s=t[i.id];if(s===null){r[i.id]=null;continue}const a=typeof s=="string"?wa(s):null,c=a!==null&&KE.has(a),l=a!==null&&Qf(a)&&(c||!va.has(a)&&!n.has(a))?a:null;l!==null&&(r[i.id]=l);const d=Ui(i.id,r);d!==null&&n.add(d)}return r}function uA(e,t,n){const r=Ui(e,t);return r===null?null:Jf(r,n)}function Jf(e,t){return HE(e,t)}function fA(e,t){const n=e.split("+"),r=n[n.length-1],i=n.slice(0,-1).map(s=>s==="primary"?t==="mac"?"Meta":"Control":s==="shift"?"Shift":s==="alt"?"Alt":s);return{glyph:Jf(e,t),aria:[...i,r.length===1?r.toUpperCase():r].join("+")}}const Gl=64,ko=["canvas","run","browser","console","code"],nI={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function Xf(e){return typeof e=="string"&&ko.includes(e)}function Sa(e){return e.startsWith("draft:")}function Mr(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function ka(e){return e.length>Gl?e.slice(e.length-Gl):e}function qf(e,t,n){return ka([...e.filter(([r])=>r!==t),[t,n]])}function rI(e,t,n){return Mr(e,t)!==n?e:e.filter(([r])=>r!==t)}function iI(e,t){return Mr(e,t)===void 0?e:e.filter(([n])=>n!==t)}function sI(e,t,n){const r=Mr(e,t);return r===void 0?e:ka([...e.filter(([i])=>i!==t&&i!==n),[n,r]])}const Hl=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function zl(e,t,n){if(n||typeof t!="string")return Hl;const r=Mr(e,t);return r===void 0?Hl:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function oI(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,i]=n;typeof r!="string"||r===""||Sa(r)||Xf(i)&&(t.delete(r),t.set(r,i))}return ka([...t.entries()])}function pA(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 Wl(e){return nI[e]}const aI={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},Dr=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,Fi=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,cI=e=>{const t=Dr(e);return t===null||t==="ask"?null:aI[t]},Dt=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Yt=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:qf(e.rightSlotMemory,n,t)}},Kn=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=rI(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},lI=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=iI(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},dI=Object.freeze({mounted:!1,session:!1}),ep=Object.freeze([]);function hA(e,t){const n=Dr(t);if(n===null||!Fi(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=Vn(ma,t.rightSlotWidth);break;case"run":r=Vn(Kl,t.rightSlotWidth);break;case"browser":r=Vn(mI,t.rightSlotWidth);break;case"console":r=Vn(gI,t.rightSlotWidth);break;case"code":r=Vn(Kl,t.rightSlotWidth);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,ga(e)):Math.min(r,Math.max(0,e-pa))}function Vn(e,t){return Math.min(Uf,Math.max(e,t||uI))}function mA(e){const t=Dr(e);return t!==null&&Fi(t,e)}function gA(e){const t=Dr(e);return t!==null&&Fi(t,e)?t:null}function _A(e){const t=Dr(e);return(t==="canvas"||t==="ask")&&Fi(t,e)}const uI=640,Zl=Ni,fI=20,pI=4,hI=20,Kl=320,mI=480,gI=480,_I=5e3,yA=(e,t)=>e.some(n=>n.surface===t),bA=(e,t=Date.now())=>e.some(n=>t-n.at<_I),yI=[],bI=4,vI=["chatMeasureWidth"],vA=Ar()(Ti((e,t)=>({finderFiles:Zf,setFinderFiles:n=>e({finderFiles:ba({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:Yf,agentAvatarSize:Gf,themeName:dp,rightSlotWidth:0,chatSidebarWidth:Zl,chatSidebarRegions:FE,chatSidebarView:bn,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:ep,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:dI,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:yI,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})},setCanvasOpen:n=>{e(r=>n?{...Dt("isCanvasOpen"),...Yt(r,"canvas")}:{isCanvasOpen:!1,...Kn(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...Dt("isRunPanelOpen"),...Yt(r,"run")}:{isRunPanelOpen:!1,...Kn(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...Dt("isBrowserPaneOpen"),...Yt(r,"browser")}:{isBrowserPaneOpen:!1,...Kn(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...Dt("isConsolePaneOpen"),...Yt(r,"console")}:{isConsolePaneOpen:!1,...Kn(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...Dt("isCodeReviewPaneOpen"),...Yt(r,"code")}:{isCodeReviewPaneOpen:!1,...Kn(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...Dt("isCodeReviewPaneOpen"),...Yt(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,i)=>{e(s=>{const a=typeof s.rightSlotKey=="string";if(n)return{...Dt("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:a?null:cI(s),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?i?.dismissSlot?{...c,...lI(s)}:{...c,...zl(s.rightSlotMemory,s.rightSlotKey,!1)}:s.rightSlotKey===null?i?.dismissSlot?{...c,rightSlotLegacySeed:null}:c:i?.dismissSlot?{...c,rightSlotLegacySeed:null}:{...c,...s.askDrawerEvictedPane===null?null:{[s.askDrawerEvictedPane]:!0}}})},requestAskOpen:(n,r="menu")=>{e({askOpenIntent:{scope:n,via:r}})},clearAskOpenIntent:n=>{e(r=>r.askOpenIntent?.scope===n?{askOpenIntent:null}:{})},setConsoleActiveSurface:n=>{e({consoleActiveSurface:n})},requestConsoleOpen:n=>{e({consoleOpenIntent:n})},clearConsoleOpenIntent:n=>{e(r=>r.consoleOpenIntent===n?{consoleOpenIntent:null}:{})},setConsoleLiveSurface:(n,r)=>{e(i=>{if(n===null||r<=0)return i.consoleLiveSurface===null?{}:{consoleLiveSurface:null};const s=i.consoleLiveSurface;return s?.sessionId===n&&s.count===r?{}:{consoleLiveSurface:{sessionId:n,count:r}}})},markConsoleUnseen:(n,r)=>{e(i=>i.consoleUnseen.some(s=>s.surface===r)?{}:{consoleUnseen:[...i.consoleUnseen,{sessionId:n,surface:r,at:Date.now()}]})},clearConsoleUnseen:n=>{const r=Array.isArray(n)?n:[n];e(i=>{const s=i.consoleUnseen.filter(a=>!r.includes(a.surface));return s.length===i.consoleUnseen.length?{}:{consoleUnseen:s}})},setRightSlotWidth:n=>{e({rightSlotWidth:n})},restoreDefaultRightSlotWidth:()=>{e({rightSlotWidth:0})},bindRightSlotKey:(n,r)=>{e(i=>{let s=i.rightSlotMemory,a=i.rightSlotLegacySeed;const c=r?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(s=sI(s,c,n)),n===null||(Sa(n)?a=null:a!==null&&Mr(s,n)===void 0&&(s=qf(s,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:s,rightSlotLegacySeed:a,...zl(s,n,i.isAskDrawerOpen)}})},setRightSlotRoute:n=>{const r=t().rightSlotRoute;r.mounted===n.mounted&&r.session===n.session||e({rightSlotRoute:{...n}})},setShortcutBinding:(n,r,i)=>{if(r===null){e(a=>{const c={...a.shortcutBindings};return delete c[n],{shortcutBindings:c}});return}const s=wa(r);s!==null&&eI(s,n,t().shortcutBindings,"linux",i)===null&&e(a=>({shortcutBindings:{...a.shortcutBindings,[n]:s}}))},clearShortcutBinding:n=>{e(r=>({shortcutBindings:{...r.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(r=>({...Dt("isRunPanelOpen"),...Yt(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(fa,Math.max(ua,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:Zl})},rememberMention:(n,r)=>{e(i=>{const s=i.mentionRecents,a=s?.cwd===n?s.paths:[],c=[r,...a.filter(l=>l!==r)].slice(0,fI);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(i=>({profileRecents:{...i.profileRecents,[n]:wI(i.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const i=EI(r.conversationRecents),s=SI(i,n);return s.length===i.length&&s.every((a,c)=>a===i[c])?r:{conversationRecents:s}})}}),{name:"ui-preferences-storage",version:bI,migrate:TI,partialize:II,merge:RI}));function wI(e,t){return[t,...e.filter(n=>n!==t)].slice(0,pI)}function SI(e,t){return[t,...e.filter(n=>n!==t)].slice(0,hI)}const kI=[];function EI(e){return Array.isArray(e)?e:kI}function II(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:r,consoleLiveSurface:i,askOpenIntent:s,isAskDrawerOpen:a,askDrawerScope:c,askDrawerEvictedPane:l,rightSlotRoute:d,isCanvasOpen:u,isRunPanelOpen:f,isBrowserPaneOpen:p,isConsolePaneOpen:g,isCodeReviewPaneOpen:y,rightSlotKey:m,...b}=e;return{...b,rightSlotMemory:xI(e.rightSlotMemory)}}function xI(e){return(e??ep).filter(([t])=>!Sa(t))}function RI(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:i,isBrowserPaneOpen:s,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:ba(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:oI(n.rightSlotMemory),rightSlotLegacySeed:Xf(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:tI(n.shortcutBindings)}}function TI(e,t){const n={...e??{}};if(t<1&&CI(n),t<2)for(const r of vI)delete n[r];if(t<3){let r=null;for(const i of ko)if(n[Wl(i)]===!0){r=i;break}r!==null&&(n.rightSlotLegacySeed=r);for(const i of ko)delete n[Wl(i)]}return t<4&&(n.finderFiles=ba(n.finderFiles)),n}function CI(e){const t=[["canvasWidth",800],["runPanelWidth",420],["browserPanelWidth",640],["consolePanelWidth",796]];let n=0;for(const[r,i]of t){const s=e[r];if(typeof s=="number"&&s>0&&s!==i){n=s;break}}for(const[r]of t)delete e[r];e.rightSlotWidth=n}const Eo=e=>e.replace(/\\/g,"/"),wA=()=>window.location.hash?Eo(window.location.hash.substring(1)):Eo(window.location.pathname),SA=(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,"/")},kA=(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 i=n[0]==="~"||n[0]==="",s=i?n.slice(0,2):n.slice(0,1),a=n.slice(s.length),c=y=>{const m=t-y.length-(y?3:2);let b=[];for(let _=a.length-1;_>=0;_-=1){const k=[a[_],...b];if(k.join("/").length>m)break;b=k}return b},l=(y,m)=>y?`${y}/…/${m.join("/")}`:`…/${m.join("/")}`,d=s.join("/"),u=c(d);if(u.length>0)return u.length===a.length?e:l(d,u);const f=i?n[0]:"",p=c(f);if(p.length>0)return l(f,p);const g=t-(f?`${f}/…/`.length:2);return g>0?l(f,[r.slice(-g)]):"…"},EA=(e,t)=>Eo(e).includes(t);export{tC as $,jS as A,vA as B,Le as C,lA as D,zE as E,o as F,Pd as G,ye as H,SS as I,kS as J,UT as K,ff as L,MT as M,pf as N,DT as O,wc as P,OT as Q,NT as R,Ge as S,$T as T,mf as U,jT as V,LT as W,hC as X,wA as Y,wf as Z,eC as _,Sx as a,UI as a$,Di as a0,kC as a1,EI as a2,u_ as a3,kT as a4,Ar as a5,pT as a6,VI as a7,qe as a8,Zs as a9,dE as aA,uE as aB,gb as aC,WS as aD,wx as aE,So as aF,aA as aG,Tr as aH,De as aI,Yl as aJ,Cp as aK,jp as aL,Np as aM,Bp as aN,$p as aO,Up as aP,Va as aQ,Hp as aR,Ya as aS,Gp as aT,Fp as aU,lC as aV,qS as aW,qT as aX,HT as aY,EA as aZ,FI as a_,Ti as aa,zm as ab,vx as ac,px as ad,eg as ae,tg as af,Rc as ag,KI as ah,ZI as ai,Rd as aj,Eo as ak,ay as al,BI as am,Xl as an,Qi as ao,am as ap,om as aq,WR as ar,dS as as,UR as at,BR as au,GR as av,tf as aw,xC as ax,lE as ay,IC as az,gx as b,zC as b$,$I as b0,LI as b1,HI as b2,mm as b3,st as b4,ir as b5,Ad as b6,Om as b7,gA as b8,uA as b9,_x as bA,Td as bB,cx as bC,tx as bD,Cd as bE,c_ as bF,vm as bG,hp as bH,wm as bI,_a as bJ,ix as bK,Al as bL,lx as bM,zS as bN,PE as bO,Bl as bP,jC as bQ,QC as bR,JC as bS,XC as bT,PC as bU,GT as bV,FT as bW,Sf as bX,cC as bY,qC as bZ,HC as b_,dT as ba,Ht as bb,rc as bc,Oo as bd,cg as be,xi as bf,vd as bg,vS as bh,PT as bi,Q as bj,AT as bk,yn as bl,po as bm,ho as bn,TT as bo,CT as bp,ET as bq,IT as br,xT as bs,fA as bt,bA as bu,_I as bv,yA as bw,h_ as bx,bx as by,yx as bz,kx as c,iC as c$,Rn as c0,bn as c1,CC as c2,Wf as c3,NC as c4,VC as c5,xr as c6,KC as c7,YC as c8,BC as c9,zI as cA,EC as cB,SA as cC,kA as cD,cA as cE,NI as cF,i0 as cG,Ix as cH,mA as cI,vo as cJ,dI as cK,Vn as cL,hA as cM,yC as cN,bC as cO,_C as cP,ma as cQ,ga as cR,ax as cS,ox as cT,mI as cU,Uf as cV,gI as cW,Kl as cX,pa as cY,NR as cZ,LR as c_,GC as ca,jl as cb,$C as cc,LC as cd,UC as ce,SE as cf,FC as cg,MC as ch,WC as ci,ZC as cj,AC as ck,BT as cl,Li as cm,OC as cn,nC as co,DC as cp,TC as cq,eA as cr,tA as cs,iA as ct,sA as cu,UE as cv,nA as cw,Rr as cx,rA as cy,oA as cz,Re as d,iv as d$,rC as d0,sC as d1,aC as d2,oC as d3,C_ as d4,jr as d5,mx as d6,sd as d7,oa as d8,uT as d9,Jf as dA,eI as dB,va as dC,dA as dD,hT as dE,sc as dF,Wt as dG,sn as dH,ym as dI,Hs as dJ,SC as dK,gC as dL,eE as dM,Ff as dN,Sp as dO,HE as dP,MI as dQ,Sa as dR,pA as dS,Wa as dT,jI as dU,PI as dV,js as dW,sr as dX,xp as dY,Lp as dZ,zp as d_,ZR as da,bT as db,vT as dc,bf as dd,$S as de,ji as df,QT as dg,JT as dh,hy as di,fT as dj,YR as dk,tS as dl,OS as dm,yf as dn,CS as dp,Tl as dq,zT as dr,aE as ds,YT as dt,RT as du,JI as dv,XI as dw,fx as dx,$i as dy,Ui as dz,Ex as e,by as e$,un as e0,Of as e1,uC as e2,Fk as e3,Tf as e4,dC as e5,pC as e6,mC as e7,ux as e8,hx as e9,Kg as eA,nx as eB,$R as eC,FR as eD,VR as eE,KR as eF,HR as eG,wn as eH,sx as eI,dx as eJ,rx as eK,Mx as eL,Bo as eM,Lo as eN,zt as eO,mt as eP,lR as eQ,dR as eR,aR as eS,oR as eT,eR as eU,Vx as eV,Yx as eW,Jx as eX,Qx as eY,pu as eZ,iR as e_,Ri as ea,Ye as eb,Tp as ec,GS as ed,_A as ee,wC as ef,ha as eg,vC as eh,$f as ei,iE as ej,ua as ek,qI as el,cc as em,Hg as en,ex as eo,Im as ep,nT as eq,rT as er,YI as es,QI as et,tT as eu,nf as ev,e0 as ew,Au as ex,Yf as ey,fu as ez,f_ as f,iT as f$,MR as f0,Ny as f1,sR as f2,Tv as f3,RR as f4,Eu as f5,CR as f6,ER as f7,IR as f8,TR as f9,nR as fA,$b as fB,uu as fC,eu as fD,Gx as fE,Co as fF,dc as fG,wa as fH,GE as fI,ty as fJ,qx as fK,Db as fL,rR as fM,cR as fN,tR as fO,My as fP,Fx as fQ,xy as fR,Hx as fS,zx as fT,Zx as fU,Wx as fV,Kx as fW,Xx as fX,DR as fY,RC as fZ,oT as f_,Iv as fa,hs as fb,xR as fc,Cv as fd,wR as fe,fR as ff,bR as fg,OR as fh,uR as fi,vR as fj,kR as fk,jR as fl,PR as fm,SR as fn,pR as fo,hR as fp,mR as fq,gR as fr,_R as fs,yR as ft,AR as fu,Sm as fv,km as fw,Em as fx,Gc as fy,$x as fz,jo as g,p0 as g0,cT as g1,sT as g2,aT as g3,lT as g4,Ux as g5,Bx as g6,Po as g7,zR as g8,mT as g9,$c as gA,Cx as gB,Ed as gC,Lx as gD,Dx as gE,KT as gF,QR as gG,eT as gH,XR as gI,qR as gJ,WT as gK,ZT as gL,cm as gM,lc as gN,gT as ga,bs as gb,yT as gc,_T as gd,wT as ge,lS as gf,ST as gg,JR as gh,zd as gi,vr as gj,Nx as gk,K_ as gl,Wd as gm,$o as gn,Bd as go,j_ as gp,M_ as gq,jx as gr,_m as gs,Px as gt,Tx as gu,Ax as gv,Lc as gw,Rx as gx,xx as gy,Ox as gz,id as h,Fm as i,Bm as j,Gm as k,Hm as l,Wp as m,fC as n,$k as o,WI as p,v_ as q,m_ as r,GI as s,DI as t,Pp as u,QS as v,Ke as w,VT as x,XT as y,DS as z};
64
+ */function Ir(){return Ir=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},Ir.apply(this,arguments)}const da=S.createContext(null),Bk=S.createContext(null),un=S.createContext(null),Mi=S.createContext(null),Tt=S.createContext({outlet:null,matches:[],isDataRoute:!1}),Mf=S.createContext(null);function mC(e,t){let{relative:n}=t===void 0?{}:t;Mn()||ke(!1);let{basename:r,navigator:i}=S.useContext(un),{hash:s,pathname:a,search:c}=zk(e,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:$t([r,a])),i.createHref({pathname:l,search:c,hash:s})}function Mn(){return S.useContext(Mi)!=null}function Di(){return Mn()||ke(!1),S.useContext(Mi).location}function Df(e){S.useContext(un).static||S.useLayoutEffect(e)}function Gk(){let{isDataRoute:e}=S.useContext(Tt);return e?nE():Hk()}function Hk(){Mn()||ke(!1);let e=S.useContext(da),{basename:t,future:n,navigator:r}=S.useContext(un),{matches:i}=S.useContext(Tt),{pathname:s}=Di(),a=JSON.stringify(ca(i,n.v7_relativeSplatPath)),c=S.useRef(!1);return Df(()=>{c.current=!0}),S.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=la(d,JSON.parse(a),s,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:$t([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,a,s,e])}function gC(){let{matches:e}=S.useContext(Tt),t=e[e.length-1];return t?t.params:{}}function zk(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=S.useContext(un),{matches:i}=S.useContext(Tt),{pathname:s}=Di(),a=JSON.stringify(ca(i,r.v7_relativeSplatPath));return S.useMemo(()=>la(e,JSON.parse(a),s,n==="path"),[e,a,s,n])}function Wk(e,t){return Zk(e,t)}function Zk(e,t,n,r){Mn()||ke(!1);let{navigator:i,static:s}=S.useContext(un),{matches:a}=S.useContext(Tt),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=Di(),f;if(t){var p;let _=typeof t=="string"?dn(t):t;d==="/"||(p=_.pathname)!=null&&p.startsWith(d)||ke(!1),f=_}else f=u;let g=f.pathname||"/",y=g;if(d!=="/"){let _=d.replace(/^\//,"").split("/");y="/"+g.replace(/^\//,"").split("/").slice(_.length).join("/")}let m=yk(e,{pathname:y}),b=Xk(m&&m.map(_=>Object.assign({},_,{params:Object.assign({},l,_.params),pathname:$t([d,i.encodeLocation?i.encodeLocation(_.pathname).pathname:_.pathname]),pathnameBase:_.pathnameBase==="/"?d:$t([d,i.encodeLocation?i.encodeLocation(_.pathnameBase).pathname:_.pathnameBase])})),a,n,r);return t&&b?S.createElement(Mi.Provider,{value:{location:Ir({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:Nt.Pop}},b):b}function Kk(){let e=tE(),t=Uk(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return S.createElement(S.Fragment,null,S.createElement("h2",null,"Unexpected Application Error!"),S.createElement("h3",{style:{fontStyle:"italic"}},t),n?S.createElement("pre",{style:i},n):null,null)}const Vk=S.createElement(Kk,null);class Yk extends S.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?S.createElement(Tt.Provider,{value:this.props.routeContext},S.createElement(Mf.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function Qk(e){let{routeContext:t,match:n,children:r}=e,i=S.useContext(da);return i&&i.static&&i.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=n.route.id),S.createElement(Tt.Provider,{value:t},r)}function Xk(e,t,n,r){var i;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var s;if(!n)return null;if(n.errors)e=n.matches;else if((s=r)!=null&&s.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,c=(i=n)==null?void 0:i.errors;if(c!=null){let u=a.findIndex(f=>f.route.id&&c?.[f.route.id]!==void 0);u>=0||ke(!1),a=a.slice(0,Math.min(a.length,u+1))}let l=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u<a.length;u++){let f=a[u];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(d=u),f.route.id){let{loaderData:p,errors:g}=n,y=f.route.loader&&p[f.route.id]===void 0&&(!g||g[f.route.id]===void 0);if(f.route.lazy||y){l=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}return a.reduceRight((u,f,p)=>{let g,y=!1,m=null,b=null;n&&(g=c&&f.route.id?c[f.route.id]:void 0,m=f.route.errorElement||Vk,l&&(d<0&&p===0?(rE("route-fallback"),y=!0,b=null):d===p&&(y=!0,b=f.route.hydrateFallbackElement||null)));let _=t.concat(a.slice(0,p+1)),k=()=>{let E;return g?E=m:y?E=b:f.route.Component?E=S.createElement(f.route.Component,null):f.route.element?E=f.route.element:E=u,S.createElement(Qk,{match:f,routeContext:{outlet:u,matches:_,isDataRoute:n!=null},children:E})};return n&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?S.createElement(Yk,{location:n.location,revalidation:n.revalidation,component:m,error:g,children:k(),routeContext:{outlet:null,matches:_,isDataRoute:!0}}):k()},null)}var Nf=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Nf||{}),Lf=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}(Lf||{});function Jk(e){let t=S.useContext(da);return t||ke(!1),t}function qk(e){let t=S.useContext(Bk);return t||ke(!1),t}function eE(e){let t=S.useContext(Tt);return t||ke(!1),t}function $f(e){let t=eE(),n=t.matches[t.matches.length-1];return n.route.id||ke(!1),n.route.id}function tE(){var e;let t=S.useContext(Mf),n=qk(),r=$f();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function nE(){let{router:e}=Jk(Nf.UseNavigateStable),t=$f(Lf.UseNavigateStable),n=S.useRef(!1);return Df(()=>{n.current=!0}),S.useCallback(function(i,s){s===void 0&&(s={}),n.current&&(typeof i=="number"?e.navigate(i):e.navigate(i,Ir({fromRouteId:t},s)))},[e,t])}const Fl={};function rE(e,t,n){Fl[e]||(Fl[e]=!0)}function _C(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function yC(e){let{to:t,replace:n,state:r,relative:i}=e;Mn()||ke(!1);let{future:s,static:a}=S.useContext(un),{matches:c}=S.useContext(Tt),{pathname:l}=Di(),d=Gk(),u=la(t,ca(c,s.v7_relativeSplatPath),l,i==="path"),f=JSON.stringify(u);return S.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:i}),[d,f,i,n,r]),null}function iE(e){ke(!1)}function bC(e){let{basename:t="/",children:n=null,location:r,navigationType:i=Nt.Pop,navigator:s,static:a=!1,future:c}=e;Mn()&&ke(!1);let l=t.replace(/^\/*/,"/"),d=S.useMemo(()=>({basename:l,navigator:s,static:a,future:Ir({v7_relativeSplatPath:!1},c)}),[l,c,s,a]);typeof r=="string"&&(r=dn(r));let{pathname:u="/",search:f="",hash:p="",state:g=null,key:y="default"}=r,m=S.useMemo(()=>{let b=Pf(u,l);return b==null?null:{location:{pathname:b,search:f,hash:p,state:g,key:y},navigationType:i}},[l,u,f,p,g,y,i]);return m==null?null:S.createElement(un.Provider,{value:d},S.createElement(Mi.Provider,{children:n,value:m}))}function vC(e){let{children:t,location:n}=e;return Wk(bo(t),n)}new Promise(()=>{});function bo(e,t){t===void 0&&(t=[]);let n=[];return S.Children.forEach(e,(r,i)=>{if(!S.isValidElement(r))return;let s=[...t,i];if(r.type===S.Fragment){n.push.apply(n,bo(r.props.children,s));return}r.type!==iE&&ke(!1),!r.props.index||!r.props.children||ke(!1);let a={id:r.props.id||s.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=bo(r.props.children,s)),n.push(a)}),n}const Ni=260,ua=220,fa=320,Uf=56,pa=480,wC=8,ha=44,ma=400,Ff=1200;function ga(e){return Math.max(0,Math.min(Ff,e-pa))}function vo(e){return ga(e)>=ma?"docked":"overlay"}const sE=48,oE=16;function SC(e,t){if(vo(e)==="docked")return{mode:"docked",width:Math.min(t,ga(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,ma),e-sE));return e-n>=oE?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function kC({capacity:e,min:t,max:n,drawn:r}){const i=e>=t;return i?{resizable:i,value:Math.min(Math.max(r,t),e),minWidth:t,maxWidth:Math.min(n,e)}:{resizable:i,value:r,minWidth:r,maxWidth:r}}function aE(e,t=Ni,n=ha){return vo(e-Bf(t)-n)==="overlay"&&vo(e-Uf-n)==="docked"}function Bf(e){return Number.isNaN(e)?Ni:Math.min(fa,Math.max(ua,e))}function cE(e,t=ha){return Math.max(0,Math.min(fa,e-pa-t))}function EC(e,t,n=Ni,r=!1,i=ha){const s=!t&&r&&aE(e,n,i),a=t||s,c=cE(e,i);return{mode:a?"strip":"docked",width:a?Uf:Math.min(Bf(n),c),collapsed:a,resizable:!a&&c>=ua}}function IC(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const xC=e=>e?"⌘B":"Ctrl+B",lE="data-canvas-shortcuts",dE=`[${lE}]`,uE=e=>Gf(e,dE),fE='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',RC=e=>Gf(e,fE);function Gf(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const TC=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&uE(e.target)?"new-file":null},Hf="small",pE=["small","medium","large"],zf="before:absolute before:-inset-0.5 before:content-['']",hE={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:zf},medium:{px:28,className:"size-7",glyphClassName:"size-3.5",hitClassName:""},large:{px:36,className:"size-9",glyphClassName:"size-4",hitClassName:""}},mE={small:{px:4,className:"mb-1"},medium:{px:6,className:"mb-1.5"},large:{px:8,className:"mb-2"}},CC={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:zf,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 AC(e){for(const t of pE)if(e===t)return t;return Hf}function OC(e){return hE[e].px+mE[e].px}const gE=["active","created"],PC={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"},_E=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function Li(e){return _E.has(e.status?.code??"")}const yE=new Set(["approval","answer"]);function bE(e){return yE.has(e.status?.code??"")}const vE=24*60*60*1e3,wE=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function _a(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 SE="last_user_at";function kE(e){const t=e[SE],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 EE(e,t,n){if(Li(e))return"running";const r=_a(e,n);if(r===null)return"older";const i=wE(t);return r>=i?"today":r>=i-6*vE?"week":"older"}function jC(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const i of e)r[EE(i,t,n)].push(i);return r}function Wf(e,t,n){const r=_a(e,n);if(r===null)return null;const i=Math.floor(Math.max(0,t-r)/6e4);if(i<1)return{unit:"now",count:0};if(i<60)return{unit:"minute",count:i};const s=Math.floor(i/60);if(s<24)return{unit:"hour",count:s};const a=Math.floor(s/24);return a<7?{unit:"day",count:a}:a<365?{unit:"week",count:Math.floor(a/7)}:{unit:"year",count:Math.floor(a/365)}}function MC(e,t,n){const r=Wf(e,t,n);return r?h("ui.chat.sidebar_view.relative_short",r):""}function DC(e,t,n){const r=Wf(e,t,n);return r?n==="created"?h("ui.chat.sidebar_view.relative_created",r):h("ui.chat.sidebar_view.relative_active",r):""}const wo=["pinned","running","today","week","older","agents","teams"],NC={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 LC(e){return e==="agents"||e==="teams"}const xr=8;function IE(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function $C(e,t){return{...e,[t]:(e[t]??xr)+xr}}function UC(e,t,n,r,i){const s=!(e[n]??r);return{expanded:{...e,[n]:s},caps:!s&&!i?IE(t,n):t}}function FC(e,t,n,r){return(e||t!=="")&&(r>xr||n.trim()!=="")}const BC="Collapse, then reopen, to restore the compact list";function GC(e){return(e??xr)>xr}const HC=e=>`section-grown-hint-${e}`,xE=e=>e===1?"Show 1 more":`Show ${e} more`;function zC(e,t){return`${xE(e)} ${t}`}const bn={hidden:[],order:[...wo],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},RE=10,Zn=[25,50],TE=50,CE=500,AE=64;function Rn(e){const t=Math.max(0,Math.floor(e));return t===0?RE:t<=Zn.length?Zn[t-1]:Zn[Zn.length-1]+(t-Zn.length)*TE}function WC(e,t){const n=Rn(e+1)-Rn(e),r=Math.max(0,Math.min(n,t));return r===1?"Show 1 more chat":`Show ${r} more chats`}function ZC(e,t,n){const r=Rn(t+1)-Rn(t),i=Rn(t),s=Math.min(i+r,e.length);let a=0;for(let l=i;l<s;l+=1)ya(e[l])&&(a+=1);const c=Math.max(0,s-i-a);return c>0?c:Math.max(0,Math.min(r,n))}function ya(e){return Li(e)}function OE(e){return bE(e)?0:Li(e)?1:2}function PE(e,t){return Li(e)?kE(e):_a(e,t)}function jE(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function KC(e,t,n){const r=e.map((i,s)=>({row:i,index:s,lane:t==="active-first"?OE(i):0,at:PE(i,n)}));return r.sort((i,s)=>i.lane-s.lane||jE(i.at,s.at)||i.index-s.index),r.map(i=>i.row)}function VC(e,t){const{limit:n,currentId:r,searching:i=!1}=t;if(i)return{rows:[...e],lifted:!1,remaining:0};const s=[];let a=Math.max(0,n);for(const d of e){if(a>0){s.push(d),a-=1;continue}ya(d)&&s.push(d)}const c=Math.max(0,e.length-s.length);if(!r)return{rows:s,lifted:!1,remaining:c};const l=e.find(d=>d.session_id===r)??null;return l===null||s.includes(l)?{rows:s,lifted:!1,remaining:c}:{rows:[l,...s],lifted:!0,remaining:c}}function YC(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=Rn(t.loads),r=[];let i=n;for(const l of e){if(ya(l)){r.push(l);continue}i>0&&(r.push(l),i-=1)}const s=t.currentId,a=s==null?null:e.find(l=>l.session_id===s)??null,c=a!==null&&!r.includes(a);return{rows:c&&a!==null?[a,...r]:r,lifted:c,hidden:e.length-r.length-(c?1:0),held:e.length}}function QC(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 ME="mt-4",DE="mt-2";function XC(e){return e?ME:DE}function JC(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function qC(e,t){if(t==="section")return null;if(t==="flat")return[{key:"all",label:"",rows:[...e]}];const n=new Map;for(const s of e){const a=s.binding?.team||s.binding?.agent||"",c=a||"ungrouped",l=n.get(c)??{key:c,label:a||"Ungrouped",rows:[]};l.rows.push(s),n.set(c,l)}const r=[...n.values()],i=r.findIndex(s=>s.key==="ungrouped");return i>0&&r.push(...r.splice(i,1)),r}function NE(e,t){return!e.hidden.includes(t)}function Zf(e){return e.order.filter(t=>NE(e,t))}function eA(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function tA(e,t,n){const r=Zf(e),i=r.indexOf(t),s=r[i+n];if(i<0||s===void 0)return e;const a=e.order.indexOf(t),c=e.order.indexOf(s),l=[...e.order];return l[a]=s,l[c]=t,{...e,order:l}}const LE=["running","today","week","older"];function Bl(e){return LE.includes(e)}function nA(e,t,n,r){if(!Bl(t)||r&&!r(t))return!1;const i=Zf(e),s=i.indexOf(t);if(s<0)return!1;const a=i[s+n];return a===void 0||!Bl(a)?!1:r?r(a):!0}const $E=["section","agent","flat"],UE=["active-first","recent"];function rA(e){if(typeof e!="object"||e===null)return bn;const t=e,n=new Set(wo),r=[];if(Array.isArray(t.order))for(const p of t.order)typeof p=="string"&&n.has(p)&&(r.includes(p)||r.push(p));for(const p of wo)r.includes(p)||r.push(p);const i=[];if(Array.isArray(t.hidden))for(const p of t.hidden)typeof p=="string"&&n.has(p)&&(i.includes(p)||i.push(p));const s=$E.includes(t.groupBy)?t.groupBy:bn.groupBy,a=gE.includes(t.basis)?t.basis:bn.basis,c=UE.includes(t.orderBy)?t.orderBy:bn.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(CE,Math.floor(t.loads)):0,d=[];if(Array.isArray(t.pinnedAgents)){for(const p of t.pinnedAgents)if(typeof p=="string"&&p!==""&&!d.includes(p)){if(d.length>=AE)break;d.push(p)}}const u=[],f=new Set;if(Array.isArray(t.pins))for(const p of t.pins)typeof p=="string"&&p.length!==0&&(f.has(p)||(f.add(p),u.push(p)));return{hidden:i,order:r,groupBy:s,tagsEnabled:typeof t.tagsEnabled=="boolean"?t.tagsEnabled:!1,autoTagForks:typeof t.autoTagForks=="boolean"?t.autoTagForks:bn.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const Kf={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},FE=["recent","name","kind","modified","created","size"],BE=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function ba(e){const t=e&&typeof e=="object"?e:{};return{sort:FE.includes(t.sort??"")?t.sort:Kf.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=>[Rr,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>BE.includes(n)))]:[]}}const Rr="Attachments";function iA(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,i)=>{const s=n(r),a=n(i);if(s===null||a===null)return s===a?0:s===null?1:-1;const c=typeof s=="string"&&typeof a=="string"?s.localeCompare(a,void 0,{numeric:!0}):Number(s)-Number(a);return(t.order==="asc"?c:-c)||r.mentioned-i.mentioned})}const GE=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 sA(e,t,n,r,i=[]){const s=e.filter(l=>l.highlighted),a=e.filter(l=>!l.highlighted),c=[];if(i.length&&c.push({id:Rr,label:h("ui.canvas.files.attachments"),items:i,open:n||!r.has(Rr),highlights:!1}),s.length&&c.push({id:"Highlights",label:h("ui.canvas.finder_layout.highlights"),items:s,open:n||!r.has("Highlights"),highlights:!0}),s.length&&a.length&&(c.push({id:"Working files",label:h("ui.canvas.finder_layout.working_files"),items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return c;if(!t.group)a.length&&c.push({id:"Files",label:h("ui.canvas.finder_layout.files"),items:a,open:!0,highlights:!1});else for(const l of["Images","Videos","Sounds","Documents","Spreadsheets","Other"]){const d=a.filter(u=>GE(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const HE=32,oA=4,Vf=32,Yf=18;function aA(e){return e.height-Vf-(e.kind==="tiles"&&e.section.id===Rr?Yf:0)}function cA(e,t,n){const r=[],i=new Map,s=Math.max(136,t-16),a=Math.max(1,Math.floor((s+4)/140));let c=0;const l=(d,u,f,p,g=1)=>{p.forEach((y,m)=>i.set(y.row.document.id,{band:r.length,column:m})),r.push({section:d,kind:u,height:f,top:c,items:p,cols:g}),c+=f};for(const d of e)if(l(d,"header",HE,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(d.id===Rr){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 p=(s-4*(a-1))/a,g=Math.round((p-8)*3/4)+Vf+Yf;for(let y=0;y<f.length;y+=a)l(d,"tiles",g,f.slice(y,y+a),a)}else if(n&&d.id==="Images"){const u=(s-4*(a-1))/a,f=Math.round((u-8)*3/4)+32;for(let p=0;p<d.items.length;p+=a)l(d,"tiles",f,d.items.slice(p,p+a),a)}else if(n&&d.id==="Videos")for(const u of d.items)l(d,"video",Math.min(Math.round((s-8)*9/16),280)+32,[u]);else if(n&&d.id==="Sounds")for(const u of d.items)l(d,"audio",80,[u]);else for(const u of d.items)l(d,"compact",36,[u]);return{bands:r,height:c,columns:a,positions:i}}function lA(e,t,n,r){const i=Math.max(600,n*.75);let s=0,a=e.bands.length;for(;s<a;){const d=s+a>>>1,u=e.bands[d];u.top+u.height<t-i?s=d+1:a=d}const c=new Set;for(let d=s;d<e.bands.length&&e.bands[d].top<=t+n+i;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 dA(e,t,n,r){const i=e.positions.get(t);if(!i)return null;const s=e.bands[i.band],a=e.bands.filter(u=>u.section.id===s.section.id&&u.items.length);if(n==="Home")return a[0]?.items[0]?.row.document.id??null;if(n==="End")return a.at(-1)?.items.at(-1)?.row.document.id??null;if(n==="ArrowLeft"||n==="ArrowRight")return s.items[i.column+(n==="ArrowLeft"?-1:1)]?.row.document.id??null;const c=n==="ArrowUp"||n==="PageUp"?-1:1,l=s.top+(n.startsWith("Page")?r*c:c);let d=i.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(i.column,u.items.length-1)].row.document.id}if(n.startsWith("Page")){const u=e.bands.filter(p=>p.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 zE="both",Qf="by-turn",So=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function uA(e){for(const t of So)if(e===t.value)return t.value;return Qf}function fA(e){return So.find(t=>t.value===e)?.label??So[0].label}const pA="primary+alt+shift+space",WE=/^f([1-9]|1[0-9]|2[0-4])$/;function ZE(e){return WE.test(e)}function KE(e,t){const n=VE(e,t);return t==="mac"?n.join(""):n.join("+")}function VE(e,t){const r=t==="mac"?{primary:"⌘",meta:"⌘",ctrl:"⌃",alt:"⌥",shift:"⇧"}:{primary:"Ctrl",meta:t==="win"?"Win":"Super",ctrl:"Ctrl",alt:"Alt",shift:"Shift"},i={space:"Space",backspace:"Backspace",delete:"Delete",insert:"Insert",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown",up:"Up",down:"Down",left:"Left",right:"Right"};return e.split("+").map(s=>s.trim().toLowerCase()).filter(s=>s.length>0).map(s=>s in r?r[s]:s in i?i[s]:ZE(s)||s.length===1?s.toUpperCase():s)}const $i=[{id:"panel.console",get label(){return h("ui.settings.shortcuts.action.open_console")},get category(){return h("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return h("ui.settings.shortcuts.action.open_canvas")},get category(){return h("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return h("ui.settings.shortcuts.action.open_run_details")},get category(){return h("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return h("ui.settings.shortcuts.action.open_asks")},get category(){return h("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return h("ui.settings.shortcuts.action.open_browser")},get category(){return h("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return h("ui.settings.shortcuts.action.open_code_review")},get category(){return h("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],YE=new Map($i.map(e=>[e.id,e])),QE=e=>YE.get(e),XE=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 JE 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,i]of this)t.call(n,i,r,this)}[Symbol.iterator](){return this.entries()}}const va=new JE([["primary+p",()=>h("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>h("ui.settings.shortcuts.reserved.palette_commands")],["primary+k",()=>h("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>h("ui.settings.shortcuts.reserved.new_chat")],["primary+b",()=>h("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>h("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>h("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>h("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>h("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>h("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>h("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>h("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>h("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>h("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>h("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>h("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>h("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>h("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>h("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>h("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>h("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>h("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>h("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>h("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>h("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>h("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>h("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>h("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>h("ui.settings.shortcuts.reserved.browser_last_tab"):()=>h("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>h("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>h("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>h("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>h("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>h("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>h("ui.settings.shortcuts.reserved.close")],["primary+m",()=>h("ui.settings.shortcuts.reserved.minimise")]]),qE=["primary","alt","shift"],eI={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},tI=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),nI=e=>tI.has(e)||/^[a-z0-9]$/.test(e);function wa(e){if(typeof e!="string")return null;const t=e.toLowerCase().split("+").map(s=>s.trim()).filter(s=>s.length>0);if(t.length===0)return null;const n=t[t.length-1];if(!nI(n))return null;const r=new Set;for(const s of t.slice(0,-1)){const a=eI[s];if(a===void 0)return null;r.add(a)}return[...qE.filter(s=>r.has(s)),n].join("+")}const Xf=e=>e.split("+").includes("primary");function Ui(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!va.has(n)?n:QE(e)?.defaultChord??null}function hA(e){const t=new Map;for(const n of $i){const r=Ui(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const rI=e=>e==="mac"?h("ui.settings.shortcuts.capture.needs_modifier_mac"):h("ui.settings.shortcuts.capture.needs_modifier");function iI(e,t,n,r="linux",i=new Map){const s=e===null?null:wa(e);if(s===null)return h("ui.settings.shortcuts.capture.unbindable");if(!Xf(s))return rI(r);const a=va.get(s);if(a!==void 0)return a;const c=i.get(s);if(c!==void 0)return h("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of $i)if(l.id!==t&&Ui(l.id,n)===s)return h("ui.settings.shortcuts.capture.already_assigned",{label:l.label});return null}function sI(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const i of $i){const s=t[i.id];if(s===null){r[i.id]=null;continue}const a=typeof s=="string"?wa(s):null,c=a!==null&&XE.has(a),l=a!==null&&Xf(a)&&(c||!va.has(a)&&!n.has(a))?a:null;l!==null&&(r[i.id]=l);const d=Ui(i.id,r);d!==null&&n.add(d)}return r}function mA(e,t,n){const r=Ui(e,t);return r===null?null:Jf(r,n)}function Jf(e,t){return KE(e,t)}function gA(e,t){const n=e.split("+"),r=n[n.length-1],i=n.slice(0,-1).map(s=>s==="primary"?t==="mac"?"Meta":"Control":s==="shift"?"Shift":s==="alt"?"Alt":s);return{glyph:Jf(e,t),aria:[...i,r.length===1?r.toUpperCase():r].join("+")}}const Gl=64,ko=["canvas","run","browser","console","code"],oI={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function qf(e){return typeof e=="string"&&ko.includes(e)}function Sa(e){return e.startsWith("draft:")}function Mr(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function ka(e){return e.length>Gl?e.slice(e.length-Gl):e}function ep(e,t,n){return ka([...e.filter(([r])=>r!==t),[t,n]])}function aI(e,t,n){return Mr(e,t)!==n?e:e.filter(([r])=>r!==t)}function cI(e,t){return Mr(e,t)===void 0?e:e.filter(([n])=>n!==t)}function lI(e,t,n){const r=Mr(e,t);return r===void 0?e:ka([...e.filter(([i])=>i!==t&&i!==n),[n,r]])}const Hl=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function zl(e,t,n){if(n||typeof t!="string")return Hl;const r=Mr(e,t);return r===void 0?Hl:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function dI(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,i]=n;typeof r!="string"||r===""||Sa(r)||qf(i)&&(t.delete(r),t.set(r,i))}return ka([...t.entries()])}function _A(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 Wl(e){return oI[e]}const uI={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},Dr=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,Fi=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,fI=e=>{const t=Dr(e);return t===null||t==="ask"?null:uI[t]},Dt=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Yt=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:ep(e.rightSlotMemory,n,t)}},Kn=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=aI(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},pI=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=cI(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},hI=Object.freeze({mounted:!1,session:!1}),tp=Object.freeze([]);function yA(e,t){const n=Dr(t);if(n===null||!Fi(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=Vn(ma,t.rightSlotWidth);break;case"run":r=Vn(Kl,t.rightSlotWidth);break;case"browser":r=Vn(bI,t.rightSlotWidth);break;case"console":r=Vn(vI,t.rightSlotWidth);break;case"code":r=Vn(Kl,t.rightSlotWidth);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,ga(e)):Math.min(r,Math.max(0,e-pa))}function Vn(e,t){return Math.min(Ff,Math.max(e,t||mI))}function bA(e){const t=Dr(e);return t!==null&&Fi(t,e)}function vA(e){const t=Dr(e);return t!==null&&Fi(t,e)?t:null}function wA(e){const t=Dr(e);return(t==="canvas"||t==="ask")&&Fi(t,e)}const mI=640,Zl=Ni,gI=20,_I=4,yI=20,Kl=320,bI=480,vI=480,wI=5e3,SA=(e,t)=>e.some(n=>n.surface===t),kA=(e,t=Date.now())=>e.some(n=>t-n.at<wI),SI=[],kI=4,EI=["chatMeasureWidth"],EA=Ar()(Ti((e,t)=>({finderFiles:Kf,setFinderFiles:n=>e({finderFiles:ba({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:Qf,agentAvatarSize:Hf,themeName:up,rightSlotWidth:0,chatSidebarWidth:Zl,chatSidebarRegions:zE,chatSidebarView:bn,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:tp,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:hI,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:SI,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})},setCanvasOpen:n=>{e(r=>n?{...Dt("isCanvasOpen"),...Yt(r,"canvas")}:{isCanvasOpen:!1,...Kn(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...Dt("isRunPanelOpen"),...Yt(r,"run")}:{isRunPanelOpen:!1,...Kn(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...Dt("isBrowserPaneOpen"),...Yt(r,"browser")}:{isBrowserPaneOpen:!1,...Kn(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...Dt("isConsolePaneOpen"),...Yt(r,"console")}:{isConsolePaneOpen:!1,...Kn(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...Dt("isCodeReviewPaneOpen"),...Yt(r,"code")}:{isCodeReviewPaneOpen:!1,...Kn(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...Dt("isCodeReviewPaneOpen"),...Yt(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,i)=>{e(s=>{const a=typeof s.rightSlotKey=="string";if(n)return{...Dt("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:a?null:fI(s),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?i?.dismissSlot?{...c,...pI(s)}:{...c,...zl(s.rightSlotMemory,s.rightSlotKey,!1)}:s.rightSlotKey===null?i?.dismissSlot?{...c,rightSlotLegacySeed:null}:c:i?.dismissSlot?{...c,rightSlotLegacySeed:null}:{...c,...s.askDrawerEvictedPane===null?null:{[s.askDrawerEvictedPane]:!0}}})},requestAskOpen:(n,r="menu")=>{e({askOpenIntent:{scope:n,via:r}})},clearAskOpenIntent:n=>{e(r=>r.askOpenIntent?.scope===n?{askOpenIntent:null}:{})},setConsoleActiveSurface:n=>{e({consoleActiveSurface:n})},requestConsoleOpen:n=>{e({consoleOpenIntent:n})},clearConsoleOpenIntent:n=>{e(r=>r.consoleOpenIntent===n?{consoleOpenIntent:null}:{})},setConsoleLiveSurface:(n,r)=>{e(i=>{if(n===null||r<=0)return i.consoleLiveSurface===null?{}:{consoleLiveSurface:null};const s=i.consoleLiveSurface;return s?.sessionId===n&&s.count===r?{}:{consoleLiveSurface:{sessionId:n,count:r}}})},markConsoleUnseen:(n,r)=>{e(i=>i.consoleUnseen.some(s=>s.surface===r)?{}:{consoleUnseen:[...i.consoleUnseen,{sessionId:n,surface:r,at:Date.now()}]})},clearConsoleUnseen:n=>{const r=Array.isArray(n)?n:[n];e(i=>{const s=i.consoleUnseen.filter(a=>!r.includes(a.surface));return s.length===i.consoleUnseen.length?{}:{consoleUnseen:s}})},setRightSlotWidth:n=>{e({rightSlotWidth:n})},restoreDefaultRightSlotWidth:()=>{e({rightSlotWidth:0})},bindRightSlotKey:(n,r)=>{e(i=>{let s=i.rightSlotMemory,a=i.rightSlotLegacySeed;const c=r?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(s=lI(s,c,n)),n===null||(Sa(n)?a=null:a!==null&&Mr(s,n)===void 0&&(s=ep(s,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:s,rightSlotLegacySeed:a,...zl(s,n,i.isAskDrawerOpen)}})},setRightSlotRoute:n=>{const r=t().rightSlotRoute;r.mounted===n.mounted&&r.session===n.session||e({rightSlotRoute:{...n}})},setShortcutBinding:(n,r,i)=>{if(r===null){e(a=>{const c={...a.shortcutBindings};return delete c[n],{shortcutBindings:c}});return}const s=wa(r);s!==null&&iI(s,n,t().shortcutBindings,"linux",i)===null&&e(a=>({shortcutBindings:{...a.shortcutBindings,[n]:s}}))},clearShortcutBinding:n=>{e(r=>({shortcutBindings:{...r.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(r=>({...Dt("isRunPanelOpen"),...Yt(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(fa,Math.max(ua,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:Zl})},rememberMention:(n,r)=>{e(i=>{const s=i.mentionRecents,a=s?.cwd===n?s.paths:[],c=[r,...a.filter(l=>l!==r)].slice(0,gI);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(i=>({profileRecents:{...i.profileRecents,[n]:II(i.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const i=TI(r.conversationRecents),s=xI(i,n);return s.length===i.length&&s.every((a,c)=>a===i[c])?r:{conversationRecents:s}})}}),{name:"ui-preferences-storage",version:kI,migrate:PI,partialize:CI,merge:OI}));function II(e,t){return[t,...e.filter(n=>n!==t)].slice(0,_I)}function xI(e,t){return[t,...e.filter(n=>n!==t)].slice(0,yI)}const RI=[];function TI(e){return Array.isArray(e)?e:RI}function CI(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:r,consoleLiveSurface:i,askOpenIntent:s,isAskDrawerOpen:a,askDrawerScope:c,askDrawerEvictedPane:l,rightSlotRoute:d,isCanvasOpen:u,isRunPanelOpen:f,isBrowserPaneOpen:p,isConsolePaneOpen:g,isCodeReviewPaneOpen:y,rightSlotKey:m,...b}=e;return{...b,rightSlotMemory:AI(e.rightSlotMemory)}}function AI(e){return(e??tp).filter(([t])=>!Sa(t))}function OI(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:i,isBrowserPaneOpen:s,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:ba(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:dI(n.rightSlotMemory),rightSlotLegacySeed:qf(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:sI(n.shortcutBindings)}}function PI(e,t){const n={...e??{}};if(t<1&&jI(n),t<2)for(const r of EI)delete n[r];if(t<3){let r=null;for(const i of ko)if(n[Wl(i)]===!0){r=i;break}r!==null&&(n.rightSlotLegacySeed=r);for(const i of ko)delete n[Wl(i)]}return t<4&&(n.finderFiles=ba(n.finderFiles)),n}function jI(e){const t=[["canvasWidth",800],["runPanelWidth",420],["browserPanelWidth",640],["consolePanelWidth",796]];let n=0;for(const[r,i]of t){const s=e[r];if(typeof s=="number"&&s>0&&s!==i){n=s;break}}for(const[r]of t)delete e[r];e.rightSlotWidth=n}const Eo=e=>e.replace(/\\/g,"/"),IA=()=>window.location.hash?Eo(window.location.hash.substring(1)):Eo(window.location.pathname),xA=(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,"/")},RA=(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 i=n[0]==="~"||n[0]==="",s=i?n.slice(0,2):n.slice(0,1),a=n.slice(s.length),c=y=>{const m=t-y.length-(y?3:2);let b=[];for(let _=a.length-1;_>=0;_-=1){const k=[a[_],...b];if(k.join("/").length>m)break;b=k}return b},l=(y,m)=>y?`${y}/…/${m.join("/")}`:`…/${m.join("/")}`,d=s.join("/"),u=c(d);if(u.length>0)return u.length===a.length?e:l(d,u);const f=i?n[0]:"",p=c(f);if(p.length>0)return l(f,p);const g=t-(f?`${f}/…/`.length:2);return g>0?l(f,[r.slice(-g)]):"…"},TA=(e,t)=>Eo(e).includes(t);export{sC as $,LS as A,EA as B,Le as C,pA as D,VE as E,o as F,Pd as G,ye as H,xS as I,RS as J,HT as K,pf as L,$T as M,hf as N,UT as O,wc as P,DT as Q,FT as R,Ge as S,GT as T,gf as U,LT as V,BT as W,yC as X,IA as Y,Sf as Z,iC as _,xx as a,HI as a$,Di as a0,RC as a1,TI as a2,f_ as a3,RT as a4,Ar as a5,_T as a6,JI as a7,qe as a8,Zs as a9,hE as aA,mE as aB,_b as aC,YS as aD,Ix as aE,So as aF,uA as aG,Tr as aH,De as aI,Yl as aJ,Ap as aK,Mp as aL,Lp as aM,Gp as aN,Up as aO,Fp as aP,Va as aQ,zp as aR,Ya as aS,Hp as aT,Bp as aU,pC as aV,rk as aW,rC as aX,KT as aY,TA as aZ,zI as a_,Ti as aa,Wm as ab,Ex as ac,_x as ad,tg as ae,ng as af,Rc as ag,XI as ah,QI as ai,Rd as aj,Eo as ak,cy as al,WI as am,Jl as an,Qi as ao,cm as ap,am as aq,YR as ar,hS as as,HR as at,WR as au,ZR as av,nf as aw,AC as ax,pE as ay,CC as az,vx as b,VC as b$,GI as b0,BI as b1,KI as b2,gm as b3,st as b4,ir as b5,Ad as b6,Pm as b7,vA as b8,mA as b9,wx as bA,Td as bB,fx as bC,sx as bD,Cd as bE,l_ as bF,wm as bG,mp as bH,Sm as bI,_a as bJ,cx as bK,Al as bL,px as bM,VS as bN,NE as bO,Bl as bP,LC as bQ,eA as bR,tA as bS,nA as bT,NC as bU,ZT as bV,zT as bW,kf as bX,fC as bY,rA as bZ,KC as b_,hT as ba,Ht as bb,rc as bc,Oo as bd,lg as be,xi as bf,vd as bg,ES as bh,NT as bi,Q as bj,MT as bk,yn as bl,po as bm,ho as bn,PT as bo,jT as bp,TT as bq,CT as br,AT as bs,gA as bt,kA as bu,wI as bv,SA as bw,m_ as bx,kx as by,Sx as bz,Rx as c,cC as c$,Rn as c0,bn as c1,jC as c2,Zf as c3,FC as c4,JC as c5,xr as c6,XC as c7,qC as c8,WC as c9,VI as cA,TC as cB,xA as cC,RA as cD,fA as cE,FI as cF,c0 as cG,Cx as cH,bA as cI,vo as cJ,hI as cK,Vn as cL,yA as cM,SC as cN,kC as cO,wC as cP,ma as cQ,ga as cR,ux as cS,dx as cT,bI as cU,Ff as cV,vI as cW,Kl as cX,pa as cY,FR as cZ,BR as c_,ZC as ca,jl as cb,GC as cc,BC as cd,HC as ce,xE as cf,zC as cg,$C as ch,YC as ci,QC as cj,MC as ck,WT as cl,Li as cm,DC as cn,oC as co,UC as cp,PC as cq,iA as cr,sA as cs,cA as ct,lA as cu,HE as cv,oA as cw,Rr as cx,aA as cy,dA as cz,Re as d,sv as d$,aC as d0,lC as d1,uC as d2,dC as d3,A_ as d4,jr as d5,bx as d6,sd as d7,oa as d8,mT as d9,Jf as dA,iI as dB,va as dC,hA as dD,yT as dE,sc as dF,Wt as dG,sn as dH,bm as dI,Hs as dJ,xC as dK,vC as dL,iE as dM,Bf as dN,kp as dO,KE as dP,$I as dQ,Sa as dR,_A as dS,Wa as dT,LI as dU,NI as dV,js as dW,sr as dX,Rp as dY,$p as dZ,Wp as d_,QR as da,kT as db,ET as dc,vf as dd,GS as de,ji as df,eC as dg,tC as dh,my as di,gT as dj,qR as dk,sS as dl,DS as dm,bf as dn,jS as dp,Tl as dq,VT as dr,uE as ds,qT as dt,OT as du,tx as dv,nx as dw,gx as dx,$i as dy,Ui as dz,Tx as e,vy as e$,un as e0,Pf as e1,mC as e2,zk as e3,Cf as e4,hC as e5,_C as e6,bC as e7,mx as e8,yx as e9,Vg as eA,ox as eB,GR as eC,zR as eD,JR as eE,XR as eF,KR as eG,wn as eH,lx as eI,hx as eJ,ax as eK,$x as eL,Bo as eM,Lo as eN,zt as eO,mt as eP,pR as eQ,hR as eR,uR as eS,dR as eT,iR as eU,Jx as eV,qx as eW,tR as eX,eR as eY,pu as eZ,cR as e_,Ri as ea,Ye as eb,Cp as ec,ZS as ed,wA as ee,IC as ef,ha as eg,EC as eh,Uf as ei,cE as ej,ua as ek,rx as el,cc as em,zg as en,ix as eo,xm as ep,oT as eq,aT as er,qI as es,ex as et,sT as eu,rf as ev,i0 as ew,Ou as ex,Qf as ey,fu as ez,p_ as f,cT as f$,$R as f0,Ly as f1,lR as f2,Ov as f3,OR as f4,Iu as f5,jR as f6,TR as f7,CR as f8,PR as f9,oR as fA,Ub as fB,uu as fC,eu as fD,Zx as fE,Co as fF,dc as fG,wa as fH,ZE as fI,ny as fJ,rR as fK,Nb as fL,aR as fM,fR as fN,sR as fO,Dy as fP,zx as fQ,Ry as fR,Kx as fS,Vx as fT,Qx as fU,Yx as fV,Xx as fW,nR as fX,UR as fY,OC as fZ,dT as f_,Tv as fa,hs as fb,AR as fc,Pv as fd,IR as fe,gR as ff,kR as fg,DR as fh,mR as fi,ER as fj,RR as fk,LR as fl,NR as fm,xR as fn,_R as fo,yR as fp,bR as fq,vR as fr,wR as fs,SR as ft,MR as fu,km as fv,Em as fw,Im as fx,Gc as fy,Gx as fz,jo as g,_0 as g0,fT as g1,lT as g2,uT as g3,pT as g4,Hx as g5,Wx as g6,Po as g7,VR as g8,bT as g9,$c as gA,jx as gB,Ed as gC,Bx as gD,Ux as gE,XT as gF,eT as gG,iT as gH,nT as gI,rT as gJ,YT as gK,QT as gL,lm as gM,lc as gN,vT as ga,bs as gb,ST as gc,wT as gd,IT as ge,pS as gf,xT as gg,tT as gh,zd as gi,vr as gj,Fx as gk,V_ as gl,Wd as gm,$o as gn,Bd as go,M_ as gp,D_ as gq,Lx as gr,ym as gs,Nx as gt,Px as gu,Mx as gv,Lc as gw,Ox as gx,Ax as gy,Dx as gz,id as h,Bm as i,Gm as j,Hm as k,zm as l,Zp as m,gC as n,Gk as o,YI as p,w_ as q,g_ as r,ZI as s,UI as t,jp as u,ek as v,Ke as w,JT as x,nC as y,US as z};