sliccy 6.2.0 → 6.3.0

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 (68) hide show
  1. package/dist/ui/assets/{account-store-CDRkjM3_.js → account-store-DhS8k8-S.js} +1 -1
  2. package/dist/ui/assets/{account-store-Dlc9jV2R.js → account-store-Uj6VFvmJ.js} +1 -1
  3. package/dist/ui/assets/{adobe-CYrtTdaC.js → adobe-B8qKdXEi.js} +1 -1
  4. package/dist/ui/assets/{adobe-F2awatTI.js → adobe-DEqarHF7.js} +1 -1
  5. package/dist/ui/assets/{apps-AV5a8hlw.js → apps-Bie0e1m2.js} +1 -1
  6. package/dist/ui/assets/{azure-openai-DpLTmXne.js → azure-openai-DuVr84k9.js} +1 -1
  7. package/dist/ui/assets/{azure-openai-hoDjHOa_.js → azure-openai-DvSSRCkA.js} +1 -1
  8. package/dist/ui/assets/{cerebras-BCrkgtqg.js → cerebras-BpS22jYI.js} +1 -1
  9. package/dist/ui/assets/{cerebras-77dHJa1T.js → cerebras-DzesQTXW.js} +1 -1
  10. package/dist/ui/assets/{connect-surface-BD3PjqRC.js → connect-surface-Ct1AdFki.js} +1 -1
  11. package/dist/ui/assets/{fs-C5eoK5vJ.js → fs-CvnWZ6Jt.js} +1 -1
  12. package/dist/ui/assets/{fs-B4YCvr-4.js → fs-DIJccx8q.js} +2 -2
  13. package/dist/ui/assets/{github-copilot-D1_1ZjYe.js → github-copilot-BiPqFhNX.js} +1 -1
  14. package/dist/ui/assets/{github-copilot-DXnF0Yve.js → github-copilot-VvH4s7sA.js} +1 -1
  15. package/dist/ui/assets/{github-CNTidRtv.js → github-dAErpFvL.js} +1 -1
  16. package/dist/ui/assets/{github-DFg_eiN4.js → github-pk5_ylPv.js} +2 -2
  17. package/dist/ui/assets/{kernel-worker-BmsF-WnR.js → kernel-worker-ajcnNy0f.js} +20 -20
  18. package/dist/ui/assets/{local-llm-BVGC0MAD.js → local-llm-CJRbK1cS.js} +1 -1
  19. package/dist/ui/assets/{local-llm-CR8EIJHr.js → local-llm-CfVfbBNa.js} +1 -1
  20. package/dist/ui/assets/{main-gaC2EacM.js → main-7V25oAV9.js} +3 -3
  21. package/dist/ui/assets/{mount-CBFBuDIW.js → mount-Bsul2M7V.js} +2 -2
  22. package/dist/ui/assets/{mount-v_oY16gF.js → mount-CRp56aa2.js} +1 -1
  23. package/dist/ui/assets/{mount-recovery-5zqnhxot.js → mount-recovery-B6-FEnb7.js} +1 -1
  24. package/dist/ui/assets/{new-session-CsQeu7Qk.js → new-session-BMY81iI-.js} +2 -2
  25. package/dist/ui/assets/{oauth-bootstrap-CB7ndbim.js → oauth-bootstrap-DFhqreg0.js} +2 -2
  26. package/dist/ui/assets/{openai-codex-DEOmNWfV.js → openai-codex-5ly8mDcH.js} +1 -1
  27. package/dist/ui/assets/{openai-codex-BzUnyNvd.js → openai-codex-o65C3vHM.js} +1 -1
  28. package/dist/ui/assets/{openrouter-B-FHk7OK.js → openrouter-Bl8rKbdM.js} +1 -1
  29. package/dist/ui/assets/{openrouter-6UAJeUSD.js → openrouter-DZzCgoha.js} +1 -1
  30. package/dist/ui/assets/{openrouter-oauth-Da_pZO2U.js → openrouter-oauth-DIW_pyO2.js} +1 -1
  31. package/dist/ui/assets/{openrouter-oauth-xwzAaTC4.js → openrouter-oauth-tJu_AMDh.js} +1 -1
  32. package/dist/ui/assets/{panel-rpc-handlers-Tt8MAppa.js → panel-rpc-handlers-BN4BCAVK.js} +2 -2
  33. package/dist/ui/assets/{provider-BFnnJUNc.js → provider-BCQiQFKs.js} +1 -1
  34. package/dist/ui/assets/{provider-RPw9sIKU.js → provider-BaiyZqj2.js} +2 -2
  35. package/dist/ui/assets/{provider-settings-D-M19QHq.js → provider-settings-CXes7fTR.js} +1 -1
  36. package/dist/ui/assets/{provider-settings-FRENlwq7.js → provider-settings-VxXaQXu5.js} +1 -1
  37. package/dist/ui/assets/{provider-store-access-CXo7Ch15.js → provider-store-access-B0oECQqK.js} +2 -2
  38. package/dist/ui/assets/provider-store-access-fl-MsQpU.js +1 -0
  39. package/dist/ui/assets/{providers-CfZWac9Z.js → providers-BwP_K_jW.js} +1 -1
  40. package/dist/ui/assets/{providers-BQA1bDUC.js → providers-Bz0SwL53.js} +2 -2
  41. package/dist/ui/assets/{quick-llm-CPncKgAM.js → quick-llm-P9wxZ7EU.js} +1 -1
  42. package/dist/ui/assets/{session-freezer-DsxMGo7G.js → session-freezer-CueXX5nZ.js} +2 -2
  43. package/dist/ui/assets/{setup-standalone-prelude-COfiDKSZ.js → setup-standalone-prelude-BfeEnJkN.js} +1 -1
  44. package/dist/ui/assets/{setup-sudo-P6vrIqoV.js → setup-sudo-DCOcjx2c.js} +2 -2
  45. package/dist/ui/assets/{skills-Pt9eJlYW.js → skills-D_Ep23NZ.js} +1 -1
  46. package/dist/ui/assets/{sprinkle-manager-DwLCgrU9.js → sprinkle-manager-HaNmX2ye.js} +1 -1
  47. package/dist/ui/assets/{store-CwkA0GJk.js → store-CguDkxqH.js} +1 -1
  48. package/dist/ui/assets/{sudo-B09269RM.js → sudo-V2MeKwLU.js} +1 -1
  49. package/dist/ui/assets/{telemetry-C8rZr13D.js → telemetry-DqIqVG5n.js} +3 -3
  50. package/dist/ui/assets/{upgrade-detection-Bjglwm5C.js → upgrade-detection-CGfE8fu7.js} +1 -1
  51. package/dist/ui/assets/{wc-extension-D1tE42E-.js → wc-extension-CqFkjCEc.js} +2 -2
  52. package/dist/ui/assets/{wc-follower-D6e9PX3w.js → wc-follower-bcBXL4QF.js} +3 -3
  53. package/dist/ui/assets/wc-live-1igAgrHi.js +8 -0
  54. package/dist/ui/assets/{wc-nav-Druc6cr1.js → wc-nav-s0llKqeE.js} +2 -2
  55. package/dist/ui/assets/{wc-onboarding-2wHtUgoB.js → wc-onboarding-CedoFc5j.js} +2 -2
  56. package/dist/ui/assets/{wc-placeholder-CA_SE_LC.js → wc-placeholder-DhOwMxPG.js} +2 -2
  57. package/dist/ui/assets/{wc-settings-Cnb1vMs-.js → wc-settings-_h48_7UA.js} +2 -2
  58. package/dist/ui/assets/{wc-shell-CjsAYvKl.js → wc-shell-Dmpb_Nl-.js} +21 -21
  59. package/dist/ui/assets/{wc-sprinkles-BFlNkrlx.js → wc-sprinkles-BUPl0ZFx.js} +2 -2
  60. package/dist/ui/assets/{wc-tray-Co3Os5si.js → wc-tray-C-KZScxb.js} +2 -2
  61. package/dist/ui/assets/{xai-grok-B1m1bhTe.js → xai-grok-BOdrR1oK.js} +1 -1
  62. package/dist/ui/assets/{xai-grok-CsHv0jp4.js → xai-grok-JLJFEJOt.js} +1 -1
  63. package/dist/ui/index.html +7 -7
  64. package/dist/ui/llm-proxy-sw.js +1 -1
  65. package/dist/ui/packages/webapp/index.html +7 -7
  66. package/package.json +1 -1
  67. package/dist/ui/assets/provider-store-access-C3_H4fyM.js +0 -1
  68. package/dist/ui/assets/wc-live-BlT_fwYf.js +0 -8
@@ -1,4 +1,4 @@
1
- import{i as e,n as t,t as n}from"./rolldown-runtime-aKtaBQYM.js";import{t as r}from"./logger-LESFN7Hj.js";import{n as i,r as a,t as o}from"./panel-rpc-CjFVE0nK.js";import{a as s,t as c}from"./providers-CfZWac9Z.js";import{n as l,t as u}from"./base64-Ba7QB87Z.js";import{a as d,i as f,n as p,r as m,s as h,t as g}from"./src-BcePBv4G.js";import{$ as _,$t as v,An as y,At as b,Bt as x,Cn as S,Ct as C,D as w,Dn as T,Dt as E,E as D,En as O,Et as k,F as ee,Fn as A,Ft as j,Gt as te,Ht as ne,I as re,In as ie,It as ae,J as oe,Jt as se,Kt as ce,Lt as le,Mn as M,Mt as N,Nn as ue,Nt as de,On as fe,Ot as pe,Pn as me,Pt as he,Q as ge,Qt as _e,R as ve,Rt as P,Sn as ye,St as be,Tn as F,Tt as I,Ut as xe,Vt as L,Wt as Se,X as R,Xt as z,Y as Ce,Yt as we,Z as Te,Zt as Ee,_n as B,_t as De,an as V,at as Oe,bn as ke,bt as Ae,cn as je,ct as Me,dn as Ne,dt as Pe,en as Fe,et as Ie,fn as H,ft as Le,gn as Re,gt as ze,hn as Be,ht as Ve,in as U,it as He,jn as Ue,jt as We,kn as Ge,kt as Ke,ln as eee,lt as qe,m as Je,mn as Ye,mt as Xe,nn as Ze,nt as Qe,on as $e,ot as et,pn as tt,pt as nt,q as rt,qt as it,rn as at,rt as ot,sn as st,st as ct,tn as lt,tt as tee,un as ut,ut as dt,vn as ft,vt as pt,w as mt,wn as ht,wt as gt,xn as _t,xt as vt,yn as yt,yt as nee,zt as bt}from"./account-store-Dlc9jV2R.js";import{a as xt,c as St,d as Ct,f as wt,i as Tt,l as Et,n as Dt,p as Ot,r as kt,s as At,t as jt,u as Mt}from"./proxied-fetch-GabK83LB.js";import{t as Nt}from"./runtime-env-byAg9ij-.js";import{n as Pt,r as Ft,t as It}from"./fetch-body-DDu_AU5I.js";import{c as Lt,i as Rt,n as zt,o as Bt,r as ree,s as Vt,t as Ht}from"./tray-follower-status-B191H1LK.js";import{a as Ut,i as Wt,n as Gt,r as Kt}from"./transcript-limits-HrXqL2T0.js";import{n as qt,o as Jt,s as Yt}from"./tool-ui-t6ocn6AG.js";import{a as Xt,i as Zt,n as Qt,o as $t,r as en,t as tn}from"./backend-local-D4WZgy4J.js";import{t as nn}from"./types-idfTVsM8.js";import{n as rn,t as an}from"./mime-types-D7IV6i7k.js";import{a as on,i as sn,n as cn,r as ln}from"./mount-v_oY16gF.js";import{o as un}from"./mount-table-store-CTrzlrNn.js";import{t as dn}from"./remote-cache-D59F5FOx.js";import{r as fn,t as pn}from"./mount-recovery-5zqnhxot.js";import{C as mn,D as hn,E as gn,S as _n,_ as vn,a as yn,b as bn,d as xn,g as Sn,h as Cn,m as wn,n as Tn,o as En,r as Dn,s as On,t as kn,u as iee,w as An,y as aee}from"./db-BTiVtoD4.js";import{a as jn,n as Mn,r as Nn,s as oee}from"./tray-runtime-config-C9Kq7Hrh.js";import{a as see,i as Pn,n as cee,o as lee,r as Fn}from"./runtime-mode-BT9Lswtn.js";import{a as In,c as Ln,d as Rn,i as zn,l as Bn,n as Vn,o as Hn,s as Un,t as Wn,u as Gn}from"./lick-manager-Ce_d4NxJ.js";import{i as Kn,n as qn,r as Jn,t as Yn}from"./path-utils-DU6QhF_k.js";import{u as Xn}from"./transform-messages-Bp94o3FD.js";import{l as Zn,m as Qn}from"./bedrock-camp-DS0ilb3O.js";import{t as $n}from"./__vite-browser-external-SwrSgYTf.js";import{a as er,n as tr,r as nr}from"./fs-C5eoK5vJ.js";import{a as W,c as rr,i as ir,l as ar,n as or,o as sr,r as cr,s as lr}from"./cost-command-_BMgmnMI.js";import{a as ur,c as dr,d as fr,f as pr,i as mr,l as hr,m as gr,n as _r,o as vr,p as yr,r as br,s as xr,u as Sr}from"./skills-Pt9eJlYW.js";import{n as Cr,t as wr}from"./llm-session-id-ZObKEXzb.js";import{n as Tr,r as Er}from"./frozen-archive-format-CqpMlNNW.js";import{a as Dr,c as Or,d as kr,f as Ar,i as jr,l as Mr,n as Nr,o as Pr,r as Fr,s as Ir,t as Lr,u as Rr}from"./installer-kDSMsl2T.js";import{n as zr,t as Br}from"./safe-buffer-C0pSmFaz.js";import{t as Vr}from"./global-db-DvmmimLY.js";import{a as Hr,i as Ur,r as Wr,t as Gr}from"./git-config-Lj0BT7Oc.js";import{t as Kr}from"./process-manager-B5dz0PkO.js";import{C as qr,O as Jr,S as Yr,_ as Xr,a as Zr,b as Qr,c as $r,f as ei,g as ti,h as ni,i as ri,k as ii,l as uee,m as dee,n as ai,o as oi,p as si,r as ci,s as li,t as ui,u as di,v as fi,x as pi,y as mi}from"./shared-pjIf7b3g.js";import{n as hi,t as gi}from"./esbuild-wasm-Bnp5hszJ.js";import{n as _i,t as vi}from"./wasm-compiler-Ct7QZURL.js";import{a as yi,i as bi,r as xi,t as Si}from"./script-catalog-BYXhqRAc.js";import{n as Ci,t as wi}from"./magick-wasm-CTgpng4k.js";import{t as Ti}from"./local-llm-BVGC0MAD.js";import{t as Ei}from"./client-BXN2qRve.js";const Di=r(`cdp`);var fee=class{ws=null;nextId=1;_superseded=!1;pending=new Map;listeners=new Map;_state=`disconnected`;get state(){return this._state}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:r}=e;return this._state=`connecting`,new Promise((e,i)=>{let a=setTimeout(()=>{this.cleanup(),i(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=r===void 0?new WebSocket(t):new WebSocket(t,r)}catch(e){clearTimeout(a),this._state=`disconnected`,i(e);return}this.ws.onopen=()=>{clearTimeout(a),this._state=`connected`,this._superseded=!1,Di.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Di.error(`Connection failed`,{url:t}),this.cleanup(),i(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),Di.info(`Disconnected`)}async send(e,t,n,r=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let i=this.nextId++,a={id:i,method:e};return t&&(a.params=t),n&&(a.sessionId=n),Di.debug(`Send`,{method:e,id:i,sessionId:n}),new Promise((t,n)=>{let o=setTimeout(()=>{this.pending.delete(i),n(Error(`CDP command timed out after ${r}ms: ${e}`))},r);this.pending.set(i,{resolve:e=>{clearTimeout(o),t(e)},reject:e=>{clearTimeout(o),n(e)}}),this.ws.send(JSON.stringify(a))})}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return new Promise((n,r)=>{let i=setTimeout(()=>{this.off(e,a),r(Error(`Timed out waiting for event: ${e}`))},t),a=t=>{clearTimeout(i),this.off(e,a),n(t)};this.on(e,a)})}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Di.debug(`Response`,{id:e.id,hasError:!!e.error});let n=this.pending.get(e.id);n&&(this.pending.delete(e.id),e.error?(Di.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),n.reject(Error(`CDP error: ${e.error.message} (${e.error.code})`))):n.resolve(e.result??{}));return}if(`method`in t){let e=t;Di.debug(`Event`,{method:e.method,sessionId:e.sessionId});let n=this.listeners.get(e.method);if(n){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of n)try{e(t)}catch{}}}}handleClose(e){let t=e===4001;t?(this._superseded=!0,Di.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):Di.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});let n=t?`CDP connection superseded by another SLICC tab/window on this instance`:`CDP connection closed`;for(let[,e]of this.pending)e.reject(Error(n));this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.clear()}};const Oi=`(function() {
1
+ import{i as e,n as t,t as n}from"./rolldown-runtime-aKtaBQYM.js";import{t as r}from"./logger-LESFN7Hj.js";import{n as i,r as a,t as o}from"./panel-rpc-CjFVE0nK.js";import{a as s,t as c}from"./providers-BwP_K_jW.js";import{n as l,t as u}from"./base64-Ba7QB87Z.js";import{a as d,i as f,n as p,r as m,s as h,t as g}from"./src-BcePBv4G.js";import{$ as _,$t as v,An as y,At as b,Bt as x,Cn as S,Ct as C,D as w,Dn as T,Dt as E,E as D,En as O,Et as k,F as ee,Fn as A,Ft as j,Gt as te,Ht as ne,I as re,In as ie,It as ae,J as oe,Jt as se,Kt as ce,Lt as le,Mn as M,Mt as N,Nn as ue,Nt as de,On as fe,Ot as pe,Pn as me,Pt as he,Q as ge,Qt as _e,R as ve,Rt as P,Sn as ye,St as be,Tn as F,Tt as I,Ut as xe,Vt as L,Wt as Se,X as R,Xt as z,Y as Ce,Yt as we,Z as Te,Zt as Ee,_n as B,_t as De,an as V,at as Oe,bn as ke,bt as Ae,cn as je,ct as Me,dn as Ne,dt as Pe,en as Fe,et as Ie,fn as H,ft as Le,gn as Re,gt as ze,hn as Be,ht as Ve,in as U,it as He,jn as Ue,jt as We,kn as Ge,kt as Ke,ln as eee,lt as qe,m as Je,mn as Ye,mt as Xe,nn as Ze,nt as Qe,on as $e,ot as et,pn as tt,pt as nt,q as rt,qt as it,rn as at,rt as ot,sn as st,st as ct,tn as lt,tt as tee,un as ut,ut as dt,vn as ft,vt as pt,w as mt,wn as ht,wt as gt,xn as _t,xt as vt,yn as yt,yt as nee,zt as bt}from"./account-store-Uj6VFvmJ.js";import{a as xt,c as St,d as Ct,f as wt,i as Tt,l as Et,n as Dt,p as Ot,r as kt,s as At,t as jt,u as Mt}from"./proxied-fetch-GabK83LB.js";import{t as Nt}from"./runtime-env-byAg9ij-.js";import{n as Pt,r as Ft,t as It}from"./fetch-body-DDu_AU5I.js";import{c as Lt,i as Rt,n as zt,o as Bt,r as ree,s as Vt,t as Ht}from"./tray-follower-status-B191H1LK.js";import{a as Ut,i as Wt,n as Gt,r as Kt}from"./transcript-limits-HrXqL2T0.js";import{n as qt,o as Jt,s as Yt}from"./tool-ui-t6ocn6AG.js";import{a as Xt,i as Zt,n as Qt,o as $t,r as en,t as tn}from"./backend-local-D4WZgy4J.js";import{t as nn}from"./types-idfTVsM8.js";import{n as rn,t as an}from"./mime-types-D7IV6i7k.js";import{a as on,i as sn,n as cn,r as ln}from"./mount-CRp56aa2.js";import{o as un}from"./mount-table-store-CTrzlrNn.js";import{t as dn}from"./remote-cache-D59F5FOx.js";import{r as fn,t as pn}from"./mount-recovery-B6-FEnb7.js";import{C as mn,D as hn,E as gn,S as _n,_ as vn,a as yn,b as bn,d as xn,g as Sn,h as Cn,m as wn,n as Tn,o as En,r as Dn,s as On,t as kn,u as iee,w as An,y as aee}from"./db-BTiVtoD4.js";import{a as jn,n as Mn,r as Nn,s as oee}from"./tray-runtime-config-C9Kq7Hrh.js";import{a as see,i as Pn,n as cee,o as lee,r as Fn}from"./runtime-mode-BT9Lswtn.js";import{a as In,c as Ln,d as Rn,i as zn,l as Bn,n as Vn,o as Hn,s as Un,t as Wn,u as Gn}from"./lick-manager-Ce_d4NxJ.js";import{i as Kn,n as qn,r as Jn,t as Yn}from"./path-utils-DU6QhF_k.js";import{u as Xn}from"./transform-messages-Bp94o3FD.js";import{l as Zn,m as Qn}from"./bedrock-camp-DS0ilb3O.js";import{t as $n}from"./__vite-browser-external-SwrSgYTf.js";import{a as er,n as tr,r as nr}from"./fs-CvnWZ6Jt.js";import{a as W,c as rr,i as ir,l as ar,n as or,o as sr,r as cr,s as lr}from"./cost-command-_BMgmnMI.js";import{a as ur,c as dr,d as fr,f as pr,i as mr,l as hr,m as gr,n as _r,o as vr,p as yr,r as br,s as xr,u as Sr}from"./skills-D_Ep23NZ.js";import{n as Cr,t as wr}from"./llm-session-id-ZObKEXzb.js";import{n as Tr,r as Er}from"./frozen-archive-format-CqpMlNNW.js";import{a as Dr,c as Or,d as kr,f as Ar,i as jr,l as Mr,n as Nr,o as Pr,r as Fr,s as Ir,t as Lr,u as Rr}from"./installer-kDSMsl2T.js";import{n as zr,t as Br}from"./safe-buffer-C0pSmFaz.js";import{t as Vr}from"./global-db-DvmmimLY.js";import{a as Hr,i as Ur,r as Wr,t as Gr}from"./git-config-Lj0BT7Oc.js";import{t as Kr}from"./process-manager-B5dz0PkO.js";import{C as qr,O as Jr,S as Yr,_ as Xr,a as Zr,b as Qr,c as $r,f as ei,g as ti,h as ni,i as ri,k as ii,l as uee,m as dee,n as ai,o as oi,p as si,r as ci,s as li,t as ui,u as di,v as fi,x as pi,y as mi}from"./shared-pjIf7b3g.js";import{n as hi,t as gi}from"./esbuild-wasm-Bnp5hszJ.js";import{n as _i,t as vi}from"./wasm-compiler-Ct7QZURL.js";import{a as yi,i as bi,r as xi,t as Si}from"./script-catalog-BYXhqRAc.js";import{n as Ci,t as wi}from"./magick-wasm-CTgpng4k.js";import{t as Ti}from"./local-llm-CJRbK1cS.js";import{t as Ei}from"./client-BXN2qRve.js";const Di=r(`cdp`);var fee=class{ws=null;nextId=1;_superseded=!1;pending=new Map;listeners=new Map;_state=`disconnected`;get state(){return this._state}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:r}=e;return this._state=`connecting`,new Promise((e,i)=>{let a=setTimeout(()=>{this.cleanup(),i(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=r===void 0?new WebSocket(t):new WebSocket(t,r)}catch(e){clearTimeout(a),this._state=`disconnected`,i(e);return}this.ws.onopen=()=>{clearTimeout(a),this._state=`connected`,this._superseded=!1,Di.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Di.error(`Connection failed`,{url:t}),this.cleanup(),i(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),Di.info(`Disconnected`)}async send(e,t,n,r=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let i=this.nextId++,a={id:i,method:e};return t&&(a.params=t),n&&(a.sessionId=n),Di.debug(`Send`,{method:e,id:i,sessionId:n}),new Promise((t,n)=>{let o=setTimeout(()=>{this.pending.delete(i),n(Error(`CDP command timed out after ${r}ms: ${e}`))},r);this.pending.set(i,{resolve:e=>{clearTimeout(o),t(e)},reject:e=>{clearTimeout(o),n(e)}}),this.ws.send(JSON.stringify(a))})}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return new Promise((n,r)=>{let i=setTimeout(()=>{this.off(e,a),r(Error(`Timed out waiting for event: ${e}`))},t),a=t=>{clearTimeout(i),this.off(e,a),n(t)};this.on(e,a)})}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Di.debug(`Response`,{id:e.id,hasError:!!e.error});let n=this.pending.get(e.id);n&&(this.pending.delete(e.id),e.error?(Di.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),n.reject(Error(`CDP error: ${e.error.message} (${e.error.code})`))):n.resolve(e.result??{}));return}if(`method`in t){let e=t;Di.debug(`Event`,{method:e.method,sessionId:e.sessionId});let n=this.listeners.get(e.method);if(n){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of n)try{e(t)}catch{}}}}handleClose(e){let t=e===4001;t?(this._superseded=!0,Di.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):Di.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});let n=t?`CDP connection superseded by another SLICC tab/window on this instance`:`CDP connection closed`;for(let[,e]of this.pending)e.reject(Error(n));this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.clear()}};const Oi=`(function() {
2
2
  'use strict';
3
3
 
4
4
  // ===== DOM Utilities =====
@@ -879,7 +879,7 @@ import{i as e,n as t,t as n}from"./rolldown-runtime-aKtaBQYM.js";import{t as r}f
879
879
  }`,returnByValue:!0},this.sessionId)).result?.value;if(!n||n.width===0||n.height===0)throw Error(`Element with backend node ${e} has no dimensions`);return{x:n.x+n.width/2,y:n.y+n.height/2}}async ensureLocalConnected(){if(this.localClient.superseded===!0){this.notifySuperseded();return}if(this.localClient.state===`disconnected`){let e=this._lastConnectOptions;await this.localClient.connect({url:e?.url??ji(),...e?.timeout===void 0?{}:{timeout:e.timeout},...e?.protocols===void 0?{}:{protocols:e.protocols}})}}async ensureConnected(){if(this.client.superseded===!0){this.notifySuperseded();return}this.client.state===`disconnected`&&(this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.sessionId=null,this.attachedTargetId=null,this.client.state===`disconnected`&&await this.connect(this._lastConnectOptions??void 0))}ensureAttached(){if(!this.sessionId)throw Error(`Not attached to a page. Call attachToPage(targetId) first.`)}addDialogListener(e){e.on(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening)}addExecutionContextListeners(e){e.on(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.on(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.on(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared)}removeDialogListener(e){e.off(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening)}removeExecutionContextListeners(e){e.off(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.off(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.off(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared)}setClient(e){this.client!==e&&(this.removeDialogListener(this.client),this.removeExecutionContextListeners(this.client),this.client=e,this.addDialogListener(this.client),this.addExecutionContextListeners(this.client))}async boundingBox(e){await this.client.send(`DOM.enable`,{},this.sessionId);let t=(await this.client.send(`DOM.getDocument`,{depth:0},this.sessionId)).root.nodeId,n;try{n=(await this.client.send(`DOM.querySelector`,{nodeId:t,selector:e},this.sessionId)).nodeId}catch{return null}if(!n)return null;let r=(await this.client.send(`DOM.getBoxModel`,{nodeId:n},this.sessionId)).model;if(!r)return null;let i=r.content;return{x:i[0],y:i[1],width:r.width,height:r.height}}};function Ni(e){let t=new Map;for(let n of e){let e=typeof n.backendDOMNodeId==`number`?n.backendDOMNodeId:null;if(e===null)continue;let r=n.role,i=n.name,a=typeof r?.value==`string`?r.value.toLowerCase():``,o=typeof i?.value==`string`?i.value:``;if(!a)continue;let s=`${a}|${o}`;t.has(s)||t.set(s,e)}return t}function Pi(e,t){let n=`${e.role.toLowerCase()}|${e.name}`,r=t.get(n);if(r!==void 0&&(e.backendNodeId=r),e.children)for(let n of e.children)Pi(n,t)}function Fi(e){let t={role:ki(e.role,`unknown`),name:ki(e.name)},n=ki(e.value);n!==``&&(t.value=n);let r=ki(e.description);return r!==``&&(t.description=r),Array.isArray(e.children)&&e.children.length>0&&(t.children=e.children.map(e=>Fi(e)).filter(e=>e.role!==`unknown`)),t}const Ii=r(`panel-rpc-cdp`);var Li=class{getPanelRpc;runtimeId;localTargetId;timeoutMs;eventListeners=new Map;pendingOnce=new Set;key;_state=`connected`;pushRegistered=!1;constructor(e,t,n,r=3e4){this.getPanelRpc=e,this.runtimeId=t,this.localTargetId=n,this.timeoutMs=r,this.key=`${t}:${n}`}get state(){return this._state}async connect(){}disconnect(){this._state=`disconnected`;for(let e of this.pendingOnce)clearTimeout(e.timer),e.reject(Error(`Transport disconnected`));this.pendingOnce.clear();let e=this.getPanelRpc();e&&(this.pushRegistered&&=(e.unregisterPushTarget(this.key),!1),e.call(`remote-cdp-detach`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId}).catch(e=>{Ii.error(`remote-cdp detach failed (page-side session may leak)`,{key:this.key,error:e instanceof Error?e.message:String(e)})})),this.eventListeners.clear()}async send(e,t,n,r){if(this._state===`disconnected`)throw Error(`Transport disconnected`);let i=this.getPanelRpc();if(!i)throw Error(`cdp: no page bridge to the leader tray (panel-RPC client)`);let a=r??this.timeoutMs,s=Math.max(a,o)+5e3;return i.call(`remote-cdp-send`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,method:e,params:t,sessionId:n,timeout:a},{timeoutMs:s})}on(e,t){let n=this.eventListeners.get(e),r=!n||n.size===0;n||(n=new Set,this.eventListeners.set(e,n)),n.add(t),r&&this.subscribe(e)}off(e,t){let n=this.eventListeners.get(e);n&&(n.delete(t),n.size===0&&(this.eventListeners.delete(e),this.unsubscribe(e)))}once(e,t){return new Promise((n,r)=>{let i=t??this.timeoutMs,a={reject:r,timer:void 0},o=()=>{clearTimeout(a.timer),this.pendingOnce.delete(a),this.off(e,s)};a.timer=setTimeout(()=>{o(),r(Error(`Remote CDP event timed out: ${e}`))},i);let s=e=>{o(),n(e)};this.pendingOnce.add(a),this.on(e,s)})}handleEvent(e,t){let n=this.eventListeners.get(e);if(n)for(let e of[...n])e(t)}ensurePushRegistered(e){this.pushRegistered||=(e.registerPushTarget(this.key,e=>this.handleEvent(e.method,e.params??{})),!0)}subscribe(e){let t=this.getPanelRpc();if(!t){Ii.error(`remote-cdp subscribe skipped: no panel-RPC client`,{key:this.key,event:e});return}this.ensurePushRegistered(t),t.call(`remote-cdp-subscribe`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,event:e}).catch(t=>{Ii.error(`remote-cdp subscribe failed; events for this transport will not arrive`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}unsubscribe(e){let t=this.getPanelRpc();t&&t.call(`remote-cdp-unsubscribe`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,event:e}).catch(t=>{Ii.error(`remote-cdp unsubscribe failed (page-side forwarder may leak)`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}};function Ri(e){let t=new Map,n=(e,t)=>`${e}:${t}`;return{getTargets(){return[]},createRemoteTransport(r,i){let a=n(r,i),o=t.get(a);return o||(o=new Li(e,r,i),t.set(a,o)),o},removeRemoteTransport(e,r){let i=n(e,r),a=t.get(i);a&&(a.disconnect(),t.delete(i))},async openRemoteTab(t,n){let r=e();if(!r)throw Error(`cdp: no page bridge to the leader tray (panel-RPC client)`);let{targetId:i}=await r.call(`remote-open-tab`,{runtimeId:t,url:n});return i}}}r(`stale-asset`);const zi=/dynamically imported module|importing a module script failed|expected a javascript module|module script/i;function Bi(e){return zi.test(e)}let Vi=null;function Hi(e){if(!e){Vi=null;return}Vi=e}function Ui(e=!1){if(!Vi||typeof BroadcastChannel!=`function`)return;let t=new BroadcastChannel(`slicc-stale-asset-reload`);try{t.postMessage({type:`stale-asset-reload`,instanceId:Vi,replayTurn:e})}finally{t.close()}}function Wi(e){Bi(e instanceof Error?e.message:String(e))&&Ui()}var Gi=class{_state=`disconnected`;nextCommandId=1;listeners=new Map;pendingCommands=new Map;unsubscribe=null;opts;label;constructor(e){this.opts=e,this.label=e.label??`CDP transport`}get state(){return this._state}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);this.unsubscribe=this.opts.subscribeIncoming(e=>this.handleIncoming(e)),this._state=`connected`}disconnect(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.pendingCommands)clearTimeout(e.timer),e.reject(Error(`${this.label} disconnected`));this.pendingCommands.clear(),this.listeners.clear(),this._state=`disconnected`}async send(e,t,n,r=3e4){if(this._state!==`connected`)throw Error(`${this.label} is not connected`);let i=this.nextCommandId++,a=this.opts.buildCommandEnvelope(i,e,t,n);return new Promise((t,n)=>{let o=!1,s=setTimeout(()=>{o||(o=!0,this.pendingCommands.delete(i),n(Error(`CDP command timed out after ${r}ms: ${e}`)))},r);this.pendingCommands.set(i,{resolve:e=>{o||(o=!0,t(e))},reject:e=>{o||(o=!0,n(e))},timer:s}),this.opts.sendEnvelope(a).catch(e=>{o||(o=!0,this.pendingCommands.delete(i),clearTimeout(s),n(Error(`Failed to send CDP command: ${e instanceof Error?e.message:String(e)}`)))})})}on(e,t){let n=this.listeners.get(e),r=!n;n||(n=new Set,this.listeners.set(e,n)),n.add(t),r&&this.opts.onSubscribeEvent?.(e)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&(this.listeners.delete(e),this.opts.onUnsubscribeEvent?.(e)))}once(e,t=3e4){return new Promise((n,r)=>{let i=setTimeout(()=>{this.off(e,a),r(Error(`Timed out waiting for event: ${e}`))},t),a=t=>{clearTimeout(i),this.off(e,a),n(t)};this.on(e,a)})}handleIncoming(e){let t=this.opts.parseResponse(e);if(t){this.handleResponse(t);return}let n=this.opts.parseEvent(e);n&&this.handleEvent(n)}handleResponse(e){let t=this.pendingCommands.get(e.id);if(!t){this.opts.onUnknownResponseId?.(e.id);return}this.pendingCommands.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result??{})}handleEvent(e){let t=this.listeners.get(e.method);if(t)for(let n of t)try{n(e.params??{})}catch(t){this.opts.onListenerError?.(e.method,t)}}};function Ki(e){let t=!1,n=()=>{t||(t=!0,typeof e.start==`function`&&e.start())};return{onMessage:t=>{let r=e=>{t(e.data)};return e.addEventListener(`message`,r),n(),()=>{e.removeEventListener(`message`,r)}},send:(t,n)=>{n&&n.length>0?e.postMessage(t,n):e.postMessage(t)}}}function qi(e){let t=Ki(e);return{onMessage:e=>t.onMessage(e),send:(e,n)=>{t.send({source:`offscreen`,payload:e},n)}}}var Ji=class extends Gi{constructor(e){let t=Ki(e);super({label:`WorkerCdpProxy`,buildCommandEnvelope:(e,t,n,r)=>({type:`cdp-cmd`,id:e,method:t,params:n,sessionId:r}),sendEnvelope:e=>(t.send(e),Promise.resolve()),subscribeIncoming:e=>t.onMessage(e),parseResponse:e=>{let t=e;if(t?.type!==`cdp-response`)return null;if(typeof t.id!=`number`||!Number.isFinite(t.id))return console.warn(`[WorkerCdpProxy] dropping cdp-response with invalid id`,t),null;let n=e;return{id:n.id,result:n.result,error:n.error}},parseEvent:e=>{let t=e;if(t?.type!==`cdp-event`)return null;if(typeof t.method!=`string`)return console.warn(`[WorkerCdpProxy] dropping cdp-event with invalid method`,t),null;let n=e;return{method:n.method,params:n.params}},onSubscribeEvent:e=>{t.send({type:`cdp-subscribe`,event:e})},onUnsubscribeEvent:e=>{t.send({type:`cdp-unsubscribe`,event:e})}})}};const Yi=`sessions`;function Xi(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Yi)||e.createObjectStore(Yi,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Zi=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await Xi();e.onversionchange=()=>{e.close(),this.db=null},e.onclose=()=>{this.db=null},this.db=e}return this.db}async save(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(Yi,`readwrite`);i.objectStore(Yi).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(Yi,`readonly`).objectStore(Yi).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=await this.getDb();return new Promise((t,n)=>{let r=e.transaction(Yi,`readonly`).objectStore(Yi).getAll();r.onsuccess=()=>{t(r.result.sort((e,t)=>t.updatedAt-e.updatedAt).map(e=>e.id))},r.onerror=()=>n(r.error)})}async delete(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(Yi,`readwrite`);i.objectStore(Yi).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async saveMessages(e,t){let n=await this.load(e),r=n?{...n,messages:t,updatedAt:Date.now()}:{id:e,messages:t,createdAt:Date.now(),updatedAt:Date.now()};await this.save(r)}};const Qi=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`upgrade`,`cherry`,`workflow`,`sudo-request`,`preview`,`discovery`]);function $i(e){return e!=null&&Qi.has(e)}const ea={webhook:`Webhook Event`,sprinkle:`Sprinkle Event`,fswatch:`File Watch Event`,"session-reload":`Session Reload`,navigate:`Navigate Event`,upgrade:`Upgrade Event`,cherry:`Cherry Event`,workflow:`Workflow Event`,cron:`Cron Event`,"sudo-request":`Scoop Access Request`,preview:`Preview`,discovery:`Discovery Event`};function ta(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`session-reload`:return`mount-recovery`;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`cherry`:return e.cherryName;case`workflow`:return e.workflowName;case`sudo-request`:return e.sudoScoopName;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function na(e,t){let n=e.body,r=e.lickId;if(n?.reason===`mount-recovery`){let e=pn(n.mounts??[]);return e===null?null:{label:t,content:`${e}${r?`\n\nLick ID: ${r}\nThis card is actionable: call \`lick_confirm\` with this lick id to re-run the listed \`mount …\` command(s) so the user can re-authorize, or \`lick_dismiss\` to leave them unmounted. The card flips to ✓ on confirm / muted ✗ on dismiss.`:``}`}}let i=la(e,t);if(!r)return i;let a=`\n\nLick ID: ${r}\nThis card is informational — there is NO confirm action. Call \`lick_dismiss\` with this lick id to acknowledge and clear it. The card flips to muted ✗ on dismiss.`;return{label:i.label,content:`${i.content}${a}`}}function ra(e,t){let n=e.upgradeFromVersion??`unknown`,r=e.upgradeToVersion??`unknown`,i=e.body?.releasedAt??null,a=i?`\nReleased: ${i}`:``,o=e.lickId;return{label:t,content:`[${t}: ${n}→${r}]\n\nSLICC was upgraded from \`${n}\` to \`${r}\`.${a}${o?`\n\nLick ID: ${o}\nUse the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`). The card is a binary action: call \`lick_confirm\` with this lick id to **Update workspace files** (it runs the three-way merge of bundled vfs-root content into the user's VFS), or \`lick_dismiss\` to clear it. The card flips to ✓ on confirm / muted ✗ on dismiss. Reviewing the changelog is a separate step you can run first — it is NOT a card action.`:`
880
880
 
881
881
  Use the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`) to offer the user a three-way merge of bundled vfs-root content into their workspace (bundled snapshot vs user's VFS, reconciled with the GitHub tag-to-tag diff).`}`}}function ia(e,t){let n=e.cherryOrigin??`unknown origin`,r=e.cherryRuntimeId??`unknown`;return{label:t,content:`[${t}: ${e.cherryName??`unnamed`}] from ${n} (runtime ${r})\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function aa(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function oa(e,t){let n=e.workflowName??`workflow`,r=e.resultPath??`(no result file)`,i=e.preview??``;return{label:t,content:`[${t}: ${n}] ${e.body?.status??`complete`} — ${i}\nFull result: ${r} (read it only if you need the whole thing).`}}function sa(e,t){let n=e.sudoScoopName??`a scoop`,r=e.lickId??`(unknown)`,i=e.sudoKind??`unknown`,a=e.sudoDetail??``,o=[`[${t}: ${n}]`,`Lick ID: ${r}`,`Kind: ${i}`,`Detail: ${a}`];return e.sudoSuggestedPattern&&o.push(`Suggested pattern: ${e.sudoSuggestedPattern}`),o.push(``,`Use the lick_confirm tool with lick_id="${r}" to approve (or always-approve with a pattern), or lick_dismiss with lick_id="${r}" to deny.`),{label:t,content:o.join(`
882
- `)}}function ca(e,t){let n=e.discoveryOrigin??`an origin`,r=e.discoveryUrl??`(unknown URL)`,i=e.discoveryKind===`llms-txt`?`an llms.txt digest`:`an ai-catalog manifest`,a=e.discoveryKind??`unknown`;return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${r}]\n${n} advertises ${i} (kind: ${a}) at ${r}.\nThis is informational — there is no card action. You MAY fetch it (e.g. \`curl ${r}\`) and act on it if it's relevant to the current task; otherwise ignore it.`}}function la(e,t){let n=ta(e);return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${n}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function ua(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return la(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function da(e,t){let n=la(e,t),r=e.lickId;if(!r)return n;let i=e.body?.verb===`upskill`?`\n\nLick ID: ${r}\nUpskill install. To install, call \`lick_confirm\` with this lick id (it runs \`upskill\` with any branch/path scope from the body); to skip, call \`lick_dismiss\`. The card flips to ✓ on confirm / muted ✗ on dismiss.`:`\n\nLick ID: ${r}\nExternal handoff — stays human-gated. Show the approval dip and wait for the user; do NOT use \`lick_confirm\` / \`lick_dismiss\` here. Carry the lick id in the dip action so the card resolves: slicc.lick({action:'accept'|'dismiss', data:{lickId:'${r}'}}).`;return{label:n.label,content:`${n.content}${i}`}}function fa(e){let t=ea[e.type];return e.type===`session-reload`?na(e,t):e.type===`upgrade`?ra(e,t):e.type===`cherry`?ia(e,t):e.type===`preview`?aa(e,t):e.type===`workflow`?oa(e,t):e.type===`sudo-request`?sa(e,t):e.type===`navigate`?da(e,t):e.type===`webhook`?ua(e,t):e.type===`discovery`?ca(e,t):la(e,t)}const pa=new Map;function ma(e){let t=pa.get(e.id);t&&(pa.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result))}const ha=`__slicc_binary__`;function ga(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[ha]===`b64`&&typeof t.data==`string`}function _a(e){if(e instanceof Uint8Array)return{[ha]:`b64`,data:l(e)};if(Array.isArray(e))return e.map(_a);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=_a(r);return t}return e}function va(e){if(ga(e))return u(e.data);if(Array.isArray(e))return e.map(va);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=va(r);return t}return e}const ya=r(`panel-transport`);function ba(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function xa(){return{onMessage:e=>{let t=(t,n,r)=>(ba(t)&&e(va(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=_a(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||ya.error(`Offscreen → panel transport send failed`,{error:t})})}}}const Sa=r(`kernel-bridge`);function Ca(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.action!==`accept`&&t.action!==`dismiss`)return null;let n=t.data,r=n&&typeof n.lickId==`string`?n.lickId:null;return r?{lickId:r,accepted:t.action===`accept`}:null}var wa=class{orchestrator=null;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopStatuses=new Map;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;activeScoopJid=null;agentEventListeners=new Set;fanOutMessageId=new Map;constructor(e){this._transport=e??null}get transport(){return this._transport||=xa(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new Zi;await n.init(),this.sessionStore=n}static createCallbacks(e){return{onResponse:(t,n,r)=>{let i=e.getOrCreateAssistantMsg(t);r?i.content+=n:(i.content=n,i.isStreaming=!1),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n})},onResponseDone:t=>{let n=e.getLatestAssistantMetadata(t),r=e.currentMessageId.get(t);if(r){let i=e.getBuffer(t).find(e=>e.id===r);i&&(i.isStreaming=!1,n&&Object.assign(i,n)),e.currentMessageId.delete(t)}e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,...n??{}})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${Ta()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n}),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onStatusChange:(t,n)=>{e.scoopStatuses.set(t,n),n===`ready`&&e.currentMessageId.delete(t),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n)=>{e.emit({type:`compaction-state`,scoopJid:t,state:n})},onError:(t,n)=>{e.emit({type:`error`,scoopJid:t,error:n})},onToolStart:(t,n,r)=>{Ut.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{Ut.has(n)||e.bufferToolEnd(t,n,r,i)},onToolUI:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i})},onToolUIDone:(t,n)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n){let r=Gt(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:Ta(),name:t,input:r}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:r})}bufferToolEnd(e,t,n,r){let i=this.currentMessageId.get(e);if(i){let a=this.getBuffer(e).find(e=>e.id===i);if(a?.toolCalls){let e=[...a.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=Kt(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:Wt(n),isError:r})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.persistScoop(e),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.fanOutMessageId.delete(e.jid),this.scoopStatuses.delete(e.jid),!e.isCone&&this.sessionStore&&this.sessionStore.delete(`session-${e.folder}`).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState,this.persistScoop(e)),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){let t=e.config&&(e.config.modelId!==void 0||e.config.thinkingLevel!==void 0)?{...e.config.modelId===void 0?{}:{modelId:e.config.modelId},...e.config.thinkingLevel===void 0?{}:{thinkingLevel:e.config.thinkingLevel}}:void 0;return{jid:e.jid,name:e.name,folder:e.folder,isCone:e.isCone,assistantLabel:e.assistantLabel,status:this.scoopStatuses.get(e.jid)??`ready`,...t?{config:t}:{}}}buildStateSnapshot(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[],t=e.find(e=>e.isCone);return{type:`state-snapshot`,scoops:e,activeScoopJid:this.getActiveScoopJid()??t?.jid??null,trayRuntimeStatus:this.buildTrayRuntimeStatus()}}emitTrayRuntimeStatus(){let e=this.buildTrayRuntimeStatus(),t={type:`tray-runtime-status`,leader:e.leader,follower:e.follower};this.emit(t)}buildTrayRuntimeStatus(){let e=see(),t=zt();return{leader:{state:e.state,session:e.session,error:e.error??null,reconnectAttempts:e.reconnectAttempts??0},follower:{state:t.state,joinUrl:t.joinUrl,trayId:t.trayId,error:t.error,lastError:t.lastError,reconnectAttempts:t.reconnectAttempts,attachAttempts:t.attachAttempts,lastAttachCode:t.lastAttachCode,connectingSince:t.connectingSince,lastPingTime:t.lastPingTime}}}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}onAgentEvent(e){return this.agentEventListeners.add(e),()=>{this.agentEventListeners.delete(e)}}fanOutAgentEvent(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.fanOutMessageId.get(t);return e||(e=`scoop-${t}-${Ta()}`,this.fanOutMessageId.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput});break}case`tool_end`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError});break}case`tool_ui`:{let t=i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`response_done`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.fanOutMessageId.delete(t);break}case`turn_end`:this.fanOutMessageId.delete(t);break}for(let e of r)for(let n of this.agentEventListeners)try{n(t,e)}catch(e){Sa.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=Ca(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n?a.find(e=>e.name===n||e.folder===n||e.folder===`${n}-scoop`):void 0;if(o||=a.find(e=>e.isCone),!o)return;let s=`sprinkle-${e}-${Date.now()}`,c=fa({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,l={id:s,chatJid:o.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:c,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(o.jid).push({id:s,role:`user`,content:c,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(o.jid),await this.orchestrator.handleMessage(l)}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(e=>e.isCone);if(!t)return;let n=e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),isStreaming:e.isStreaming,model:e.model,usage:e.usage}));if(this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.fanOutMessageId.delete(t.jid),this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.saveMessages(n,e).catch(e=>{Sa.error(`applyFollowerSnapshot persist failed`,{error:e instanceof Error?e.message:String(e)})})}this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?.getScoops().find(e=>e.isCone)?.jid??null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error});break}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopStatuses.set(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromAgentMessages(e){let t=this.orchestrator?.getScoopContext(e.jid);if(!t)return null;let n=t.getAgentMessages();if(n.length===0)return null;let{agentMessagesToChatMessages:r}=await import(`./agent-message-to-chat-DUYzcUYs.js`);return r(n,{source:e.isCone?`cone`:e.name??e.folder}).map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),model:e.model,usage:e.usage,isStreaming:!1}))}async seedBuffersFromAgentState(){if(this.orchestrator)for(let e of this.orchestrator.getScoops()){let t=this.messageBuffers.get(e.jid);if(t&&t.length>0)continue;let n=await this.buildBufferFromAgentMessages(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.fanOutMessageId.delete(e.jid),await this.persistScoopAwait(e.jid))}}async handleRequestScoopMessages(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:n});return}let r=await this.buildBufferFromAgentMessages(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r});return}if(this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;try{let t=(await this.sessionStore.load(n))?.messages??[];t.length>0&&(this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t}))}catch(e){Sa.error(`sessionStore load failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}}async handleConeCreate(e){if(!this.orchestrator)return;let t={jid:`cone_${Date.now()}`,name:e,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()};await this.orchestrator.registerScoop(t),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(t)})}handleRequestSessionStats(e){let t=0,n=0,r=[],i=[],a=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=(this.orchestrator?.getSessionCosts({includeDropped:!0})??[]).reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getBurnRate()??0,r=this.orchestrator?.getContextFills()??[],i=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),a=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type,source:e.source}))}catch{}this.emit({type:`session-stats`,requestId:e,totalCost:t,burnRate:n,fills:r,models:i,scoops:a})}async handleRequestScoopTranscript(e,t){let n=()=>{this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:``})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Ea(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-DUYzcUYs.js`),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:r.isCone?`cone`:r.name??r.folder});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Ea(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromAgentMessages(r);if(a&&a.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}if(this.sessionStore){let n=r.isCone?`session-cone`:`session-${r.folder}`;try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}n()}persistScoop(e){this.persistScoopAwait(e)}async persistScoopAwait(e){if(!this.sessionStore||!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=t.isCone?`session-cone`:`session-${t.folder}`,r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){Sa.error(`persistScoop failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}getBuffer(e){let t=this.messageBuffers.get(e);return t||(t=[],this.messageBuffers.set(e,t)),t}getOrCreateAssistantMsg(e){let t=this.getBuffer(e),n=this.currentMessageId.get(e);if(n){let e=t.find(e=>e.id===n);if(e)return e}n=`scoop-${e}-${Ta()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?.isCone?`cone`:r?.name??`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){ma(e.payload);return}this.handlePanelMessage(e.payload).catch(t=>{console.error(`[kernel-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})}})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[kernel-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`set-model`:this.orchestrator.updateModel();break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`clear-chat`:await this.handleClearChat(e.requestId);break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[kernel-bridge] clear-filesystem failed:`,e));break;case`refresh-model`:this.orchestrator.updateModel();break;case`set-thinking-level`:{let t=e;try{await this.orchestrator.setScoopThinkingLevel(t.scoopJid,t.level,t.effortOverride)}catch(e){console.error(`[kernel-bridge] set-thinking-level failed:`,e)}break}case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.orchestrator.handleWebhookEvent(e.webhookId,e.headers,e.body);break;case`set-follower-forwarding`:this.handleSetFollowerForwarding(e.enabled);break;case`inject-forwarded-lick`:this.handleInjectForwardedLick(e.event);break;case`lick-cherry-host-event`:this.orchestrator.handleCherryHostEvent(e.cherryRuntimeId,e.name,e.detail);break;case`lick-preview`:this.orchestrator.handlePreviewLick(e.event);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[kernel-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:await this.handlePanelCdpCommand(e);break;case`tool-ui-action`:await this.handleToolUIAction(e);break;case`local-storage-set`:this.applyLocalStorageOp(e.type,t=>t.setItem(e.key,e.value));break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key));break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear());break}}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete queued message:`,e)});let n=this.messageBuffers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length!==n.length&&(this.messageBuffers.set(e,r),this.persistScoop(e))}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.persistScoop(e.scoopJid),this.followerSync){e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`,...e.steer?{steer:!0}:{}};await this.orchestrator?.handleMessage(t),this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(await this.orchestrator.unregisterScoop(e),this.messageBuffers.delete(e),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.scoopStatuses.delete(e),t&&this.sessionStore){let e=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.delete(e).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,e,t)})}this.emitScoopList()}async handleClearChat(e){let t=this.orchestrator?.getScoops().find(e=>e.isCone)?.jid;t&&await this.orchestrator?.clearScoopMessages(t),this.sessionStore&&await this.sessionStore.delete(`session-cone`),t&&(this.messageBuffers.delete(t),this.currentMessageId.delete(t),this.fanOutMessageId.delete(t)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[kernel-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.originLabel)}handleSetFollowerForwarding(e){let t=globalThis.__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] set-follower-forwarding ignored: worker LickManager unavailable`);return}e?t.setForwarder(e=>this.emit({type:`forward-lick`,event:e})):t.setForwarder(null)}handleInjectForwardedLick(e){let t=globalThis.__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.emitEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[kernel-bridge] Panel CDP command received but BrowserAPI is null`),this.emit({type:`panel-cdp-response`,id:t,error:`BrowserAPI not available`});return}try{let e=await this.browserAPI.getTransport().send(n,r,i);this.emit({type:`panel-cdp-response`,id:t,result:e})}catch(e){this.emit({type:`panel-cdp-response`,id:t,error:e instanceof Error?e.message:String(e)})}}async handleToolUIAction(e){let{requestId:t,action:n,data:r}=e;if(n===`__mounted`){Yt.markMounted(t);return}try{await Yt.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[kernel-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),Yt.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[kernel-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[];this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.fanOutAgentEvent(e)}};function Ta(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Ea(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
882
+ `)}}function ca(e,t){let n=e.discoveryOrigin??`an origin`,r=e.discoveryUrl??`(unknown URL)`,i=e.discoveryKind===`llms-txt`?`an llms.txt digest`:`an ai-catalog manifest`,a=e.discoveryKind??`unknown`;return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${r}]\n${n} advertises ${i} (kind: ${a}) at ${r}.\nThis is informational — there is no card action. You MAY fetch it (e.g. \`curl ${r}\`) and act on it if it's relevant to the current task; otherwise ignore it.`}}function la(e,t){let n=ta(e);return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${n}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function ua(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return la(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function da(e,t){let n=la(e,t),r=e.lickId;if(!r)return n;let i=e.body?.verb===`upskill`?`\n\nLick ID: ${r}\nUpskill install. To install, call \`lick_confirm\` with this lick id (it runs \`upskill\` with any branch/path scope from the body); to skip, call \`lick_dismiss\`. The card flips to ✓ on confirm / muted ✗ on dismiss.`:`\n\nLick ID: ${r}\nExternal handoff — stays human-gated. Show the approval dip and wait for the user; do NOT use \`lick_confirm\` / \`lick_dismiss\` here. Carry the lick id in the dip action so the card resolves: slicc.lick({action:'accept'|'dismiss', data:{lickId:'${r}'}}).`;return{label:n.label,content:`${n.content}${i}`}}function fa(e){let t=ea[e.type];return e.type===`session-reload`?na(e,t):e.type===`upgrade`?ra(e,t):e.type===`cherry`?ia(e,t):e.type===`preview`?aa(e,t):e.type===`workflow`?oa(e,t):e.type===`sudo-request`?sa(e,t):e.type===`navigate`?da(e,t):e.type===`webhook`?ua(e,t):e.type===`discovery`?ca(e,t):la(e,t)}const pa=new Map;function ma(e){let t=pa.get(e.id);t&&(pa.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result))}const ha=`__slicc_binary__`;function ga(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[ha]===`b64`&&typeof t.data==`string`}function _a(e){if(e instanceof Uint8Array)return{[ha]:`b64`,data:l(e)};if(Array.isArray(e))return e.map(_a);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=_a(r);return t}return e}function va(e){if(ga(e))return u(e.data);if(Array.isArray(e))return e.map(va);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=va(r);return t}return e}const ya=r(`panel-transport`);function ba(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function xa(){return{onMessage:e=>{let t=(t,n,r)=>(ba(t)&&e(va(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=_a(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||ya.error(`Offscreen → panel transport send failed`,{error:t})})}}}const Sa=r(`kernel-bridge`);function Ca(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.action!==`accept`&&t.action!==`dismiss`)return null;let n=t.data,r=n&&typeof n.lickId==`string`?n.lickId:null;return r?{lickId:r,accepted:t.action===`accept`}:null}var wa=class{orchestrator=null;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopStatuses=new Map;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;activeScoopJid=null;agentEventListeners=new Set;fanOutMessageId=new Map;constructor(e){this._transport=e??null}get transport(){return this._transport||=xa(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new Zi;await n.init(),this.sessionStore=n}static createCallbacks(e){return{onResponse:(t,n,r)=>{let i=e.getOrCreateAssistantMsg(t);r?i.content+=n:(i.content=n,i.isStreaming=!1),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n})},onResponseDone:t=>{let n=e.getLatestAssistantMetadata(t),r=e.currentMessageId.get(t);if(r){let i=e.getBuffer(t).find(e=>e.id===r);i&&(i.isStreaming=!1,n&&Object.assign(i,n)),e.currentMessageId.delete(t)}e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,...n??{}})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${Ta()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n}),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onStatusChange:(t,n)=>{e.scoopStatuses.set(t,n),n===`ready`&&e.currentMessageId.delete(t),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n)=>{e.emit({type:`compaction-state`,scoopJid:t,state:n})},onError:(t,n)=>{e.emit({type:`error`,scoopJid:t,error:n})},onLickBackpressure:(t,n)=>{e.emit({type:`lick-backpressure`,scoopJid:t,...n})},onToolStart:(t,n,r)=>{Ut.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{Ut.has(n)||e.bufferToolEnd(t,n,r,i)},onToolUI:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i})},onToolUIDone:(t,n)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n){let r=Gt(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:Ta(),name:t,input:r}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:r})}bufferToolEnd(e,t,n,r){let i=this.currentMessageId.get(e);if(i){let a=this.getBuffer(e).find(e=>e.id===i);if(a?.toolCalls){let e=[...a.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=Kt(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:Wt(n),isError:r})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.persistScoop(e),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.fanOutMessageId.delete(e.jid),this.scoopStatuses.delete(e.jid),!e.isCone&&this.sessionStore&&this.sessionStore.delete(`session-${e.folder}`).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState,this.persistScoop(e)),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){let t=e.config&&(e.config.modelId!==void 0||e.config.thinkingLevel!==void 0)?{...e.config.modelId===void 0?{}:{modelId:e.config.modelId},...e.config.thinkingLevel===void 0?{}:{thinkingLevel:e.config.thinkingLevel}}:void 0;return{jid:e.jid,name:e.name,folder:e.folder,isCone:e.isCone,assistantLabel:e.assistantLabel,status:this.scoopStatuses.get(e.jid)??`ready`,...t?{config:t}:{}}}buildStateSnapshot(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[],t=e.find(e=>e.isCone);return{type:`state-snapshot`,scoops:e,activeScoopJid:this.getActiveScoopJid()??t?.jid??null,trayRuntimeStatus:this.buildTrayRuntimeStatus()}}emitTrayRuntimeStatus(){let e=this.buildTrayRuntimeStatus(),t={type:`tray-runtime-status`,leader:e.leader,follower:e.follower};this.emit(t)}buildTrayRuntimeStatus(){let e=see(),t=zt();return{leader:{state:e.state,session:e.session,error:e.error??null,reconnectAttempts:e.reconnectAttempts??0},follower:{state:t.state,joinUrl:t.joinUrl,trayId:t.trayId,error:t.error,lastError:t.lastError,reconnectAttempts:t.reconnectAttempts,attachAttempts:t.attachAttempts,lastAttachCode:t.lastAttachCode,connectingSince:t.connectingSince,lastPingTime:t.lastPingTime}}}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}onAgentEvent(e){return this.agentEventListeners.add(e),()=>{this.agentEventListeners.delete(e)}}fanOutAgentEvent(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.fanOutMessageId.get(t);return e||(e=`scoop-${t}-${Ta()}`,this.fanOutMessageId.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput});break}case`tool_end`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError});break}case`tool_ui`:{let t=i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`response_done`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.fanOutMessageId.delete(t);break}case`turn_end`:this.fanOutMessageId.delete(t);break}for(let e of r)for(let n of this.agentEventListeners)try{n(t,e)}catch(e){Sa.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=Ca(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n?a.find(e=>e.name===n||e.folder===n||e.folder===`${n}-scoop`):void 0;if(o||=a.find(e=>e.isCone),!o)return;let s=`sprinkle-${e}-${Date.now()}`,c=fa({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,l={id:s,chatJid:o.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:c,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(o.jid).push({id:s,role:`user`,content:c,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(o.jid),await this.orchestrator.handleMessage(l)}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(e=>e.isCone);if(!t)return;let n=e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),isStreaming:e.isStreaming,model:e.model,usage:e.usage}));if(this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.fanOutMessageId.delete(t.jid),this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.saveMessages(n,e).catch(e=>{Sa.error(`applyFollowerSnapshot persist failed`,{error:e instanceof Error?e.message:String(e)})})}this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?.getScoops().find(e=>e.isCone)?.jid??null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error});break}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopStatuses.set(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromAgentMessages(e){let t=this.orchestrator?.getScoopContext(e.jid);if(!t)return null;let n=t.getAgentMessages();if(n.length===0)return null;let{agentMessagesToChatMessages:r}=await import(`./agent-message-to-chat-DUYzcUYs.js`);return r(n,{source:e.isCone?`cone`:e.name??e.folder}).map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),model:e.model,usage:e.usage,isStreaming:!1}))}async seedBuffersFromAgentState(){if(this.orchestrator)for(let e of this.orchestrator.getScoops()){let t=this.messageBuffers.get(e.jid);if(t&&t.length>0)continue;let n=await this.buildBufferFromAgentMessages(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.fanOutMessageId.delete(e.jid),await this.persistScoopAwait(e.jid))}}async handleRequestScoopMessages(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:n});return}let r=await this.buildBufferFromAgentMessages(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r});return}if(this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;try{let t=(await this.sessionStore.load(n))?.messages??[];t.length>0&&(this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t}))}catch(e){Sa.error(`sessionStore load failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}}async handleConeCreate(e){if(!this.orchestrator)return;let t={jid:`cone_${Date.now()}`,name:e,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()};await this.orchestrator.registerScoop(t),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(t)})}handleRequestSessionStats(e){let t=0,n=0,r=[],i=[],a=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=(this.orchestrator?.getSessionCosts({includeDropped:!0})??[]).reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getBurnRate()??0,r=this.orchestrator?.getContextFills()??[],i=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),a=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type,source:e.source}))}catch{}this.emit({type:`session-stats`,requestId:e,totalCost:t,burnRate:n,fills:r,models:i,scoops:a})}async handleRequestScoopTranscript(e,t){let n=()=>{this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:``})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Ea(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-DUYzcUYs.js`),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:r.isCone?`cone`:r.name??r.folder});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Ea(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromAgentMessages(r);if(a&&a.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}if(this.sessionStore){let n=r.isCone?`session-cone`:`session-${r.folder}`;try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}n()}persistScoop(e){this.persistScoopAwait(e)}async persistScoopAwait(e){if(!this.sessionStore||!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=t.isCone?`session-cone`:`session-${t.folder}`,r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){Sa.error(`persistScoop failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}getBuffer(e){let t=this.messageBuffers.get(e);return t||(t=[],this.messageBuffers.set(e,t)),t}getOrCreateAssistantMsg(e){let t=this.getBuffer(e),n=this.currentMessageId.get(e);if(n){let e=t.find(e=>e.id===n);if(e)return e}n=`scoop-${e}-${Ta()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?.isCone?`cone`:r?.name??`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){ma(e.payload);return}this.handlePanelMessage(e.payload).catch(t=>{console.error(`[kernel-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})}})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[kernel-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`set-model`:this.orchestrator.updateModel();break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`clear-chat`:await this.handleClearChat(e.requestId);break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[kernel-bridge] clear-filesystem failed:`,e));break;case`refresh-model`:this.orchestrator.updateModel();break;case`set-thinking-level`:{let t=e;try{await this.orchestrator.setScoopThinkingLevel(t.scoopJid,t.level,t.effortOverride)}catch(e){console.error(`[kernel-bridge] set-thinking-level failed:`,e)}break}case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.orchestrator.handleWebhookEvent(e.webhookId,e.headers,e.body);break;case`set-follower-forwarding`:this.handleSetFollowerForwarding(e.enabled);break;case`inject-forwarded-lick`:this.handleInjectForwardedLick(e.event);break;case`lick-cherry-host-event`:this.orchestrator.handleCherryHostEvent(e.cherryRuntimeId,e.name,e.detail);break;case`lick-preview`:this.orchestrator.handlePreviewLick(e.event);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[kernel-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:await this.handlePanelCdpCommand(e);break;case`tool-ui-action`:await this.handleToolUIAction(e);break;case`local-storage-set`:this.applyLocalStorageOp(e.type,t=>t.setItem(e.key,e.value));break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key));break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear());break}}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete queued message:`,e)});let n=this.messageBuffers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length!==n.length&&(this.messageBuffers.set(e,r),this.persistScoop(e))}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.persistScoop(e.scoopJid),this.followerSync){e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`,...e.steer?{steer:!0}:{}};await this.orchestrator?.handleMessage(t),this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(await this.orchestrator.unregisterScoop(e),this.messageBuffers.delete(e),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.scoopStatuses.delete(e),t&&this.sessionStore){let e=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.delete(e).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,e,t)})}this.emitScoopList()}async handleClearChat(e){let t=this.orchestrator?.getScoops().find(e=>e.isCone)?.jid;t&&await this.orchestrator?.clearScoopMessages(t),this.sessionStore&&await this.sessionStore.delete(`session-cone`),t&&(this.messageBuffers.delete(t),this.currentMessageId.delete(t),this.fanOutMessageId.delete(t)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[kernel-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.originLabel)}handleSetFollowerForwarding(e){let t=globalThis.__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] set-follower-forwarding ignored: worker LickManager unavailable`);return}e?t.setForwarder(e=>this.emit({type:`forward-lick`,event:e})):t.setForwarder(null)}handleInjectForwardedLick(e){let t=globalThis.__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.emitEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[kernel-bridge] Panel CDP command received but BrowserAPI is null`),this.emit({type:`panel-cdp-response`,id:t,error:`BrowserAPI not available`});return}try{let e=await this.browserAPI.getTransport().send(n,r,i);this.emit({type:`panel-cdp-response`,id:t,result:e})}catch(e){this.emit({type:`panel-cdp-response`,id:t,error:e instanceof Error?e.message:String(e)})}}async handleToolUIAction(e){let{requestId:t,action:n,data:r}=e;if(n===`__mounted`){Yt.markMounted(t);return}try{await Yt.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[kernel-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),Yt.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[kernel-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[];this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.fanOutAgentEvent(e)}};function Ta(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Ea(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
883
883
  `)}const Da=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function Oa(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(Da.map(e=>ka(i,e,t,r)))).filter(e=>e!==null)}async function ka(e,t,n,r){let i=e+t.path,a=new AbortController,o=setTimeout(()=>a.abort(Error(`timeout`)),r);try{let e=await n(i,{method:`GET`,signal:a.signal});return e.status!==200||!Aa(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function Aa(e,t){if(e==null)return!0;let n=e.toLowerCase();return n.length===0?!0:n.includes(`text/html`)||n.includes(`application/xhtml`)?!1:t===`ai-catalog`?n.includes(`json`)||n.includes(`text/plain`)||n.includes(`octet-stream`):n.includes(`text/plain`)||n.includes(`markdown`)||n.includes(`octet-stream`)}const ja=r(`navigation-watcher`);function Ma(e,t){return Un(e,t)}var Na=class{transport;onEvent;sessions=new Map;started=!1;onDiscovery;probeFetch;isDiscoveryEnabled;probeTimeoutMs;probedOrigins=new Set;onAttachedToTarget=e=>{this.handleAttachedToTarget(e)};onDetachedFromTarget=e=>{let t=e.sessionId;t&&this.sessions.delete(t)};onTargetInfoChanged=e=>{let t=e.targetInfo;if(t?.targetId)for(let e of this.sessions.values())e.targetId===t.targetId&&(typeof t.title==`string`&&(e.title=t.title),typeof t.url==`string`&&(e.url=t.url))};onTargetCreated=e=>{this.handleTargetCreated(e)};onFrameNavigated=e=>{let t=e.sessionId;if(!t)return;let n=this.sessions.get(t);if(!n)return;let r=e.frame;r?.id&&(r.parentId||(n.rootFrameId=r.id,typeof r.url==`string`&&(n.url=r.url)))};onResponseReceived=e=>{let t=e.sessionId;if(!t)return;let n=this.sessions.get(t);if(!n||e.type!==`Document`)return;let r=e.frameId;if(!r||r!==n.rootFrameId)return;let i=e.response;if(!i)return;let a=typeof i.url==`string`&&i.url.length>0?i.url:n.url;if(!a)return;let{match:o,links:s}=Ma(i.headers,a);if(o){let e={url:a,verb:o.verb,target:o.target,links:s,targetId:n.targetId};o.instruction!=null&&(e.instruction=o.instruction),o.branch!=null&&(e.branch=o.branch),o.path!=null&&(e.path=o.path),n.title!=null&&(e.title=n.title),this.onEvent(e)}this.maybeRunDiscovery(a,s,n.targetId)};constructor(e,t,n={}){this.transport=e,this.onEvent=t,this.onDiscovery=n.onDiscovery,this.probeFetch=n.probeFetch,this.isDiscoveryEnabled=n.isDiscoveryEnabled??(()=>!0),this.probeTimeoutMs=n.probeTimeoutMs}maybeRunDiscovery(e,t,n){if(!this.onDiscovery||!this.isDiscoveryEnabled())return;let r;try{r=new URL(e).origin}catch{return}let i=Gn(t);i&&this.onDiscovery({origin:r,kind:i.kind,url:i.url,targetId:n}),this.probeFetch&&!this.probedOrigins.has(r)&&(this.probedOrigins.add(r),this.runWellKnownProbe(r,n))}async runWellKnownProbe(e,t){if(!(!this.probeFetch||!this.onDiscovery))try{let n=await Oa(e,this.probeFetch,{timeoutMs:this.probeTimeoutMs});for(let r of n)this.onDiscovery({origin:e,kind:r.kind,url:r.url,targetId:t})}catch(t){ja.debug(`Well-known discovery probe failed`,{origin:e,error:t instanceof Error?t.message:String(t)})}}async start(){if(!this.started){this.transport.on(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.on(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.on(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.on(`Target.targetCreated`,this.onTargetCreated),this.transport.on(`Page.frameNavigated`,this.onFrameNavigated),this.transport.on(`Network.responseReceived`,this.onResponseReceived);try{await this.transport.send(`Target.setDiscoverTargets`,{discover:!0})}catch(e){ja.error(`Failed to enable target discovery`,{error:e instanceof Error?e.message:String(e)}),this.transport.off(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.off(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.off(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.off(`Target.targetCreated`,this.onTargetCreated),this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.transport.off(`Network.responseReceived`,this.onResponseReceived);return}this.started=!0;try{let e=(await this.transport.send(`Target.getTargets`)).targetInfos??[];for(let t of e){if(t.type!==`page`)continue;let e=t.attached===!0,n=t.targetId;if(!(e||typeof n!=`string`))try{await this.transport.send(`Target.attachToTarget`,{targetId:n,flatten:!0})}catch(e){ja.debug(`Failed to attach to preexisting target`,{targetId:n,error:e instanceof Error?e.message:String(e)})}}}catch(e){ja.debug(`Failed to enumerate preexisting targets`,{error:e instanceof Error?e.message:String(e)})}}}async stop(){if(this.started){this.started=!1,this.transport.off(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.off(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.off(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.off(`Target.targetCreated`,this.onTargetCreated),this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.transport.off(`Network.responseReceived`,this.onResponseReceived),this.sessions.clear();try{await this.transport.send(`Target.setDiscoverTargets`,{discover:!1})}catch(e){ja.debug(`Failed to disable target discovery on stop`,{error:e instanceof Error?e.message:String(e)})}}}async handleTargetCreated(e){let t=e.targetInfo;if(!(t?.type!==`page`||typeof t.targetId!=`string`)&&!t.attached)try{await this.transport.send(`Target.attachToTarget`,{targetId:t.targetId,flatten:!0})}catch(e){ja.debug(`Failed to attach to discovered target`,{targetId:t.targetId,error:e instanceof Error?e.message:String(e)})}}async handleAttachedToTarget(e){let t=e.sessionId,n=e.targetInfo;if(!(!t||!n||n.type!==`page`||typeof n.targetId!=`string`)){this.sessions.set(t,{targetId:n.targetId,rootFrameId:null,title:n.title,url:n.url});try{await this.transport.send(`Page.enable`,{},t),await this.transport.send(`Network.enable`,{},t);let e=(await this.transport.send(`Page.getFrameTree`,{},t)).frameTree?.frame;if(e?.id&&typeof e.id==`string`){let n=this.sessions.get(t);n&&(n.rootFrameId=e.id)}}catch(e){ja.debug(`Failed to enable Page/Network on attached target`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}}};const Pa=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function Fa(e){return Pa.test(e)}function Ia(e,t){return`(${e} && ${t})`}function La(e,t){return`(${e} || ${t})`}function Ra(e){return`!(${e})`}function za(e){return`Array.isArray(${e})`}function Ba(e){return`Guard.IsAsyncIterator(${e})`}function Va(e){return`typeof ${e} === "bigint"`}function Ha(e){return`typeof ${e} === "boolean"`}function Ua(e){return`Number.isInteger(${e})`}function Wa(e){return`Guard.IsIterator(${e})`}function Ga(e){return`${e} === null`}function Ka(e){return`Number.isFinite(${e})`}function qa(e){return Ia(Ja(e),Ra(za(e)))}function Ja(e){return`typeof ${e} === "object" && ${e} !== null`}function Ya(e){return`typeof ${e} === "string"`}function Xa(e){return`typeof ${e} === "symbol"`}function Za(e){return`${e} === undefined`}function Qa(e){return`typeof ${e} === "function"`}function $a(e){return`Guard.IsConstructor(${e})`}function eo(e,t){return`${e} === ${t}`}function to(e,t){return`${e} > ${t}`}function no(e,t){return`${e} < ${t}`}function ro(e,t){return`${e} <= ${t}`}function io(e,t){return`${e} >= ${t}`}function ao(e,t){return`Guard.IsMinLength(${e}, ${t})`}function oo(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function so(e,t,n,r){return H(t,`0`)?`${e}.every((${n[0]}, ${n[1]}) => ${r})`:`((value, callback) => { for(let index = ${t}; index < value.length; index++) if (!callback(value[index], index)) return false; return true })(${e}, (${n[0]}, ${n[1]}) => ${r})`}function co(e){return`Object.entries(${e})`}function lo(e){return`Object.getOwnPropertyNames(${e})`}function uo(e,t){return H(t,`"__proto__"`)||H(t,`"constructor"`)?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function fo(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function po(e){return`[${e.join(`, `)}]`}function mo(e,t){return`((${e.join(`, `)}) => ${t})`}function ho(e,t){return`${e}(${t.join(`, `)})`}function go(e,t){return`new ${e}(${t.join(`, `)})`}function G(e,t){return`${e}${Fa(t)?`.${t}`:`[${K(t)}]`}`}function K(e){return T(e)?JSON.stringify(e):`${e}`}function _o(e,t,n){return`(${e} ? ${t} : ${n})`}function vo(e){return`{ ${e.join(`; `)}; }`}function yo(e,t){return`const ${e} = ${t}`}function bo(e,t){return`if(${e}) { ${t} }`}function xo(e){return`return ${e}`}function So(e){return H(e.length,0)?`true`:e.reduce((e,t)=>Ia(e,t))}function Co(e){return H(e.length,0)?`false`:e.reduce((e,t)=>La(e,t))}function wo(e){return`++${e}`}function To(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}function Eo(e,t){return t[e.length]?.(...e)??(()=>{throw Error(`Invalid Arguments`)})()}let Do;function mee(){try{return ko(`null`)(),!0}catch{return!1}}function Oo(){return Ge(Do)&&(Do=mee()),Do&&z().useAcceleration}function ko(...e){return new globalThis.Function(...e)}function hee(e){switch(e.keyword){case`additionalProperties`:return`must not have additional properties`;case`anyOf`:return`must match a schema in anyOf`;case`boolean`:return`schema is false`;case`const`:return`must be equal to constant`;case`contains`:return`must contain at least 1 valid item`;case`dependencies`:return`must have properties ${e.params.dependencies.join(`, `)} when property ${e.params.property} is present`;case`dependentRequired`:return`must have properties ${e.params.dependencies.join(`, `)} when property ${e.params.property} is present`;case`enum`:return`must be equal to one of the allowed values`;case`exclusiveMaximum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`exclusiveMinimum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`format`:return`must match format "${e.params.format}"`;case`if`:return`must match "${e.params.failingKeyword}" schema`;case`maxItems`:return`must not have more than ${e.params.limit} items`;case`maxLength`:return`must not have more than ${e.params.limit} characters`;case`maxProperties`:return`must not have more than ${e.params.limit} properties`;case`maximum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`minItems`:return`must not have fewer than ${e.params.limit} items`;case`minLength`:return`must not have fewer than ${e.params.limit} characters`;case`minProperties`:return`must not have fewer than ${e.params.limit} properties`;case`minimum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`multipleOf`:return`must be multiple of ${e.params.multipleOf}`;case`not`:return`must not be valid`;case`oneOf`:return`must match exactly one schema in oneOf`;case`pattern`:return`must match pattern "${e.params.pattern}"`;case`propertyNames`:return`property names ${e.params.propertyNames.join(`, `)} are invalid`;case`required`:return`must have required properties ${e.params.requiredProperties.join(`, `)}`;case`type`:return typeof e.params.type==`string`?`must be ${e.params.type}`:`must be either ${e.params.type.join(` or `)}`;case`unevaluatedItems`:return`must not have unevaluated items`;case`unevaluatedProperties`:return`must not have unevaluated properties`;case`uniqueItems`:return`must not have duplicate items`;case`~guard`:return`must match check function`;case`~refine`:return e.params.message;default:return`an unknown validation error occurred`}}let gee=hee;function _ee(){return gee}const vee=[/prompt is too long/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i,/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i],yee=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function bee(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!yee.some(t=>t.test(e.errorMessage))&&vee.some(t=>t.test(e.errorMessage))||t&&e.stopReason===`stop`&&e.usage.input+e.usage.cacheRead>t||t&&e.stopReason===`length`&&e.usage.output===0&&e.usage.input+e.usage.cacheRead>=t*.99)}function xee(e){return F(e)&&U(e,`check`)&&U(e,`errors`)&&tt(e.check)&&tt(e.errors)}function Ao(e){return U(e,`~guard`)&&xee(e[`~guard`])}function jo(e){return U(e,`~refine`)&&V(e[`~refine`])&&Ze(e[`~refine`],0,e=>F(e)&&U(e,`check`)&&U(e,`error`)&&tt(e.check)&&tt(e.error))}function Mo(e){return F(e)&&!V(e)}function No(e){return je(e)}function Po(e){return Mo(e)||No(e)}function Fo(e){return U(e,`additionalItems`)&&Po(e.additionalItems)}function Io(e){return U(e,`additionalProperties`)&&Po(e.additionalProperties)}function Lo(e){return U(e,`allOf`)&&V(e.allOf)&&e.allOf.every(e=>Po(e))}function Ro(e){return U(e,`$anchor`)&&T(e.$anchor)}function zo(e){return U(e,`anyOf`)&&V(e.anyOf)&&e.anyOf.every(e=>Po(e))}function Bo(e){return U(e,`const`)}function Vo(e){return U(e,`contains`)&&Po(e.contains)}function Ho(e){return U(e,`default`)}function Uo(e){return U(e,`dependencies`)&&F(e.dependencies)&&Object.values(e.dependencies).every(e=>Po(e)||V(e)&&e.every(e=>T(e)))}function Wo(e){return U(e,`dependentRequired`)&&F(e.dependentRequired)&&Object.values(e.dependentRequired).every(e=>V(e)&&e.every(e=>T(e)))}function Go(e){return U(e,`dependentSchemas`)&&F(e.dependentSchemas)&&Object.values(e.dependentSchemas).every(e=>Po(e))}function Ko(e){return U(e,`$dynamicAnchor`)&&T(e.$dynamicAnchor)}function qo(e){return U(e,`$dynamicRef`)&&T(e.$dynamicRef)}function Jo(e){return U(e,`else`)&&Po(e.else)}function Yo(e){return U(e,`enum`)&&V(e.enum)}function Xo(e){return U(e,`exclusiveMaximum`)&&(ht(e.exclusiveMaximum)||st(e.exclusiveMaximum))}function Zo(e){return U(e,`exclusiveMinimum`)&&(ht(e.exclusiveMinimum)||st(e.exclusiveMinimum))}function Qo(e){return U(e,`format`)&&T(e.format)}function $o(e){return U(e,`$id`)&&T(e.$id)}function es(e){return U(e,`if`)&&Po(e.if)}function ts(e){return U(e,`items`)&&(Po(e.items)||V(e.items)&&e.items.every(e=>Po(e)))}function ns(e){return ts(e)&&V(e.items)}function rs(e){return U(e,`maximum`)&&(ht(e.maximum)||st(e.maximum))}function is(e){return U(e,`maxContains`)&&ht(e.maxContains)}function as(e){return U(e,`maxItems`)&&ht(e.maxItems)}function os(e){return U(e,`maxLength`)&&ht(e.maxLength)}function ss(e){return U(e,`maxProperties`)&&ht(e.maxProperties)}function cs(e){return U(e,`minimum`)&&(ht(e.minimum)||st(e.minimum))}function ls(e){return U(e,`minContains`)&&ht(e.minContains)}function us(e){return U(e,`minItems`)&&ht(e.minItems)}function ds(e){return U(e,`minLength`)&&ht(e.minLength)}function fs(e){return U(e,`minProperties`)&&ht(e.minProperties)}function ps(e){return U(e,`multipleOf`)&&(ht(e.multipleOf)||st(e.multipleOf))}function ms(e){return U(e,`not`)&&Po(e.not)}function hs(e){return U(e,`oneOf`)&&V(e.oneOf)&&e.oneOf.every(e=>Po(e))}function gs(e){return U(e,`pattern`)&&(T(e.pattern)||e.pattern instanceof RegExp)}function _s(e){return U(e,`patternProperties`)&&F(e.patternProperties)&&Object.values(e.patternProperties).every(e=>Po(e))}function vs(e){return U(e,`prefixItems`)&&V(e.prefixItems)&&e.prefixItems.every(e=>Po(e))}function ys(e){return U(e,`properties`)&&F(e.properties)&&Object.values(e.properties).every(e=>Po(e))}function bs(e){return U(e,`propertyNames`)&&(F(e.propertyNames)||Po(e.propertyNames))}function xs(e){return U(e,`$recursiveAnchor`)&&je(e.$recursiveAnchor)}function Ss(e){return xs(e)&&H(e.$recursiveAnchor,!0)}function Cs(e){return U(e,`$recursiveRef`)&&T(e.$recursiveRef)}function ws(e){return U(e,`$ref`)&&T(e.$ref)}function Ts(e){return U(e,`required`)&&V(e.required)&&e.required.every(e=>T(e))}function Es(e){return U(e,`then`)&&Po(e.then)}function Ds(e){return U(e,`type`)&&(T(e.type)||V(e.type)&&e.type.every(e=>T(e)))}function Os(e){return U(e,`uniqueItems`)&&je(e.uniqueItems)}function ks(e){return U(e,`unevaluatedItems`)&&Po(e.unevaluatedItems)}function As(e){return U(e,`unevaluatedProperties`)&&Po(e.unevaluatedProperties)}function js(e){return ks(e)||As(e)||M(e).some(t=>Ns(e[t]))}function Ms(e){return e.some(e=>Ns(e))}function Ns(e){return V(e)?Ms(e):F(e)?js(e):!1}function Ps(e,t){return Ns(t)||M(e).some(t=>Ns(e[t]))}var Fs=class{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return ho(G(`context`,`Push`),[])}Pop(){return ho(G(`context`,`Pop`),[])}AddIndex(e){return ho(G(`context`,`AddIndex`),[e])}AddKey(e){return ho(G(`context`,`AddKey`),[e])}Merge(e){return ho(G(`context`,`Merge`),[e])}},Is=class{constructor(){let e=new Set,t=new Set;this.stack=[{indices:e,keys:t}]}Push(){let e=new Set,t=new Set;return this.stack.push({indices:e,keys:t}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let t of e)t.GetIndices().forEach(e=>this.GetIndices().add(e)),t.GetKeys().forEach(e=>this.GetKeys().add(e));return!0}},Ls=class extends Is{constructor(e){super(),this.callback=e}AddError(e){return this.callback(e),!1}},Rs=class extends Ls{constructor(){super(e=>this.errors.push(e)),this.errors=[]}AddError(e){return this.errors.push(e),!1}GetErrors(){return this.errors}};const zs={identifier:`External`,variables:[]};function Bs(e){let t=`External[${zs.variables.length}]`;return zs.variables.push(e),t}function Vs(){zs.variables=[]}function Hs(){return{...zs}}function Us(e,t,n,r){return ho(G(G(Bs(n),`~guard`),`check`),[r])}function Ws(e,t,n,r){return n[`~guard`].check(r)}function Gs(e,t,n,r,i,a){return i[`~guard`].check(a)||t.AddError({keyword:`~guard`,schemaPath:n,instancePath:r,params:{errors:i[`~guard`].errors(a)}})}function Ks(e,t,n,r){return so(Bs(n[`~refine`].map(e=>e)),K(0),[`refinement`,`_`],ho(G(`refinement`,`check`),[r]))}function qs(e,t,n,r){return Ze(n[`~refine`],0,(e,t)=>e.check(r))}function Js(e,t,n,r,i,a){return at(i[`~refine`],0,(e,i)=>e.check(a)||t.AddError({keyword:`~refine`,schemaPath:n,instancePath:r,params:{index:i,message:e.error(a)}}))}let Ys=0;function Xs(){return`var_${Ys++}`}function Zs(e){return ts(e)&&V(e.items)}function Qs(e,t,n,r){if(!Zs(n))return K(!0);let[i,a]=[Xs(),Xs()],o=Df(e,t,n.additionalItems,i),s=no(a,K(n.items.length)),c=t.AddIndex(a),l=t.UseUnevaluated()?La(s,Ia(o,c)):La(s,o);return ho(G(r,`every`),[mo([i,a],l)])}function $s(e,t,n,r){return!Zs(n)||r.every((r,i)=>yt(i,n.items.length)||kf(e,t,n.additionalItems,r)&&t.AddIndex(i))}function ec(e,t,n,r,i,a){return!Zs(i)||a.every((a,o)=>{let s=`${n}/additionalItems`,c=`${r}/${o}`;return yt(o,i.items.length)||jf(e,t,s,c,i.additionalItems,a)&&t.AddIndex(o)})}function tc(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`}function nc(e){let t=[];return _s(e)&&t.push(...M(e.patternProperties)),ys(e)&&t.push(...M(e.properties).map(tc)),H(t.length,0)?`(?!)`:`(${t.join(`|`)})`}function rc(e,t,n){return Ts(t)&&ys(t)&&!_s(t)&&H(t.additionalProperties,!1)&&H(M(t.properties).length,t.required.length)}function ic(e,t,n){return eo(G(ho(G(`Object`,`getOwnPropertyNames`),[n]),`length`),K(t.required.length))}function ac(e,t,n,r){let[i,a]=[Xs(),Xs()],o=Bs(new RegExp(nc(n))),s=Df(e,t,n.additionalProperties,`${r}[${i}]`),c=ho(G(o,`test`),[i]),l=t.AddKey(i),u=t.UseUnevaluated()?La(c,Ia(s,l)):La(c,s);return so(lo(r),K(0),[i,a],u)}function oc(e,t,n,r){return rc(t,n,r)?ic(t,n,r):ac(e,t,n,r)}function sc(e,t,n,r){let i=new RegExp(nc(n));return Ze(M(r),0,(a,o)=>i.test(a)||kf(e,t,n.additionalProperties,r[a])&&t.AddKey(a))}function cc(e,t,n,r,i,a){let o=new RegExp(nc(i)),s=[];return at(M(a),0,(c,l)=>{let u=`${n}/additionalProperties`,d=`${r}/${c}`,f=new Rs,p=o.test(c)||jf(e,f,u,d,i.additionalProperties,a[c])&&t.AddKey(c);return p||s.push(c),p})||t.AddError({keyword:`additionalProperties`,schemaPath:n,instancePath:r,params:{additionalProperties:s}})}function lc(e,t,n,r,i){let a=yo(`results`,`[]`),o=n.map((e,t)=>yo(`context_${t}`,go(`CheckContext`,[]))),s=n.map((n,i)=>yo(`condition_${i}`,ho(mo([`context`],Of(e,t,n,r)),[`context_${i}`]))),c=n.map((e,t)=>bo(`condition_${t}`,ho(G(`results`,`push`),[`context_${t}`]))),l=xo(Ia(i,t.Merge(`results`)));return ho(mo([],vo([a,...o,...s,...c,l])),[])}function uc(e,t,n,r){return lc(e,t,n.allOf,r,eo(G(`results`,`length`),K(n.allOf.length)))}function dc(e,t,n,r){return So(n.allOf.map(n=>Of(e,t,n,r)))}function fc(e,t,n,r){return t.UseUnevaluated()?uc(e,t,n,r):dc(e,t,n,r)}function pc(e,t,n,r){let i=n.allOf.reduce((t,n)=>{let i=new Is;return Af(e,i,n,r)?[...t,i]:t},[]);return H(i.length,n.allOf.length)&&t.Merge(i)}function mc(e,t,n,r,i,a){let o=[],s=i.allOf.reduce((t,i,s)=>{let c=`${n}/allOf/${s}`,l=new Rs,u=Mf(e,l,c,r,i,a);return u||o.push(l),u?[...t,l]:t},[]),c=H(s.length,i.allOf.length)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c}function hc(e,t,n,r){return lc(e,t,n.anyOf,r,to(G(`results`,`length`),K(0)))}function gc(e,t,n,r){return Co(n.anyOf.map(n=>Of(e,t,n,r)))}function _c(e,t,n,r){return t.UseUnevaluated()?hc(e,t,n,r):gc(e,t,n,r)}function vc(e,t,n,r){let i=n.anyOf.reduce((t,n)=>{let i=new Is;return Af(e,i,n,r)?[...t,i]:t},[]);return Be(i.length,0)&&t.Merge(i)}function yc(e,t,n,r,i,a){let o=[],s=i.anyOf.reduce((t,i,s)=>{let c=new Rs,l=Mf(e,c,`${n}/anyOf/${s}`,r,i,a);return l||o.push(c),l?[...t,c]:t},[]),c=Be(s.length,0)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c||t.AddError({keyword:`anyOf`,schemaPath:n,instancePath:r,params:{}})}function bc(e,t,n,r){return K(!!n)}function xc(e,t,n,r){return n}function Sc(e,t,n,r,i,a){return xc(e,t,i,a)||t.AddError({keyword:`boolean`,schemaPath:n,instancePath:r,params:{}})}function Cc(e,t,n,r){return Ue(n.const)?eo(r,K(n.const)):fo(r,Bs(n.const))}function wc(e,t,n,r){return Ue(n.const)?H(r,n.const):Ne(r,n.const)}function Tc(e,t,n,r,i,a){return wc(e,t,i,a)||t.AddError({keyword:`const`,schemaPath:n,instancePath:r,params:{allowedValue:i.const}})}function Ec(e){return!(ls(e)&&H(e.minContains,0))}function Dc(e,t,n,r){if(!Ec(n))return K(!0);let i=Xs();return Ia(Ra(eo(G(r,`length`),K(0))),ho(G(r,`some`),[mo([i],Of(e,t,n.contains,i))]))}function Oc(e,t,n,r){return!Ec(n)||!H(r.length,0)&&r.some(r=>Af(e,t,n.contains,r))}function kc(e,t,n,r,i,a){return Oc(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:1}})}function Ac(e,t,n,r){return La(eo(G(lo(r),`length`),K(0)),So(Fe(n.dependencies).map(([n,i])=>{let a=Ra(uo(r,K(n))),o=Of(e,t,i,r);return La(a,V(i)?(e=>So(e.map(e=>uo(r,K(e)))))(i):o)})))}function jc(e,t,n,r){let i=H(M(r).length,0),a=Ze(Fe(n.dependencies),0,([n,i])=>!U(r,n)||(V(i)?i.every(e=>U(r,e)):Af(e,t,i,r)));return i||a}function Mc(e,t,n,r,i,a){let o=H(M(a).length,0),s=at(Fe(i.dependencies),0,([i,o])=>{let s=`${n}/dependencies/${i}`;return!U(a,i)||(V(o)?o.every(e=>U(a,e)||t.AddError({keyword:`dependencies`,schemaPath:n,instancePath:r,params:{property:i,dependencies:o}})):Mf(e,t,s,r,o,a))});return o||s}function Nc(e,t,n,r){return La(eo(G(lo(r),`length`),K(0)),So(Fe(n.dependentRequired).map(([e,t])=>La(Ra(uo(r,K(e))),So(t.map(e=>uo(r,K(e))))))))}function Pc(e,t,n,r){let i=H(M(r).length,0),a=Ze(Fe(n.dependentRequired),0,([e,t])=>!U(r,e)||t.every(e=>U(r,e)));return i||a}function Fc(e,t,n,r,i,a){let o=H(M(a).length,0),s=at(Fe(i.dependentRequired),0,([e,i])=>!U(a,e)||at(i,0,o=>U(a,o)||t.AddError({keyword:`dependentRequired`,schemaPath:n,instancePath:r,params:{property:e,dependencies:i}})));return o||s}function Ic(e,t,n,r){return La(eo(G(lo(r),`length`),K(0)),So(Fe(n.dependentSchemas).map(([n,i])=>La(Ra(uo(r,K(n))),Of(e,t,i,r)))))}function Lc(e,t,n,r){let i=H(M(r).length,0),a=Ze(Fe(n.dependentSchemas),0,([n,i])=>!U(r,n)||Af(e,t,i,r));return i||a}function Rc(e,t,n,r,i,a){let o=H(M(a).length,0),s=at(Fe(i.dependentSchemas),0,([i,o])=>{let s=`${n}/dependentSchemas/${i}`;return!U(a,i)||Mf(e,t,s,r,o,a)});return o||s}function zc(e,t,n,r){return Rf(e,t,e.DynamicRef(n)??!1,r)}function Bc(e,t,n,r){let i=e.DynamicRef(n)??!1;return Po(i)&&Af(e,t,i,r)}function Vc(e,t,n,r,i,a){let o=e.DynamicRef(i)??!1;return Po(o)&&Mf(e,t,`#`,r,o,a)}function Hc(e,t,n,r){return Co(n.enum.map(e=>Ue(e)?eo(r,K(e)):fo(r,Bs(e))))}function Uc(e,t,n,r){return n.enum.some(e=>Ue(e)?H(r,e):Ne(r,e))}function Wc(e,t,n,r,i,a){return Uc(e,t,i,a)||t.AddError({keyword:`enum`,schemaPath:n,instancePath:r,params:{allowedValues:i.enum}})}function Gc(e,t,n,r){return no(r,K(n.exclusiveMaximum))}function Kc(e,t,n,r){return yt(r,n.exclusiveMaximum)}function qc(e,t,n,r,i,a){return Kc(e,t,i,a)||t.AddError({keyword:`exclusiveMaximum`,schemaPath:n,instancePath:r,params:{comparison:`<`,limit:i.exclusiveMaximum}})}function Jc(e,t,n,r){return to(r,K(n.exclusiveMinimum))}function Yc(e,t,n,r){return Be(r,n.exclusiveMinimum)}function Xc(e,t,n,r,i,a){return Yc(e,t,i,a)||t.AddError({keyword:`exclusiveMinimum`,schemaPath:n,instancePath:r,params:{comparison:`>`,limit:i.exclusiveMinimum}})}const Zc=[0,31,28,31,30,31,30,31,31,30,31,30,31],Qc=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function $c(e){return e%4==0&&(e%100!=0||e%400==0)}function el(e){let t=Qc.exec(e);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r===2&&$c(n)?29:Zc[r])}const tl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function nl(e,t=!0){let n=tl.exec(e);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4]===`-`?-1:1,s=+(n[5]||0),c=+(n[6]||0);if(s>23||c>59||t&&!n[4]&&e.toLowerCase().indexOf(`z`)===-1)return!1;if(r<=23&&i<=59&&a<60)return!0;let l=i-c*o,u=r-s*o-+(l<0);return(u===23||u===-1)&&(l===59||l===-1)&&a<61}function rl(e,t=!0){let n=e.split(/T/i);return n.length===2&&el(n[0])&&nl(n[1],t)}const il=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function al(e){return il.test(e)}const ol=/^(?!.*\.\.)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i;function sl(e){return ol.test(e)}function cl(e,t,n){e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t);let r=0;for(;e>455;)e=Math.floor(e/35),r+=36;return r+Math.floor(36*e/(e+38))}function ll(e){let t=[],n=128,r=0,i=72,a=e.lastIndexOf(`-`);if(a>0)for(let n=0;n<a;n++){let r=e.charCodeAt(n);if(r>=128)throw Error(`Invalid punycode: non-basic before delimiter`);t.push(r)}let o=a<0?0:a+1;for(;o<e.length;){let a=r,s=1,c=36;for(;;){if(o>=e.length)throw Error(`Invalid punycode: unexpected end of input`);let t=e.charCodeAt(o++),n;if(t>=97&&t<=122)n=t-97;else if(t>=48&&t<=57)n=t-48+26;else if(t>=65&&t<=90)n=t-65;else throw Error(`Invalid punycode: bad digit character`);r+=n*s;let a=c<=i?1:c>=i+26?26:c-i;if(n<a)break;s*=36-a,c+=36}let l=t.length+1;i=cl(r-a,l,a===0),n+=Math.floor(r/l),r%=l,t.splice(r,0,n),r++}return globalThis.String.fromCodePoint(...t)}function ul(e){return/\p{Mn}/u.test(String.fromCodePoint(e))}function dl(e){return/\p{Mc}/u.test(String.fromCodePoint(e))}function fl(e){return/\p{Me}/u.test(String.fromCodePoint(e))}function pl(e){return ul(e)||dl(e)||fl(e)}const ml=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),hl=new Set([2381,2509,2637,2765,2893,3021,3149,3277,3387,3388,3405,3530,6980,7082,7083,43456,69702,69759,69817,69939,69940,70080,70197,70477,70722,70850,71103,71231,71350,72767,73028,73029]);function gl(e){return/\p{Script=Greek}/u.test(String.fromCodePoint(e))}function _l(e){return/\p{Script=Hebrew}/u.test(String.fromCodePoint(e))}function vl(e){return/\p{Script=Hiragana}/u.test(String.fromCodePoint(e))}function yl(e){return/\p{Script=Katakana}/u.test(String.fromCodePoint(e))}function bl(e){return/\p{Script=Han}/u.test(String.fromCodePoint(e))}function xl(e){return e>=1632&&e<=1641}function Sl(e){return e>=1776&&e<=1785}function Cl(e){return hl.has(e)}function wl(e){if(e.length===0)return!1;let t=[...e].map(e=>e.codePointAt(0)),n=t.length;if(t[0]===45||t[n-1]===45||n>=4&&t[2]===45&&t[3]===45||pl(t[0]))return!1;let r=!1,i=!1,a=!1;for(let e=0;e<n;e++){let n=t[e];if(ml.has(n))return!1;(vl(n)||yl(n)||bl(n))&&(r=!0),xl(n)&&(i=!0),Sl(n)&&(a=!0);let o=t[e-1],s=t[e+1];switch(n){case 183:if(o!==108||s!==108)return!1;break;case 885:if(s===void 0||!gl(s))return!1;break;case 1523:case 1524:if(o===void 0||!_l(o))return!1;break;case 8205:if(o===void 0||!Cl(o))return!1;break;case 12539:break}}return!(e.includes(`・`)&&!r||i&&a)}function Tl(e){if(e.charCodeAt(0)===45||e.charCodeAt(e.length-1)===45||e.length>=4&&e.charCodeAt(2)===45&&e.charCodeAt(3)===45)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(!(n>=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||n===45))return!1}return!0}function El(e){return e.toLowerCase().startsWith(`xn--`)}function Dl(e){try{return wl(ll(e.slice(4)))}catch{return!1}}function Ol(e){return e.length===0||e.length>63?!1:El(e)?Dl(e):wl(e)}function kl(e){return e.length===0||e.length>63?!1:El(e)?Dl(e):Tl(e)}function Al(e){if(e.length===0||e.length>253||e.charCodeAt(e.length-1)===46)return!1;for(let t of e.split(`.`))if(!kl(t))return!1;return!0}const jl=/^(?!.*\.\.)[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+(?:\.[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+)*@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?)*$/iu;function Ml(e){return jl.test(e)}function Nl(e){if(e.length===0||e.includes(` `))return!1;let t=e.normalize(`NFC`).replace(/[\u002E\u3002\uFF0E\uFF61]/g,`.`);if(t.length>253)return!1;for(let e of t.split(`.`))if(!Ol(e))return!1;return!0}function Pl(e,t,n){let r=0,i=0,a=0,o=0;for(let s=t;s<n;s++){let t=e.charCodeAt(s);if(t===46){if(a===0||i>255||o===48&&a>1)return!1;r++,i=0,a=0,o=0}else if(t>=48&&t<=57)a===0&&(o=t),i=i*10+(t-48),a++;else return!1}return r===3&&a>0&&i<=255&&!(o===48&&a>1)}function Fl(e){return Pl(e,0,e.length)}function Il(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Ll(e){let t=e.length;if(t===0)return!1;let n=0,r=!1,i=0;if(e.charCodeAt(0)===58&&e.charCodeAt(1)===58){if(t===2)return!0;r=!0,i=2}for(;i<t;){let a=0,o=i;for(;i<t&&Il(e.charCodeAt(i));)i++,a++;if(a===0)return!1;let s=e.charCodeAt(i);if(s===46){if(!Pl(e,o,t))return!1;n+=2,i=t;break}if(a>4)return!1;if(n++,i===t)break;if(s!==58)return!1;if(i++,e.charCodeAt(i)===58){if(r||e.charCodeAt(i+1)===58)return!1;if(r=!0,i++,i===t)break}}return r?n<=7:n===8}function Rl(e){try{return new URL(e,`http://example.com`),!0}catch{return!1}}function zl(e){if(e.includes(` `)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e)||/%(?![0-9a-fA-F]{2})/.test(e))return!1;if(e===``)return!0;let t=e.indexOf(`:`);return t>0&&/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(e.substring(0,t))?Rl(e):e.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&t===-1?!1:Rl(e)}function Bl(e){try{return new URL(e),!0}catch{return!1}}const Vl=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Hl(e){return Vl.test(e)}const Ul=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Wl(e){return Ul.test(e)}function Gl(e){if(e.length===0)return!1;try{return new RegExp(e),!0}catch{return!1}}const Kl=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function ql(e){return Kl.test(e)}const Jl=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function Yl(e){return Jl.test(e)}const Xl=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;function Zl(e){return Xl.test(e)}function Ql(e){return e>=97&&e<=122||e>=65&&e<=90}function $l(e){return Ql(e)||e>=48&&e<=57}function eu(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function tu(e){return $l(e)||e===43||e===45||e===46}function nu(e){return $l(e)||e===45||e===46||e===95||e===126}function ru(e){return e===33||e===36||e===38||e===39||e===40||e===41||e===42||e===43||e===44||e===59||e===61}function iu(e){return nu(e)||ru(e)||e===58||e===64}function au(e){let t=e.length;if(t===0||!Ql(e.charCodeAt(0)))return!1;let n=1;for(;n<t;){let t=e.charCodeAt(n);if(t===58)break;if(!tu(t))return!1;n++}if(e.charCodeAt(n)!==58)return!1;if(n++,e.charCodeAt(n)===47&&e.charCodeAt(n+1)===47){n+=2;let r=n,i=-1;for(let r=n;r<t;r++){let t=e.charCodeAt(r);if(t===64){i=r;break}if(t===47||t===63||t===35)break}if(i!==-1){for(let t=r;t<i;t++){let n=e.charCodeAt(t);if(n===91||n===93)return!1;if(n===37){if(t+2>=i||!eu(e.charCodeAt(t+1))||!eu(e.charCodeAt(t+2)))return!1;t+=2}else if(!nu(n)&&!ru(n)&&n!==58)return!1}n=i+1}if(e.charCodeAt(n)===91){for(n++;n<t&&e.charCodeAt(n)!==93;)n++;if(e.charCodeAt(n)!==93)return!1;n++}else for(;n<t;){let t=e.charCodeAt(n);if(t===47||t===63||t===35||t===58)break;if(t<128&&!nu(t)&&!ru(t))return!1;n++}if(e.charCodeAt(n)===58)for(n++;n<t;){let t=e.charCodeAt(n);if(t===47||t===63||t===35)break;if(t<48||t>57)return!1;n++}}for(;n<t;){let r=e.charCodeAt(n);if(r===37){if(n+2>=t||!eu(e.charCodeAt(n+1))||!eu(e.charCodeAt(n+2)))return!1;n+=2}else if(r>127)return!1;else if(!(iu(r)||r===47||r===63||r===35))return!1;n++}return!0}const ou=/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;function su(e){return ou.test(e)}const cu=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function lu(e){return cu.test(e)}const uu=new Map;function du(){uu.clear()}function fu(){return[...uu.entries()]}function pu(e,t){uu.set(e,t)}function mu(e){return uu.has(e)}function hu(e){return uu.get(e)}function gu(e,t){return uu.get(e)?.(t)??!0}function _u(){du(),uu.set(`date-time`,rl),uu.set(`date`,el),uu.set(`duration`,al),uu.set(`email`,sl),uu.set(`hostname`,Al),uu.set(`idn-email`,Ml),uu.set(`idn-hostname`,Nl),uu.set(`ipv4`,Fl),uu.set(`ipv6`,Ll),uu.set(`iri-reference`,zl),uu.set(`iri`,Bl),uu.set(`json-pointer-uri-fragment`,Hl),uu.set(`json-pointer`,Wl),uu.set(`regex`,Gl),uu.set(`relative-json-pointer`,ql),uu.set(`time`,nl),uu.set(`uri-reference`,Yl),uu.set(`uri-template`,Zl),uu.set(`uri`,au),uu.set(`url`,su),uu.set(`uuid`,lu)}_u();var vu=t({Clear:()=>du,Entries:()=>fu,Get:()=>hu,Has:()=>mu,IsDate:()=>el,IsDateTime:()=>rl,IsDuration:()=>al,IsEmail:()=>sl,IsHostname:()=>Al,IsIPv4:()=>Fl,IsIPv6:()=>Ll,IsIdnEmail:()=>Ml,IsIdnHostname:()=>Nl,IsIri:()=>Bl,IsIriReference:()=>zl,IsJsonPointer:()=>Wl,IsJsonPointerUriFragment:()=>Hl,IsRegex:()=>Gl,IsRelativeJsonPointer:()=>ql,IsTime:()=>nl,IsUri:()=>au,IsUriReference:()=>Yl,IsUriTemplate:()=>Zl,IsUrl:()=>su,IsUuid:()=>lu,Reset:()=>_u,Set:()=>pu,Test:()=>gu});function yu(e,t,n,r){return ho(G(`Format`,`Test`),[K(n.format),r])}function bu(e,t,n,r){return gu(n.format,r)}function xu(e,t,n,r,i,a){return bu(e,t,i,a)||t.AddError({keyword:`format`,schemaPath:n,instancePath:r,params:{format:i.format}})}function Su(e,t,n,r){let i=!Es(n)||n.then,a=!Jo(n)||n.else;return _o(Of(e,t,n.if,r),Of(e,t,i,r),Of(e,t,a,r))}function Cu(e,t,n,r){let i=!Es(n)||n.then,a=!Jo(n)||n.else;return Af(e,t,n.if,r)?Af(e,t,i,r):Af(e,t,a,r)}function wu(e,t,n,r,i,a){let o=!Es(i)||i.then,s=!Jo(i)||i.else,c=new Rs,l=Mf(e,c,`${n}/if`,r,i.if,a)?Mf(e,c,`${n}/then`,r,o,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`then`}}):Mf(e,t,`${n}/else`,r,s,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`else`}});return l&&t.Merge([c]),l}function Tu(e,t,n,r){return So(n.items.map((n,i)=>{let a=ro(G(r,`length`),K(i)),o=Df(e,t,n,`${r}[${i}]`),s=t.AddIndex(K(i));return La(a,t.UseUnevaluated()?Ia(o,s):o)}))}function Eu(e,t,n,r){return Ze(n.items,0,(n,i)=>ft(r.length,i)||kf(e,t,n,r[i])&&t.AddIndex(i))}function Du(e,t,n,r,i,a){return at(i.items,0,(i,o)=>{let s=`${n}/items/${o}`,c=`${r}/${o}`;return ft(a.length,o)||jf(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Ou(e,t,n,r){let i=vs(n)?n.prefixItems.length:0,a=Df(e,t,n.items,`element`),o=t.AddIndex(`index`),s=t.UseUnevaluated()?Ia(a,o):a;return so(r,K(i),[`element`,`index`],s)}function ku(e,t,n,r){return Ze(r,vs(n)?n.prefixItems.length:0,(r,i)=>kf(e,t,n.items,r)&&t.AddIndex(i))}function Au(e,t,n,r,i,a){return at(a,vs(i)?i.prefixItems.length:0,(a,o)=>jf(e,t,`${n}/items`,`${r}/${o}`,i.items,a)&&t.AddIndex(o))}function ju(e,t,n,r){return ns(n)?Tu(e,t,n,r):Ou(e,t,n,r)}function Mu(e,t,n,r){return ns(n)?Eu(e,t,n,r):ku(e,t,n,r)}function Nu(e,t,n,r,i,a){return ns(i)?Du(e,t,n,r,i,a):Au(e,t,n,r,i,a)}function Pu(e){return Vo(e)}function Fu(e,t,n,r){if(!Pu(n))return K(!0);let[i,a]=[Xs(),Xs()];return ro(ho(G(r,`reduce`),[mo([i,a],_o(Of(e,t,n.contains,a),wo(i),i)),K(0)]),K(n.maxContains))}function Iu(e,t,n,r){return!Pu(n)||ft(r.reduce((r,i)=>Af(e,t,n.contains,i)?++r:r,0),n.maxContains)}function Lu(e,t,n,r,i,a){let o=ls(i)?i.minContains:1;return Iu(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:o,maxContains:i.maxContains}})}function Ru(e,t,n,r){return ro(r,K(n.maximum))}function zu(e,t,n,r){return ft(r,n.maximum)}function Bu(e,t,n,r,i,a){return zu(e,t,i,a)||t.AddError({keyword:`maximum`,schemaPath:n,instancePath:r,params:{comparison:`<=`,limit:i.maximum}})}function Vu(e,t,n,r){return ro(G(r,`length`),K(n.maxItems))}function Hu(e,t,n,r){return ft(r.length,n.maxItems)}function Uu(e,t,n,r,i,a){return Hu(e,t,i,a)||t.AddError({keyword:`maxItems`,schemaPath:n,instancePath:r,params:{limit:i.maxItems}})}function Wu(e,t,n,r){return oo(r,K(n.maxLength))}function Gu(e,t,n,r){return ke(r,n.maxLength)}function Ku(e,t,n,r,i,a){return Gu(e,t,i,a)||t.AddError({keyword:`maxLength`,schemaPath:n,instancePath:r,params:{limit:i.maxLength}})}function qu(e,t,n,r){return ro(G(lo(r),`length`),K(n.maxProperties))}function Ju(e,t,n,r){return ft(M(r).length,n.maxProperties)}function Yu(e,t,n,r,i,a){return Ju(e,t,i,a)||t.AddError({keyword:`maxProperties`,schemaPath:n,instancePath:r,params:{limit:i.maxProperties}})}function Xu(e){return Vo(e)}function Zu(e,t,n,r){if(!Xu(n))return K(!0);let[i,a]=[Xs(),Xs()];return io(ho(G(r,`reduce`),[mo([i,a],_o(Of(e,t,n.contains,a),wo(i),i)),K(0)]),K(n.minContains))}function Qu(e,t,n,r){return!Xu(n)||Ye(r.reduce((r,i)=>Af(e,t,n.contains,i)?++r:r,0),n.minContains)}function $u(e,t,n,r,i,a){return Qu(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:i.minContains}})}function ed(e,t,n,r){return io(r,K(n.minimum))}function td(e,t,n,r){return Ye(r,n.minimum)}function nd(e,t,n,r,i,a){return td(e,t,i,a)||t.AddError({keyword:`minimum`,schemaPath:n,instancePath:r,params:{comparison:`>=`,limit:i.minimum}})}function rd(e,t,n,r){return io(G(r,`length`),K(n.minItems))}function id(e,t,n,r){return Ye(r.length,n.minItems)}function ad(e,t,n,r,i,a){return id(e,t,i,a)||t.AddError({keyword:`minItems`,schemaPath:n,instancePath:r,params:{limit:i.minItems}})}function od(e,t,n,r){return ao(r,K(n.minLength))}function sd(e,t,n,r){return _t(r,n.minLength)}function cd(e,t,n,r,i,a){return sd(e,t,i,a)||t.AddError({keyword:`minLength`,schemaPath:n,instancePath:r,params:{limit:i.minLength}})}function ld(e,t,n,r){return io(G(lo(r),`length`),K(n.minProperties))}function ud(e,t,n,r){return Ye(M(r).length,n.minProperties)}function dd(e,t,n,r,i,a){return ud(e,t,i,a)||t.AddError({keyword:`minProperties`,schemaPath:n,instancePath:r,params:{limit:i.minProperties}})}function fd(e,t,n,r){return To(r,K(n.multipleOf))}function pd(e,t,n,r){return ye(r,n.multipleOf)}function md(e,t,n,r,i,a){return pd(e,t,i,a)||t.AddError({keyword:`multipleOf`,schemaPath:n,instancePath:r,params:{multipleOf:i.multipleOf}})}function hd(e,t,n,r){return lc(e,t,[n.not],r,Ra(eo(G(`results`,`length`),K(1))))}function gd(e,t,n,r){return Ra(Of(e,t,n.not,r))}function _d(e,t,n,r){return t.UseUnevaluated()?hd(e,t,n,r):gd(e,t,n,r)}function vd(e,t,n,r){let i=new Is;return!Af(e,i,n.not,r)&&t.Merge([i])}function yd(e,t,n,r,i,a){return vd(e,t,i,a)||t.AddError({keyword:`not`,schemaPath:n,instancePath:r,params:{}})}function bd(e,t,n,r){return lc(e,t,n.oneOf,r,eo(G(`results`,`length`),K(1)))}function xd(e,t,n,r){return eo(ho(G(po(n.oneOf.map(n=>Of(e,t,n,r))),`reduce`),[mo([`count`,`result`],_o(eo(`result`,K(!0)),wo(`count`),`count`)),K(0)]),K(1))}function Sd(e,t,n,r){return t.UseUnevaluated()?bd(e,t,n,r):xd(e,t,n,r)}function Cd(e,t,n,r){let i=n.oneOf.reduce((t,n)=>{let i=new Is;return Af(e,i,n,r)?[...t,i]:t},[]);return H(i.length,1)&&t.Merge(i)}function wd(e,t,n,r,i,a){let o=[],s=[],c=i.oneOf.reduce((t,i,c)=>{let l=new Rs,u=Mf(e,l,`${n}/oneOf/${c}`,r,i,a);return u&&s.push(c),u||o.push(l),u?[...t,l]:t},[]),l=H(c.length,1)&&t.Merge(c);return!l&&H(s.length,0)&&o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),l||t.AddError({keyword:`oneOf`,schemaPath:n,instancePath:r,params:{passingSchemas:s}})}function Td(e,t,n,r){return ho(G(Bs(T(n.pattern)?new RegExp(n.pattern,`u`):n.pattern),`test`),[r])}function Ed(e,t,n,r){return(T(n.pattern)?new RegExp(n.pattern,`u`):n.pattern).test(r)}function Dd(e,t,n,r,i,a){return Ed(e,t,i,a)||t.AddError({keyword:`pattern`,schemaPath:n,instancePath:r,params:{pattern:i.pattern}})}function Od(e,t,n,r){return So(Fe(n.patternProperties).map(([n,i])=>{let[a,o]=[Xs(),Xs()],s=Ra(ho(G(Bs(new RegExp(n,`u`)),`test`),[a])),c=Df(e,t,i,o),l=t.AddKey(a),u=t.UseUnevaluated()?La(s,Ia(c,l)):La(s,c);return so(co(r),K(0),[`[${a}, ${o}]`,`_`],u)}))}function kd(e,t,n,r){return Ze(Fe(n.patternProperties),0,([n,i])=>{let a=new RegExp(n,`u`);return Ze(Fe(r),0,([n,r])=>!a.test(n)||kf(e,t,i,r)&&t.AddKey(n))})}function Ad(e,t,n,r,i,a){return at(Fe(i.patternProperties),0,([i,o])=>{let s=`${n}/patternProperties/${i}`,c=new RegExp(i,`u`);return at(Fe(a),0,([n,i])=>{let a=`${r}/${n}`;return!c.test(n)||jf(e,t,s,a,o,i)&&t.AddKey(n)})})}function jd(e,t,n,r){return So(n.prefixItems.map((n,i)=>{let a=ro(G(r,`length`),K(i)),o=Df(e,t,n,`${r}[${i}]`),s=t.AddIndex(K(i));return La(a,t.UseUnevaluated()?Ia(o,s):o)}))}function Md(e,t,n,r){return H(r.length,0)||Ze(n.prefixItems,0,(n,i)=>ft(r.length,i)||kf(e,t,n,r[i])&&t.AddIndex(i))}function Nd(e,t,n,r,i,a){return H(a.length,0)||at(i.prefixItems,0,(i,o)=>{let s=`${n}/prefixItems/${o}`,c=`${r}/${o}`;return ft(a.length,o)||jf(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Pd(e,t){return e.includes(t)||z().exactOptionalPropertyTypes}function Fd(e,t){return Za(G(e,t))}function Id(e,t){return Ge(e[t])}function Ld(e,t,n,r){let i=Ts(n)?n.required:[];return So(Fe(n.properties).map(([n,a])=>{let o=Ra(uo(r,K(n))),s=Df(e,t,a,G(r,n)),c=t.AddKey(K(n)),l=t.UseUnevaluated()?Ia(s,c):s,u=i.includes(n)?l:La(o,l);return Pd(i,n)?u:La(Fd(r,n),u)}))}function Rd(e,t,n,r){let i=Ts(n)?n.required:[];return Ze(Fe(n.properties),0,([n,a])=>{let o=!U(r,n)||kf(e,t,a,r[n])&&t.AddKey(n);return Pd(i,n)?o:Id(r,n)||o})}function zd(e,t,n,r,i,a){let o=Ts(i)?i.required:[];return at(Fe(i.properties),0,([i,s])=>{let c=`${n}/properties/${i}`,l=`${r}/${i}`,u=()=>!U(a,i)||jf(e,t,c,l,s,a[i])&&t.AddKey(i);return Pd(o,i)?u():Id(a,i)||u()})}function Bd(e,t,n,r){let[i,a]=[Xs(),Xs()];return so(lo(r),K(0),[i,a],Of(e,t,n.propertyNames,i))}function Vd(e,t,n,r){return Ze(M(r),0,(r,i)=>Af(e,t,n.propertyNames,r))}function Hd(e,t,n,r,i,a){let o=[];return at(M(a),0,(t,a)=>{let s=`${r}/${t}`,c=`${n}/propertyNames`,l=Mf(e,new Rs,c,s,i.propertyNames,t);return l||o.push(t),l})||t.AddError({keyword:`propertyNames`,schemaPath:n,instancePath:r,params:{propertyNames:o}})}function Ud(e,t,n,r){return Rf(e,t,e.RecursiveRef(n)??!1,r)}function Wd(e,t,n,r){let i=e.RecursiveRef(n)??!1;return Po(i)&&Af(e,t,i,r)}function Gd(e,t,n,r,i,a){let o=e.RecursiveRef(i)??!1;return Po(o)&&Mf(e,t,`#`,r,o,a)}function Kd(e,t,n,r){let i=mo([`context`,`value`],Rf(e,t,n,`value`));return ho(mo([`context`,`value`],vo([yo(`nextContext`,go(`CheckContext`,[])),yo(`result`,ho(i,[`nextContext`,`value`])),bo(`result`,t.Merge(`[nextContext]`)),xo(`result`)])),[`context`,r])}function qd(e,t,n,r){return Rf(e,t,n,r)}function Jd(e,t,n,r){let i=e.Ref(n)??!1;return t.UseUnevaluated()?Kd(e,t,i,r):qd(e,t,i,r)}function Yd(e,t,n,r){let i=e.Ref(n)??!1,a=new Is,o=Po(i)&&Af(e,a,i,r);return o&&t.Merge([a]),o}function Xd(e,t,n,r,i,a){let o=e.Ref(i)??!1,s=new Rs,c=Po(o)&&Mf(e,s,`#`,r,o,a);return c&&t.Merge([s]),c||s.GetErrors().forEach(e=>t.AddError(e)),c}function Zd(e,t,n,r){return So(n.required.map(e=>uo(r,K(e))))}function Qd(e,t,n,r){return Ze(n.required,0,e=>U(r,e))}function $d(e,t,n,r,i,a){let o=[];return at(i.required,0,e=>{let t=U(a,e);return t||o.push(e),t})||t.AddError({keyword:`required`,schemaPath:n,instancePath:r,params:{requiredProperties:o}})}function ef(e,t,n,r){return H(n,`object`)?qa(r):H(n,`array`)?za(r):H(n,`boolean`)?Ha(r):H(n,`integer`)?Ua(r):H(n,`number`)?Ka(r):H(n,`null`)?Ga(r):H(n,`string`)?Ya(r):H(n,`asyncIterator`)?Ba(r):H(n,`bigint`)?Va(r):H(n,`constructor`)?$a(r):H(n,`function`)?Qa(r):H(n,`iterator`)?Wa(r):H(n,`symbol`)?Xa(r):H(n,`undefined`)||H(n,`void`)?Za(r):K(!0)}function tf(e,t,n,r,i){return H(n,`object`)?O(i):H(n,`array`)?V(i):H(n,`boolean`)?je(i):H(n,`integer`)?Re(i):H(n,`number`)?ht(i):H(n,`null`)?S(i):H(n,`string`)?T(i):H(n,`asyncIterator`)?$e(i):H(n,`bigint`)?st(i):H(n,`constructor`)?ut(i):H(n,`function`)?tt(i):H(n,`iterator`)?B(i):H(n,`symbol`)?fe(i):H(n,`undefined`)?Ge(i):!H(n,`void`)||Ge(i)}function nf(e,t,n,r){return Co(n.map(n=>ef(e,t,n,r)))}function rf(e,t,n,r,i){return n.some(n=>tf(e,t,n,r,i))}function af(e,t,n,r){return V(n.type)?nf(e,t,n.type,r):ef(e,t,n.type,r)}function of(e,t,n,r){return V(n.type)?rf(e,t,n.type,n,r):tf(e,t,n.type,n,r)}function sf(e,t,n,r,i,a){return(V(i.type)?rf(e,t,i.type,i,a):tf(e,t,i.type,i,a))||t.AddError({keyword:`type`,schemaPath:n,instancePath:r,params:{type:i.type}})}function cf(e,t,n,r){let[i,a]=[Xs(),Xs()],o=ho(G(`context`,`GetIndices`),[]),s=ho(G(`indices`,`has`),[i]),c=Of(e,t,n.unevaluatedItems,a),l=ho(G(`context`,`AddIndex`),[i]),u=so(r,K(0),[a,i],Ia(La(s,c),l));return ho(mo([`context`],vo([yo(`indices`,o),xo(u)])),[`context`])}function lf(e,t,n,r){let i=t.GetIndices();return Ze(r,0,(r,a)=>(i.has(a)||Af(e,t,n.unevaluatedItems,r))&&t.AddIndex(a))}function uf(e,t,n,r,i,a){let o=t.GetIndices(),s=[];return at(a,0,(a,c)=>{let l=new Rs,u=(o.has(c)||Mf(e,l,n,r,i.unevaluatedItems,a))&&t.AddIndex(c);return u||s.push(c),u})||t.AddError({keyword:`unevaluatedItems`,schemaPath:n,instancePath:r,params:{unevaluatedItems:s}})}function df(e,t,n,r){let[i,a]=[Xs(),Xs()],o=ho(G(`context`,`GetKeys`),[]),s=ho(G(`keys`,`has`),[i]),c=ho(G(`context`,`AddKey`),[i]),l=Of(e,t,n.unevaluatedProperties,a),u=so(co(r),K(0),[`[${i}, ${a}]`,`_`],La(s,Ia(l,c)));return ho(mo([`context`],vo([yo(`keys`,o),xo(u)])),[`context`])}function ff(e,t,n,r){let i=t.GetKeys();return Ze(Fe(r),0,([r,a])=>i.has(r)||Af(e,t,n.unevaluatedProperties,a)&&t.AddKey(r))}function pf(e,t,n,r,i,a){let o=t.GetKeys(),s=[];return at(Fe(a),0,([a,c])=>{let l=new Rs,u=o.has(a)||Mf(e,l,n,r,i.unevaluatedProperties,c)&&t.AddKey(a);return u||s.push(a),u})||t.AddError({keyword:`unevaluatedProperties`,schemaPath:n,instancePath:r,params:{unevaluatedProperties:s}})}function mf(e){return!H(e.uniqueItems,!1)}function hf(e,t,n,r){return mf(n)?eo(G(go(`Set`,[ho(G(r,`map`),[G(`Hashing`,`Hash`)])]),`size`),G(r,`length`)):K(!0)}function gf(e,t,n,r){if(!mf(n))return!0;let i=new Set(r.map(E)).size,a=r.length;return H(i,a)}function _f(e,t,n,r,i,a){if(!mf(i))return!0;let o=new Set,s=a.reduce((e,t,n)=>{let r=E(t);return o.has(r)?[...e,n]:(o.add(r),e)},[]);return H(s.length,0)||t.AddError({keyword:`uniqueItems`,schemaPath:n,instancePath:r,params:{duplicateItems:s}})}function vf(e,t){return Ds(e)&&(V(e.type)&&e.type.includes(t)||H(e.type,t))}function yf(e){return vf(e,`object`)}function bf(e){return Mo(e)&&(Io(e)||Uo(e)||Wo(e)||Go(e)||ys(e)||_s(e)||bs(e)||fs(e)||ss(e)||Ts(e)||As(e))}function xf(e){return vf(e,`array`)}function Sf(e){return Mo(e)&&(Fo(e)||ts(e)||Vo(e)||is(e)||as(e)||ls(e)||us(e)||vs(e)||ks(e)||Os(e))}function Cf(e){return vf(e,`string`)}function wf(e){return Mo(e)&&(ds(e)||os(e)||Qo(e)||gs(e))}function Tf(e){return vf(e,`number`)||vf(e,`bigint`)}function Ef(e){return Mo(e)&&(cs(e)||rs(e)||Xo(e)||Zo(e)||ps(e))}function Df(e,t,n,r){return t.UseUnevaluated()?Ia(Ia(t.Push(),Of(e,t,n,r)),t.Pop()):Of(e,t,n,r)}function Of(e,t,n,r){e.Push(n);let i=[];if(No(n))return bc(e,t,n,r);if(Ds(n)&&i.push(af(e,t,n,r)),bf(n)){let a=[];Ts(n)&&a.push(Zd(e,t,n,r)),Io(n)&&a.push(oc(e,t,n,r)),Uo(n)&&a.push(Ac(e,t,n,r)),Wo(n)&&a.push(Nc(e,t,n,r)),Go(n)&&a.push(Ic(e,t,n,r)),_s(n)&&a.push(Od(e,t,n,r)),ys(n)&&a.push(Ld(e,t,n,r)),bs(n)&&a.push(Bd(e,t,n,r)),fs(n)&&a.push(ld(e,t,n,r)),ss(n)&&a.push(qu(e,t,n,r));let o=So(a),s=La(Ra(qa(r)),o);i.push(yf(n)?o:s)}if(Sf(n)){let a=[];Fo(n)&&a.push(Qs(e,t,n,r)),Vo(n)&&a.push(Dc(e,t,n,r)),ts(n)&&a.push(ju(e,t,n,r)),is(n)&&a.push(Fu(e,t,n,r)),as(n)&&a.push(Vu(e,t,n,r)),ls(n)&&a.push(Zu(e,t,n,r)),us(n)&&a.push(rd(e,t,n,r)),vs(n)&&a.push(jd(e,t,n,r)),Os(n)&&a.push(hf(e,t,n,r));let o=So(a),s=La(Ra(za(r)),o);i.push(xf(n)?o:s)}if(wf(n)){let a=[];os(n)&&a.push(Wu(e,t,n,r)),ds(n)&&a.push(od(e,t,n,r)),Qo(n)&&a.push(yu(e,t,n,r)),gs(n)&&a.push(Td(e,t,n,r));let o=So(a),s=La(Ra(Ya(r)),o);i.push(Cf(n)?o:s)}if(Ef(n)){let a=[];Xo(n)&&a.push(Gc(e,t,n,r)),Zo(n)&&a.push(Jc(e,t,n,r)),rs(n)&&a.push(Ru(e,t,n,r)),cs(n)&&a.push(ed(e,t,n,r)),ps(n)&&a.push(fd(e,t,n,r));let o=So(a),s=La(Ra(La(Ka(r),Va(r))),o);i.push(Tf(n)?o:s)}ws(n)&&i.push(Jd(e,t,n,r)),Cs(n)&&i.push(Ud(e,t,n,r)),qo(n)&&i.push(zc(e,t,n,r)),Ao(n)&&i.push(Us(e,t,n,r)),Bo(n)&&i.push(Cc(e,t,n,r)),Yo(n)&&i.push(Hc(e,t,n,r)),es(n)&&i.push(Su(e,t,n,r)),ms(n)&&i.push(_d(e,t,n,r)),Lo(n)&&i.push(fc(e,t,n,r)),zo(n)&&i.push(_c(e,t,n,r)),hs(n)&&i.push(Sd(e,t,n,r)),ks(n)&&i.push(La(Ra(za(r)),cf(e,t,n,r))),As(n)&&i.push(La(Ra(Ja(r)),df(e,t,n,r))),jo(n)&&i.push(Ks(e,t,n,r));let a=So(i);return e.Pop(n),a}function kf(e,t,n,r){return t.Push()&&Af(e,t,n,r)&&t.Pop()}function Af(e,t,n,r){e.Push(n);let i=No(n)?xc(e,t,n,r):(!Ds(n)||of(e,t,n,r))&&(!(F(r)&&!V(r))||(!Ts(n)||Qd(e,t,n,r))&&(!Io(n)||sc(e,t,n,r))&&(!Uo(n)||jc(e,t,n,r))&&(!Wo(n)||Pc(e,t,n,r))&&(!Go(n)||Lc(e,t,n,r))&&(!_s(n)||kd(e,t,n,r))&&(!ys(n)||Rd(e,t,n,r))&&(!bs(n)||Vd(e,t,n,r))&&(!fs(n)||ud(e,t,n,r))&&(!ss(n)||Ju(e,t,n,r)))&&(!V(r)||(!Fo(n)||$s(e,t,n,r))&&(!Vo(n)||Oc(e,t,n,r))&&(!ts(n)||Mu(e,t,n,r))&&(!is(n)||Iu(e,t,n,r))&&(!as(n)||Hu(e,t,n,r))&&(!ls(n)||Qu(e,t,n,r))&&(!us(n)||id(e,t,n,r))&&(!vs(n)||Md(e,t,n,r))&&(!Os(n)||gf(e,t,n,r)))&&(!T(r)||(!os(n)||Gu(e,t,n,r))&&(!ds(n)||sd(e,t,n,r))&&(!Qo(n)||bu(e,t,n,r))&&(!gs(n)||Ed(e,t,n,r)))&&(!(ht(r)||st(r))||(!Xo(n)||Kc(e,t,n,r))&&(!Zo(n)||Yc(e,t,n,r))&&(!rs(n)||zu(e,t,n,r))&&(!cs(n)||td(e,t,n,r))&&(!ps(n)||pd(e,t,n,r)))&&(!ws(n)||Yd(e,t,n,r))&&(!Cs(n)||Wd(e,t,n,r))&&(!qo(n)||Bc(e,t,n,r))&&(!Ao(n)||Ws(e,t,n,r))&&(!Bo(n)||wc(e,t,n,r))&&(!Yo(n)||Uc(e,t,n,r))&&(!es(n)||Cu(e,t,n,r))&&(!ms(n)||vd(e,t,n,r))&&(!Lo(n)||pc(e,t,n,r))&&(!zo(n)||vc(e,t,n,r))&&(!hs(n)||Cd(e,t,n,r))&&(!ks(n)||!V(r)||lf(e,t,n,r))&&(!As(n)||!F(r)||ff(e,t,n,r))&&(!jo(n)||qs(e,t,n,r));return e.Pop(n),i}function jf(e,t,n,r,i,a){return t.Push()&&Mf(e,t,n,r,i,a)&&t.Pop()}function Mf(e,t,n,r,i,a){e.Push(i);let o=No(i)?Sc(e,t,n,r,i,a):!!((!Ds(i)||sf(e,t,n,r,i,a))&+(!(F(a)&&!V(a))||!!((!Ts(i)||$d(e,t,n,r,i,a))&+(!Io(i)||cc(e,t,n,r,i,a))&(!Uo(i)||Mc(e,t,n,r,i,a))&(!Wo(i)||Fc(e,t,n,r,i,a))&(!Go(i)||Rc(e,t,n,r,i,a))&(!_s(i)||Ad(e,t,n,r,i,a))&(!ys(i)||zd(e,t,n,r,i,a))&(!bs(i)||Hd(e,t,n,r,i,a))&(!fs(i)||dd(e,t,n,r,i,a))&(!ss(i)||Yu(e,t,n,r,i,a))))&(!V(a)||!!((!Fo(i)||ec(e,t,n,r,i,a))&+(!Vo(i)||kc(e,t,n,r,i,a))&(!ts(i)||Nu(e,t,n,r,i,a))&(!is(i)||Lu(e,t,n,r,i,a))&(!as(i)||Uu(e,t,n,r,i,a))&(!ls(i)||$u(e,t,n,r,i,a))&(!us(i)||ad(e,t,n,r,i,a))&(!vs(i)||Nd(e,t,n,r,i,a))&(!Os(i)||_f(e,t,n,r,i,a))))&(!T(a)||!!((!os(i)||Ku(e,t,n,r,i,a))&+(!ds(i)||cd(e,t,n,r,i,a))&(!Qo(i)||xu(e,t,n,r,i,a))&(!gs(i)||Dd(e,t,n,r,i,a))))&(!(ht(a)||st(a))||!!((!Xo(i)||qc(e,t,n,r,i,a))&+(!Zo(i)||Xc(e,t,n,r,i,a))&(!rs(i)||Bu(e,t,n,r,i,a))&(!cs(i)||nd(e,t,n,r,i,a))&(!ps(i)||md(e,t,n,r,i,a))))&(!ws(i)||Xd(e,t,n,r,i,a))&(!Cs(i)||Gd(e,t,n,r,i,a))&(!qo(i)||Vc(e,t,n,r,i,a))&(!Ao(i)||Gs(e,t,n,r,i,a))&(!Bo(i)||Tc(e,t,n,r,i,a))&(!Yo(i)||Wc(e,t,n,r,i,a))&(!es(i)||wu(e,t,n,r,i,a))&(!ms(i)||yd(e,t,n,r,i,a))&(!Lo(i)||mc(e,t,n,r,i,a))&(!zo(i)||yc(e,t,n,r,i,a))&(!hs(i)||wd(e,t,n,r,i,a))&(!ks(i)||!V(a)||uf(e,t,n,r,i,a))&(!As(i)||!F(a)||pf(e,t,n,r,i,a)))&&(!jo(i)||Js(e,t,n,r,i,a));return e.Pop(i),o}const Nf=new Map;function Pf(e,t,n,r){return e.UseUnevaluated()?ho(`check_${n}`,[`context`,r]):ho(`check_${n}`,[r])}function Ff(e,t,n,r){let i=Of(e,t,n,`value`);return t.UseUnevaluated()?yo(`check_${r}`,mo([`context`,`value`],i)):yo(`check_${r}`,mo([`value`],i))}function If(){Nf.clear()}function Lf(){return[...Nf.values()]}function Rf(e,t,n,r){let i=Mo(n)?E({__baseURL:e.BaseURL().href,...n}):E(n),a=Pf(t,n,i,r);return Nf.has(i)?a:(Nf.set(i,``),Nf.set(i,Ff(e,t,n,i)),a)}function zf(e,t){return F(t)&&!y(e)?t[e]:void 0}function Bf(e,t){return e.reduce((e,t)=>zf(t,e),t)}function Vf(e){if(H(e.length,0))return[];let t=e.split(`/`).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`));return t.length>0&&t[0]===``?t.slice(1):t}function Hf(e,t){return Bf(Vf(t),e)}function Uf(e,t,n){if(e.$id===n.hash)return e;let r=new URL(e.$id,t.href),i=new URL(n.href,t.href);if(H(r.pathname,i.pathname))return n.hash.startsWith(`#`)?Kf(e,t,n):e}function Wf(e,t,n){let r=new URL(`#${e.$anchor}`,t.href),i=new URL(n.href,t.href);return H(r.href,i.href)?e:void 0}function Gf(e,t,n){let r=new URL(`#${e.$dynamicAnchor}`,t.href),i=new URL(n.href,t.href);return H(r.href,i.href)?e:void 0}function Kf(e,t,n){if(n.href.endsWith(`#`))return e;if(!n.hash.startsWith(`#`))return;let r=decodeURIComponent(n.hash.slice(1));if(r.startsWith(`/`))return Hf(e,r)}function qf(e,t,n){if($o(e)){let r=Uf(e,t,n);if(!Ge(r))return r}if(Ro(e)){let r=Wf(e,t,n);if(!Ge(r))return r}if(Ko(e)){let r=Gf(e,t,n);if(!Ge(r))return r}return Kf(e,t,n)}function Jf(e,t,n){return e.reduce((e,r)=>{let i=Xf(r,t,n);return Ge(i)?e:i},void 0)}function Yf(e,t,n){return M(e).reduce((r,i)=>{let a=Xf(e[i],t,n);return Ge(a)?r:a},void 0)}function Xf(e,t,n){let r=Mo(e)&&$o(e)?new URL(e.$id,t.href):t;if(Mo(e)){let t=qf(e,r,n);if(!Ge(t))return t}if(V(e))return Jf(e,r,n);if(F(e))return Yf(e,r,n)}function Zf(e,t){let n=new URL(`http://unknown/`),r=$o(e)?new URL(e.$id,n.href):n;return Xf(e,r,new URL(t,r.href))}function Qf(e,t,n,r){let i=n.$dynamicRef.startsWith(`#`)?Zf(t,n.$dynamicRef):Zf(e,n.$dynamicRef);if(!Ge(i))return!Mo(i)||!Ko(i)||new URL(n.$dynamicRef,`http://unknown/`).hash.startsWith(`#/`)?i:r.find(e=>e.$dynamicAnchor===i.$dynamicAnchor)??i}var $f=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},ep,tp,np,rp,ip,ap=class{constructor(e,t){ep.add(this),this.context=e,this.schema=t,this.ids=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[]}BaseURL(){return this.ids.reduce((e,t)=>new URL(t.$id,e),new URL(`http://unknown`))}Base(){return this.ids[this.ids.length-1]??this.schema}Push(e){Mo(e)&&($o(e)&&(this.ids.push(e),$f(this,ep,`m`,tp).call(this,e)),Ro(e)&&this.anchors.push(e),Ss(e)&&this.recursiveAnchors.push(e),Ko(e)&&this.dynamicAnchors.push(e))}Pop(e){Mo(e)&&($o(e)&&(this.ids.pop(),$f(this,ep,`m`,np).call(this,e)),Ro(e)&&this.anchors.pop(),Ss(e)&&this.recursiveAnchors.pop(),Ko(e)&&this.dynamicAnchors.pop())}Ref(e){return $f(this,ep,`m`,rp).call(this,e)??$f(this,ep,`m`,ip).call(this,e)}RecursiveRef(e){return Ss(this.Base())?Zf(this.recursiveAnchors[0],e.$recursiveRef):Zf(this.Base(),e.$recursiveRef)}DynamicRef(e){let t=this.schema;return Qf(t,this.Base(),e,this.dynamicAnchors)}};ep=new WeakSet,tp=function e(t,n=!0){if(!Mo(t))return;let r=t;if(!(!n&&$o(r))){!n&&Ko(r)&&this.dynamicAnchors.push(r);for(let t of M(r))$f(this,ep,`m`,e).call(this,r[t],!1)}},np=function e(t,n=!0){if(!Mo(t))return;let r=t;if(!(!n&&$o(r))){!n&&Ko(r)&&this.dynamicAnchors.pop();for(let t of M(r))$f(this,ep,`m`,e).call(this,r[t],!1)}},rp=function(e){return U(this.context,e.$ref)?this.context[e.$ref]:void 0},ip=function(e){let t=this.schema;return e.$ref.startsWith(`#`)?Zf(this.Base(),e.$ref):Zf(t,e.$ref)};function op(e){return`${e.Functions().join(`;
884
884
  `)}; return (value) => { ${(e.UseUnevaluated()?[`const context = new CheckContext({}, {})`,`return ${e.Entry()}`]:[`return ${e.Entry()}`]).join(`; `)} }`}function sp(e,t){return ko(`CheckContext`,`Guard`,`Format`,`Hashing`,e.External().identifier,t)(Is,me,vu,pe,e.External().variables)}function cp(e){let t=new ap(e.Context(),e.Schema()),n=new Is;return r=>Af(t,n,e.Schema(),r)}function lp(e,t){return Oo()?sp(e,t):cp(e)}var up=class{constructor(e,t,n){this.isAccelerated=e,this.code=t,this.check=n}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}},dp=class{constructor(e,t,n,r,i,a){this.context=e,this.schema=t,this.external=n,this.functions=r,this.entry=i,this.useUnevaluated=a}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=op(this),t=lp(this,e);return new up(Oo(),e,t)}};function fp(...e){let[t,n]=Eo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});Vs(),If();let r=new ap(t,n),i=new Fs(Ps(t,n)),a=Rf(r,i,n,`value`),o=Lf();return new dp(t,n,Hs(),o,a,i.UseUnevaluated())}function pp(...e){let[t,n,r]=Eo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),i=z(),a=_ee(),o=[];return[Mf(new ap(t,n),new Ls(e=>{if(!Ye(o.length,i.maxErrors))return o.push({...e,message:a(e)})}),`#`,``,n,r),o]}function mp(...e){let[t,n,r]=Eo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Af(new ap(t,n),new Is,n,r)}function hp(...e){let[t,n,r]=Eo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return mp(t,n,r)}function gp(...e){let[t,n,r]=Eo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),[i,a]=pp(t,n,r);return a}var _p=class extends Error{constructor(e,t,n){super(e),Object.defineProperty(this,"cause",{value:{source:e,errors:n,value:t},writable:!1,configurable:!1,enumerable:!1})}};function vp(e,t,n){return V(n)?n.map(n=>zp(e,t.items,n)):n}function yp(e,t,n){return t.Clean(n)}function bp(e,t,n){return zp({...e,...t.$defs},x(t.$ref),n)}function xp(e,t){let n=U(t,`unevaluatedProperties`)?{additionalProperties:t.unevaluatedProperties}:{},r=ge(_(e,t));return ae(r)?Ie(r,n):r}function Sp(e,t,n){return zp(e,xp(e,t),n)}function Cp(e){return U(e,`additionalProperties`)?e.additionalProperties:void 0}function wp(e,t,n){if(!F(n)||V(n))return n;let r=Cp(t);for(let i of M(n)){if(U(t.properties,i)){n[i]=zp(e,t.properties[i],n[i]);continue}if(je(r)&&H(r,!0)||we(r)&&hp(e,r,n[i])){n[i]=zp(e,r,n[i]);continue}delete n[i]}return n}function Tp(e,t,n){if(!F(n))return n;let r=Cp(t),[i,a]=[new RegExp(et(t)),ct(t)];for(let t of M(n)){if(i.test(t)){n[t]=zp(e,a,n[t]);continue}if(je(r)&&H(r,!0)||we(r)&&hp(e,r,n[t])){n[t]=zp(e,r,n[t]);continue}delete n[t]}return n}function Ep(e,t,n){return U(e,t.$ref)?zp(e,e[t.$ref],n):n}function Dp(e,t,n){if(!V(n))return n;let r=Math.min(n.length,t.items.length);for(let i=0;i<r;i++)n[i]=zp(e,t.items[i],n[i]);return Be(n.length,r)?n.slice(0,r):n}function Op(e){return e}function kp(e){let t={};for(let n of M(e))y(n)||(t[n]=Ip(e[n]));for(let n of ue(e))t[n]=Ip(e[n]);return t}function Ap(e){return eee(e)?Op(e):kp(e)}function jp(e){return e.map(e=>Ip(e))}function Mp(e){return e.slice()}function Np(e){return new Map(Ip([...e.entries()]))}function Pp(e){return new Set(Ip([...e.values()]))}function Fp(e){return e}function Ip(e){return v(e)?Mp(e):Ee(e)?Np(e):_e(e)?Pp(e):V(e)?jp(e):F(e)?Ap(e):Fp(e)}function Lp(e,t){return JSON.stringify(e).localeCompare(JSON.stringify(t))}function Rp(e,t=1){return e.sort((e,n)=>{let r=tee(e,n);return(H(r,`disjoint`)?Lp(e,n):H(r,`right-inside`)?1:H(r,`left-inside`)?-1:Lp(e,n))*t})}function See(e,t,n){for(let r of Rp(t.anyOf)){let t=zp(e,r,Ip(n));if(hp(e,r,t))return t}return n}function zp(e,t,n){return Se(t)?vp(e,t,n):ce(t)?yp(e,t,n):N(t)?bp(e,t,n):b(t)?Sp(e,t,n):ae(t)?wp(e,t,n):Oe(t)?Tp(e,t,n):bt(t)?Ep(e,t,n):Me(t)?Dp(e,t,n):he(t)?See(e,t,n):n}function Bp(...e){let[t,n,r]=Eo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return zp(t,n,r)}function Vp(e){return F(e)&&U(e,`value`)}function q(e){return{value:e}}function Cee(e){return V(e)?q(e):q([e])}function wee(e){return H(e,!0)?q(BigInt(1)):q(BigInt(0))}const Tee=/^-?(0|[1-9]\d*)n$/,Eee=/^-?(0|[1-9]\d*)\.\d+$/,Dee=/^-?(0|[1-9]\d*)$/;function Oee(e){return Tee.test(e)}function kee(e){return Eee.test(e)}function Aee(e){return Dee.test(e)}function jee(e){let t=e.toLowerCase();return Oee(e)?q(BigInt(e.slice(0,e.length-1))):kee(e)?q(BigInt(e.split(`.`)[0])):Aee(e)?q(BigInt(e)):H(t,`false`)?q(BigInt(0)):H(t,`true`)?q(BigInt(1)):void 0}function Hp(e){return st(e)?q(e):je(e)?wee(e):ht(e)?q(BigInt(Math.trunc(e))):S(e)?q(BigInt(0)):T(e)?jee(e):Ge(e)?q(BigInt(0)):void 0}function Mee(e){return H(e,BigInt(0))?q(!1):H(e,BigInt(1))?q(!0):void 0}function Nee(e){return H(e,0)?q(!1):H(e,1)?q(!0):void 0}function Pee(e){return H(e.toLowerCase(),`false`)?q(!1):H(e.toLowerCase(),`true`)?q(!0):H(e,`0`)?q(!1):H(e,`1`)?q(!0):void 0}function Up(e){return st(e)?Mee(e):je(e)?q(e):ht(e)?Nee(e):S(e)?q(!1):T(e)?Pee(e):Ge(e)?q(!1):void 0}function Fee(e){return H(e,BigInt(0))?q(null):void 0}function Iee(e){return H(e,!1)?q(null):void 0}function Lee(e){return H(e,0)?q(null):void 0}function Ree(e){let t=e.toLowerCase();return H(t,`undefined`)||H(t,`null`)||H(e,``)||H(e,`0`)?q(null):void 0}function zee(e){return st(e)?Fee(e):je(e)?Iee(e):ht(e)?Lee(e):S(e)?q(null):T(e)?Ree(e):Ge(e)?q(null):void 0}const Wp=BigInt(2**53-1),Gp=BigInt(-(2**53-1));function Bee(e){return e<=Wp&&e>=Gp?q(Number(e)):void 0}function Vee(e){return q(+!!e)}function Hee(e){let t=+e;if(ht(t))return q(t);let n=e.toLowerCase();if(H(n,`false`))return q(0);if(H(n,`true`))return q(1);let r=Hp(e);if(Vp(r))return r.value<=Wp&&r.value>=Gp?q(Number(r.value)):void 0}function Kp(e){return st(e)?Bee(e):je(e)?Vee(e):ht(e)?q(e):S(e)?q(0):T(e)?Hee(e):Ge(e)?q(0):void 0}function qp(e){return st(e)||je(e)||ht(e)?q(e.toString()):S(e)?q(`null`):T(e)?q(e):Ge(e)?q(``):void 0}function Uee(e){return H(e,BigInt(0))?q(void 0):void 0}function Wee(e){return H(e,!1)?q(void 0):void 0}function Gee(e){return H(e,0)?q(void 0):void 0}function Kee(e){let t=e.toLowerCase();return H(t,`undefined`)||H(t,`null`)||H(e,``)||H(e,`0`)?q(void 0):void 0}function Jp(e){return st(e)?Uee(e):je(e)?Wee(e):ht(e)?Gee(e):S(e)?q(void 0):T(e)?Kee(e):Ge(e)?q(e):void 0}function qee(e,t,n){return Cee(n).value.map(n=>um(e,t.items,n))}function Jee(e,t,n){return t.Convert(n)}function Yee(e,t,n){let r=Hp(n);return Vp(r)?r.value:n}function Xee(e,t,n){let r=Up(n);return Vp(r)?r.value:n}function Zee(e,t,n){return um({...e,...t.$defs},x(t.$ref),n)}function Yp(e,t,n){if(t.anyOf.some(t=>hp(e,t,n)))return n;let r=t.anyOf.map(t=>um(e,t,Ip(n))).find(n=>hp(e,t,n));return Ge(r)?n:r}function Qee(e,t,n){return Yp(e,qe(t),n)}function $ee(e,t,n){let r=Kp(n);return Vp(r)?Math.trunc(r.value):n}function ete(e,t,n){return um(e,ge(_(e,t)),n)}function tte(e,t,n){let r=Hp(n);return Vp(r)&&H(t.const,r.value)?r.value:n}function nte(e,t,n){let r=Up(n);return Vp(r)&&H(t.const,r.value)?r.value:n}function rte(e,t,n){let r=Kp(n);return Vp(r)&&H(t.const,r.value)?r.value:n}function ite(e,t,n){let r=qp(n);return Vp(r)&&H(t.const,r.value)?r.value:n}function ate(e,t,n){return H(t.const,n)?n:De(t)?tte(e,t,n):pt(t)?nte(e,t,n):nee(t)?rte(e,t,n):Ae(t)?ite(e,t,n):Ke()}function Xp(e,t,n){let r=zee(n);return Vp(r)?r.value:n}function Zp(e,t,n){let r=Kp(n);return Vp(r)?r.value:n}function Qp(e,t,n,r){let i=M(r);for(let[a,o]of t)for(let t of i)a.test(t)||(r[t]=um(e,n,r[t]));return r}function $p(e,t,n){return it(e)&&Ge(n[t])}function em(e,t,n){let r=lt(t.properties),i=M(n);for(let[t,a]of r)for(let r of i)!t.test(r)||$p(a,r,n)||(n[r]=um(e,a,n[r]));return U(t,`additionalProperties`)&&F(t.additionalProperties)?Qp(e,r,t.additionalProperties,n):n}function tm(e,t,n){return O(n)?em(e,t,n):n}function nm(e,t,n){let r=lt(t.patternProperties),i=M(n);for(let[t,a]of r)for(let r of i)t.test(r)&&(n[r]=um(e,a,n[r]));return U(t,`additionalProperties`)&&F(t.additionalProperties)?Qp(e,r,t.additionalProperties,n):n}function rm(e,t,n){return O(n)?nm(e,t,n):n}function im(e,t,n){return U(e,t.$ref)?um(e,e[t.$ref],n):n}function am(e,t,n){let r=qp(n);return Vp(r)?r.value:n}function om(e,t,n){return um(e,dt(t.pattern),n)}function sm(e,t,n){if(!V(n))return n;for(let r=0;r<Math.min(t.items.length,n.length);r++)n[r]=um(e,t.items[r],n[r]);return n}function cm(e,t,n){let r=Jp(n);return Vp(r)?r.value:n}function lm(e,t,n){return Vp(Jp(n))?void 0:n}function um(e,t,n){return Se(t)?qee(e,t,n):ce(t)?Jee(e,t,n):I(t)?Yee(e,t,n):gt(t)?Xee(e,t,n):N(t)?Zee(e,t,n):We(t)?Qee(e,t,n):C(t)?$ee(e,t,n):b(t)?ete(e,t,n):ze(t)?ate(e,t,n):Ve(t)?Xp(e,t,n):Xe(t)?Zp(e,t,n):ae(t)?tm(e,t,n):Oe(t)?rm(e,t,n):bt(t)?im(e,t,n):Pe(t)?am(e,t,n):Qe(t)?om(e,t,n):Me(t)?sm(e,t,n):He(t)?cm(e,t,n):he(t)?Yp(e,t,n):ot(t)?lm(e,t,n):n}function dm(...e){let[t,n,r]=Eo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return um(t,n,r)}function fm(e,t,n){if(!V(n))return n;for(let r=0;r<n.length;r++)n[r]=bm(e,t.items,n[r]);return n}function pm(e,t,n){return t.Default(n)}function ote(e,t,n){return bm({...e,...t.$defs},x(t.$ref),n)}function ste(e,t){return Ge(t)?tt(e.default)?e.default():Ip(e.default):t}function mm(e,t,n){return bm(e,ge(_(e,t)),n)}function hm(e,t,n){if(!F(n))return n;let r=M(t.properties);for(let i of r)Ge(bm(e,t.properties[i],n[i]))&&(it(t.properties[i])||!U(t.properties[i],`default`))||(n[i]=bm(e,t.properties[i],n[i]));if(!Io(t)||je(t.additionalProperties))return n;for(let i of M(n))r.includes(i)||(n[i]=bm(e,t.additionalProperties,n[i]));return n}function gm(e,t,n){if(!F(n))return n;let[r,i]=[new RegExp(et(t)),ct(t)];for(let t of M(n))r.test(t)&&Ho(i)&&(n[t]=bm(e,i,n[t]));if(!Io(t))return n;for(let i of M(n))r.test(i)||(n[i]=bm(e,t.additionalProperties,n[i]));return n}function _m(e,t,n){return U(e,t.$ref)?bm(e,e[t.$ref],n):n}function vm(e,t,n){if(!V(n))return n;let[r,i]=[t.items,Math.max(t.items.length,n.length)];for(let t=0;t<i;t++)t<r.length&&(n[t]=bm(e,r[t],n[t]));return n}function ym(e,t,n){for(let r of t.anyOf){let t=bm(e,r,Ip(n));if(hp(e,r,t))return t}return n}function bm(e,t,n){let r=Ho(t)?ste(t,n):n;return Se(t)?fm(e,t,r):ce(t)?pm(e,t,r):N(t)?ote(e,t,r):b(t)?mm(e,t,r):ae(t)?hm(e,t,r):Oe(t)?gm(e,t,r):bt(t)?_m(e,t,r):Me(t)?vm(e,t,r):he(t)?ym(e,t,r):r}function xm(...e){let[t,n,r]=Eo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return bm(t,n,r)}function Sm(e){return(...t)=>{let[n,r,i]=Eo(t,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return e.reduce((e,t)=>t(n,r,e),i)}}function Cm(e,t,n){return t[`~codec`].decode(n)}function wm(e,t,n){return t[`~codec`].encode(n)}function Tm(e,t,n,r){return k(n)?H(e,`Decode`)?Cm(t,n,r):wm(t,n,r):r}function Em(e,t,n,r){if(!V(r))return Ke();for(let i=0;i<r.length;i++)r[i]=Ym(e,t,n.items,r[i]);return Tm(e,t,n,r)}function Dm(e,t,n,r){let i=Tm(e,t,n,r);if(!V(i))return i;for(let r=0;r<i.length;r++)i[r]=Ym(e,t,n.items,i[r]);return i}function Om(e,t,n,r){return H(e,`Decode`)?Em(e,t,n,r):Dm(e,t,n,r)}function km(e,t,n,r){return r=Ym(e,{...t,...n.$defs},x(n.$ref),r),Tm(e,t,n,r)}function Am(e){return e.reduce((e,t)=>({...e,...t}),{})}function jm(e,t){for(let n of t)if(!Ne(e,n))return n;return e}function Mm(e,t,n,r){if(H(n.allOf.length,0))return Tm(e,t,n,r);let i=n.allOf.map(n=>Ym(e,t,n,Bp(n,Ip(r))));return Tm(e,t,n,i.every(e=>F(e))?Am(i):jm(r,i))}function Nm(e,t,n,r){if(H(n.allOf.length,0))return Tm(e,t,n,r);let i=Tm(e,t,n,r),a=n.allOf.map(n=>Ym(e,t,n,Bp(n,Ip(i))));return a.every(e=>F(e))?Am(a):jm(i,a)}function Pm(e,t,n,r){return H(e,`Decode`)?Mm(e,t,n,r):Nm(e,t,n,r)}function Fm(e,t,n,r){if(!O(r))return Ke();for(let i of M(n.properties))!U(r,i)||$p(n.properties[i],i,r)||(r[i]=Ym(e,t,n.properties[i],r[i]));return Tm(e,t,n,r)}function Im(e,t,n,r){let i=Tm(e,t,n,r);if(!O(i))return i;for(let r of M(n.properties))!U(i,r)||$p(n.properties[r],r,i)||(i[r]=Ym(e,t,n.properties[r],i[r]));return i}function Lm(e,t,n,r){return H(e,`Decode`)?Fm(e,t,n,r):Im(e,t,n,r)}function Rm(e,t,n,r){if(!O(r))return Ke();let i=new RegExp(et(n));for(let a of M(r))i.test(a)||Ke(),r[a]=Ym(e,t,ct(n),r[a]);return Tm(e,t,n,r)}function zm(e,t,n,r){let i=Tm(e,t,n,r);if(!O(i))return i;let a=new RegExp(et(n));for(let r of M(i))a.test(r)&&(i[r]=Ym(e,t,ct(n),i[r]));return i}function Bm(e,t,n,r){return H(e,`Decode`)?Rm(e,t,n,r):zm(e,t,n,r)}function Vm(e,t,n,r){return U(t,n.$ref)?Ym(e,t,t[n.$ref],r):r}function Hm(e,t,n,r){return H(e,`Decode`)?Tm(e,t,n,Vm(e,t,n,r)):Vm(e,t,n,Tm(e,t,n,r))}function Um(e,t,n,r){if(!V(r))return Ke();for(let i=0;i<Math.min(n.items.length,r.length);i++)r[i]=Ym(e,t,n.items[i],r[i]);return Tm(e,t,n,r)}function Wm(e,t,n,r){let i=Tm(e,t,n,r);if(!V(i))return r;for(let r=0;r<Math.min(n.items.length,i.length);r++)i[r]=Ym(e,t,n.items[r],i[r]);return i}function Gm(e,t,n,r){return H(e,`Decode`)?Um(e,t,n,r):Wm(e,t,n,r)}function Km(e,t,n,r){for(let i of Rp(n.anyOf,1))if(hp(t,i,r))return Tm(e,t,n,Ym(e,t,i,r));return r}function qm(e,t,n,r){let i=Tm(e,t,n,r);for(let r of Rp(n.anyOf,-1)){let n=Ym(e,t,r,Ip(i));if(hp(t,r,n))return n}return i}function Jm(e,t,n,r){return H(e,`Decode`)?Km(e,t,n,r):qm(e,t,n,r)}function Ym(e,t,n,r){return Se(n)?Om(e,t,n,r):N(n)?km(e,t,n,r):b(n)?Pm(e,t,n,r):ae(n)?Lm(e,t,n,r):Oe(n)?Bm(e,t,n,r):bt(n)?Hm(e,t,n,r):Me(n)?Gm(e,t,n,r):he(n)?Jm(e,t,n,r):Tm(e,t,n,r)}var Xm=class extends _p{constructor(e,t){super(`Decode`,e,t)}};function Zm(e,t,n){if(!hp(e,t,n))throw new Xm(n,gp(e,t,n));return n}function Qm(e,t,n){return Ym(`Decode`,e,t,n)}const $m=Sm([(e,t,n)=>Ip(n),(e,t,n)=>xm(e,t,n),(e,t,n)=>dm(e,t,n),(e,t,n)=>Bp(e,t,n),(e,t,n)=>Zm(e,t,n),(e,t,n)=>Qm(e,t,n)]);function eh(...e){let[t,n,r]=Eo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return $m(t,n,r)}var th=class extends _p{constructor(e,t){super(`Encode`,e,t)}};function nh(e,t,n){if(!hp(e,t,n))throw new th(n,gp(e,t,n));return n}function rh(e,t,n){return Ym(`Encode`,e,t,n)}const ih=Sm([(e,t,n)=>Ip(n),(e,t,n)=>rh(e,t,n),(e,t,n)=>xm(e,t,n),(e,t,n)=>dm(e,t,n),(e,t,n)=>Bp(e,t,n),(e,t,n)=>nh(e,t,n)]);function ah(...e){let[t,n,r]=Eo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return ih(t,n,r)}function oh(e,t){return k(t)||mh(e,t.items)}function sh(e,t){return k(t)||dh({...e,...t.$defs},x(t.$ref))}function ch(e,t){return k(t)||t.allOf.some(t=>mh(e,t))}function lh(e,t){return k(t)||M(t.properties).some(n=>mh(e,t.properties[n]))}function uh(e,t){return k(t)||mh(e,ct(t))}function dh(e,t){return hh.has(t.$ref)?!1:(hh.add(t.$ref),k(t)||U(e,t.$ref)&&mh(e,e[t.$ref]))}function fh(e,t){return k(t)||t.items.some(t=>mh(e,t))}function ph(e,t){return k(t)||t.anyOf.some(t=>mh(e,t))}function mh(e,t){return Se(t)?oh(e,t):N(t)?sh(e,t):b(t)?ch(e,t):ae(t)?lh(e,t):Oe(t)?uh(e,t):bt(t)?dh(e,t):Me(t)?fh(e,t):he(t)?ph(e,t):k(t)}const hh=new Set;function gh(...e){let[t,n]=Eo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return hh.clear(),mh(t,n)}var _h=class extends Error{constructor(e,t){super(t),this.type=e}};function vh(e,t){return tt(t.default)?t.default(t):F(t.default)?Ip(t.default):t.default}function yh(e,t){if(Os(t)&&!Ho(t))throw new _h(t,`Arrays with uniqueItems constraints must specify a default annotation`);let n=us(t)?t.minItems:0;return Array.from({length:n},()=>Kh(e,t.items))}async function*bh(){}function xh(e,t){return bh()}function Sh(e,t){return t.Create()}function Ch(e,t){return Zo(t)?BigInt(t.exclusiveMinimum)+BigInt(1):cs(t)?BigInt(t.minimum):BigInt(0)}function wh(e,t){return!1}function Th(e,t){let n=Kh(e,t.instanceType);return class{constructor(){Object.assign(this,n)}}}function Eh(e,t){return Kh({...e,...t.$defs},x(t.$ref))}function Dh(e,t){return Kh(e,qe(t))}function Oh(e,t){let n=Kh(e,t.returnType);return()=>n}function kh(e,t){return Zo(t)&&ht(t.exclusiveMinimum)?t.exclusiveMinimum+1:cs(t)?t.minimum:0}function Ah(e,t){return Kh(e,ge(_(e,t)))}function*jh(){}function Mh(e,t){return jh()}function Nh(e,t){return t.const}function Ph(e,t){throw new _h(t,`Cannot create TNever types`)}function Fh(e,t){return null}function Ih(e,t){return Zo(t)&&ht(t.exclusiveMinimum)?t.exclusiveMinimum+1:cs(t)?t.minimum:0}function Lh(e,t){return(Ge(t.required)?[]:t.required).reduce((n,r)=>({...n,[r]:Kh(e,t.properties[r])}),{})}function Rh(e,t){return Promise.resolve(Kh(e,t.item))}function zh(e,t){if(fs(t)&&!Ho(t))throw new _h(t,`Record with the minProperties constraint must have a default annotation`);return{}}function Bh(e,t){return U(e,t.$ref)?Kh(e,e[t.$ref]):(()=>{throw new _h(t,`Unable to deref Ref`)})()}function Vh(e,t){if((gs(t)||Qo(t))&&!Ho(t))throw Error(`Strings with format or pattern constraints must specify default`);let n=ds(t)?t.minLength:0;return``.padEnd(n)}function Hh(e,t){return Symbol()}function Uh(e,t){let n=dt(t.pattern);if(Pe(n))throw new _h(t,`Unable to create TemplateLiteral due to infinite type expansion`);return Kh(e,n)}function Wh(e,t){return Array.from({length:t.minItems},(n,r)=>Kh(e,t.items[r]))}function Gh(e,t){if(H(t.anyOf.length,0))throw Error(`Unable to create Union with no variants`);return Kh(e,t.anyOf[0])}function Kh(e,t){return Ho(t)?vh(e,t):Se(t)?yh(e,t):xe(t)?xh(e,t):ce(t)?Sh(e,t):I(t)?Ch(e,t):gt(t)?wh(e,t):ne(t)?Th(e,t):N(t)?Eh(e,t):We(t)?Dh(e,t):L(t)?Oh(e,t):C(t)?kh(e,t):b(t)?Ah(e,t):be(t)?Mh(e,t):ze(t)?Nh(e,t):P(t)?Ph(e,t):Ve(t)?Fh(e,t):Xe(t)?Ih(e,t):ae(t)?Lh(e,t):se(t)?Rh(e,t):Oe(t)?zh(e,t):bt(t)?Bh(e,t):Pe(t)?Vh(e,t):nt(t)?Hh(e,t):Qe(t)?Uh(e,t):Me(t)?Wh(e,t):He(t)?void 0:he(t)?Gh(e,t):(ot(t),void 0)}function qh(...e){let[t,n]=Eo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return Kh(t,n)}var Jh=class extends _p{constructor(e,t){super(`Parse`,e,t)}};function Yh(e,t,n){if(!hp(e,t,n))throw new Jh(n,gp(e,t,n));return n}const Xh=Sm([(e,t,n)=>Ip(n),(e,t,n)=>xm(e,t,n),(e,t,n)=>dm(e,t,n),(e,t,n)=>Bp(e,t,n),(e,t,n)=>Yh(e,t,n)]);j([le({type:vt(`insert`),path:Le(),value:de()}),Object({type:vt(`update`),path:Le(),value:de()}),le({type:vt(`delete`),path:Le()})]);var Zh=class e extends te{constructor(...e){super();let t=Eo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[e,t]});if(t.length===3&&t[1]instanceof dp&&t[2]instanceof up){let[e,n,r]=t;this.hasCodec=e,this.buildResult=n,this.evaluateResult=r}else{let[e,n]=t;this.hasCodec=gh(e,n),this.buildResult=fp(e,n),this.evaluateResult=this.buildResult.Evaluate()}}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(e){return this.evaluateResult.Check(e)}Parse(e){if(this.Check(e))return e;if(z().correctiveParse)return Xh(this.Context(),this.Type(),e);throw new Jh(e,this.Errors(e))}Errors(e){return this.IsAccelerated()&&this.Check(e)?[]:gp(this.Context(),this.Type(),e)}Clean(e){return Bp(this.Context(),this.Type(),e)}Convert(e){return dm(this.Context(),this.Type(),e)}Create(){return qh(this.Context(),this.Type())}Default(e){return xm(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?eh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?ah(this.Context(),this.Type(),e):this.Parse(e)}Clone(){return new e(this.hasCodec,this.buildResult,this.evaluateResult)}};function Qh(...e){let[t,n]=Eo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return new Zh(t,n)}const $h=new WeakMap,eg=Symbol.for(`TypeBox.Kind`);function tg(e){return typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type.filter(e=>typeof e==`string`):[]}function ng(e,t){switch(t){case`number`:return typeof e==`number`;case`integer`:return typeof e==`number`&&Number.isInteger(e);case`boolean`:return typeof e==`boolean`;case`string`:return typeof e==`string`;case`null`:return e===null;case`array`:return Array.isArray(e);case`object`:return typeof e==`object`&&!!e&&!Array.isArray(e);default:return!1}}function rg(e){try{return lg(e)}catch{return}}function ig(e,t){switch(t){case`number`:if(e===null)return 0;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return typeof e==`boolean`?+!!e:e;case`integer`:if(e===null)return 0;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isInteger(t))return t}return typeof e==`boolean`?+!!e:e;case`boolean`:if(e===null)return!1;if(typeof e==`string`){if(e===`true`)return!0;if(e===`false`)return!1}if(typeof e==`number`){if(e===1)return!0;if(e===0)return!1}return e;case`string`:return e===null?``:typeof e==`number`||typeof e==`boolean`?String(e):e;case`null`:return e===``||e===0||e===!1?null:e;default:return e}}function ag(e,t){let n=t.properties,r=new Set(n?Object.keys(n):[]);if(n)for(let[t,r]of Object.entries(n))t in e&&(e[t]=cg(e[t],r));if(t.additionalProperties&&typeof t.additionalProperties==`object`)for(let[n,i]of Object.entries(e))r.has(n)||(e[n]=cg(i,t.additionalProperties))}function og(e,t){if(Array.isArray(t.items)){for(let n=0;n<e.length;n++){let r=t.items[n];r&&(e[n]=cg(e[n],r))}return}if(t.items&&typeof t.items==`object`)for(let n=0;n<e.length;n++)e[n]=cg(e[n],t.items)}function sg(e,t){for(let n of t){let t=cg(structuredClone(e),n);if(rg(n)?.Check(t))return t}return e}function cg(e,t){let n=e;if(Array.isArray(t.allOf))for(let e of t.allOf)n=cg(n,e);Array.isArray(t.anyOf)&&(n=sg(n,t.anyOf)),Array.isArray(t.oneOf)&&(n=sg(n,t.oneOf));let r=tg(t),i=r.length>1&&r.some(e=>ng(n,e));if(r.length>0&&!i)for(let e of r){let t=ig(n,e);if(t!==n){n=t;break}}return r.includes(`object`)&&typeof n==`object`&&n&&!Array.isArray(n)&&ag(n,t),r.includes(`array`)&&Array.isArray(n)&&og(n,t),n}function lg(e){let t=e,n=$h.get(t);if(n)return n;let r=Qh(e);return $h.set(t,r),r}function ug(e){if(e.keyword===`required`){let t=e.params.requiredProperties?.[0];if(t){let n=e.instancePath.replace(/^\//,``).replace(/\//g,`.`);return n?`${n}.${t}`:t}}return e.instancePath.replace(/^\//,``).replace(/\//g,`.`)||`root`}function dg(e,t){let n=structuredClone(t.arguments);dm(e.parameters,n);let r=lg(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(eg)){let t=cg(n,e.parameters);if(t!==n)if(typeof n==`object`&&n&&typeof t==`object`&&t){for(let e of Object.keys(n))delete n[e];Object.assign(n,t)}else return r.Check(t)?t:n}if(r.Check(n))return n;let i=r.Errors(n).map(e=>` - ${ug(e)}: ${e.message}`).join(`
885
885
  `)||`Unknown validation error`,a=`Validation failed for tool "${t.name}":\n${i}\n\nReceived arguments:\n${JSON.stringify(t.arguments,null,2)}`;throw Error(a)}function fg(){throw Error(`No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().`)}async function pg(e,t,n,r,i,a){let o=[...e],s={...t,messages:[...t.messages,...e]};await r({type:`agent_start`}),await r({type:`turn_start`});for(let t of e)await r({type:`message_start`,message:t}),await r({type:`message_end`,message:t});return await hg(s,o,n,i,r,a??fg()),o}async function mg(e,t,n,r,i){if(e.messages.length===0)throw Error(`Cannot continue: no messages in context`);if(e.messages[e.messages.length-1].role===`assistant`)throw Error(`Cannot continue from message role: assistant`);let a=[],o={...e};return await n({type:`agent_start`}),await n({type:`turn_start`}),await hg(o,a,t,r,n,i??fg()),a}async function hg(e,t,n,r,i,a){let o=e,s=n,c=!0,l=await s.getSteeringMessages?.()||[];for(;;){let e=!0;for(;e||l.length>0;){if(c?c=!1:await i({type:`turn_start`}),l.length>0){for(let e of l)await i({type:`message_start`,message:e}),await i({type:`message_end`,message:e}),o.messages.push(e),t.push(e);l=[]}let n=await gg(o,s,r,i,a);if(t.push(n),n.stopReason===`error`||n.stopReason===`aborted`){await i({type:`turn_end`,message:n,toolResults:[]}),await i({type:`agent_end`,messages:t});return}let u=n.content.filter(e=>e.type===`toolCall`),d=[];if(e=!1,u.length>0){let a=n.stopReason===`length`?await _g(u,i):await vg(o,n,s,r,i);d.push(...a.messages),e=!a.terminate;for(let e of d)o.messages.push(e),t.push(e)}await i({type:`turn_end`,message:n,toolResults:d});let f={message:n,toolResults:d,context:o,newMessages:t},p=await s.prepareNextTurn?.(f);if(p&&(o=p.context??o,s={...s,model:p.model??s.model,reasoning:p.thinkingLevel===void 0?s.reasoning:p.thinkingLevel===`off`?void 0:p.thinkingLevel}),await s.shouldStopAfterTurn?.({message:n,toolResults:d,context:o,newMessages:t})){await i({type:`agent_end`,messages:t});return}l=await s.getSteeringMessages?.()||[]}let n=await s.getFollowUpMessages?.()||[];if(n.length>0){l=n;continue}break}await i({type:`agent_end`,messages:t})}async function gg(e,t,n,r,i){let a=e.messages;t.transformContext&&(a=await t.transformContext(a,n));let o=await t.convertToLlm(a),s={systemPrompt:e.systemPrompt,messages:o,tools:e.tools},c=(t.getApiKey?await t.getApiKey(t.model.provider):void 0)||t.apiKey,l=await i(t.model,s,{...t,apiKey:c,signal:n}),u=null,d=!1;for await(let t of l)switch(t.type){case`start`:u=t.partial,e.messages.push(u),d=!0,await r({type:`message_start`,message:{...u}});break;case`text_start`:case`text_delta`:case`text_end`:case`thinking_start`:case`thinking_delta`:case`thinking_end`:case`toolcall_start`:case`toolcall_delta`:case`toolcall_end`:u&&(u=t.partial,e.messages[e.messages.length-1]=u,await r({type:`message_update`,assistantMessageEvent:t,message:{...u}}));break;case`done`:case`error`:{let t=await l.result();return d?e.messages[e.messages.length-1]=t:e.messages.push(t),d||await r({type:`message_start`,message:{...t}}),await r({type:`message_end`,message:t}),t}}let f=await l.result();return d?e.messages[e.messages.length-1]=f:(e.messages.push(f),await r({type:`message_start`,message:{...f}})),await r({type:`message_end`,message:f}),f}async function _g(e,t){let n=[];for(let r of e){await t({type:`tool_execution_start`,toolCallId:r.id,toolName:r.name,args:r.arguments});let e={toolCall:r,result:Eg(`Tool call "${r.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await Dg(e,t);let i=Og(e);await kg(i,t),n.push(i)}return{messages:n,terminate:!1}}async function vg(e,t,n,r,i){let a=t.content.filter(e=>e.type===`toolCall`),o=a.some(t=>e.tools?.find(e=>e.name===t.name)?.executionMode===`sequential`);return n.toolExecution===`sequential`||o?yg(e,t,a,n,r,i):bg(e,t,a,n,r,i)}async function yg(e,t,n,r,i,a){let o=[],s=[];for(let c of n){await a({type:`tool_execution_start`,toolCallId:c.id,toolName:c.name,args:c.arguments});let n=await Cg(e,t,c,r,i),l;l=n.kind===`immediate`?{toolCall:c,result:n.result,isError:n.isError}:await Tg(e,t,n,await wg(n,i,a),r,i),await Dg(l,a);let u=Og(l);if(await kg(u,a),o.push(l),s.push(u),i?.aborted)break}return{messages:s,terminate:xg(o)}}async function bg(e,t,n,r,i,a){let o=[];for(let s of n){await a({type:`tool_execution_start`,toolCallId:s.id,toolName:s.name,args:s.arguments});let n=await Cg(e,t,s,r,i);if(n.kind===`immediate`){let e={toolCall:s,result:n.result,isError:n.isError};if(await Dg(e,a),o.push(e),i?.aborted)break;continue}if(o.push(async()=>{let o=await wg(n,i,a),s=await Tg(e,t,n,o,r,i);return await Dg(s,a),s}),i?.aborted)break}let s=await Promise.all(o.map(e=>typeof e==`function`?e():Promise.resolve(e))),c=[];for(let e of s){let t=Og(e);await kg(t,a),c.push(t)}return{messages:c,terminate:xg(s)}}function xg(e){return e.length>0&&e.every(e=>e.result.terminate===!0)}function Sg(e,t){if(!e.prepareArguments)return t;let n=e.prepareArguments(t.arguments);return n===t.arguments?t:{...t,arguments:n}}async function Cg(e,t,n,r,i){let a=e.tools?.find(e=>e.name===n.name);if(!a)return{kind:`immediate`,result:Eg(`Tool ${n.name} not found`),isError:!0};try{let o=dg(a,Sg(a,n));if(r.beforeToolCall){let a=await r.beforeToolCall({assistantMessage:t,toolCall:n,args:o,context:e},i);if(i?.aborted)return{kind:`immediate`,result:Eg(`Operation aborted`),isError:!0};if(a?.block)return{kind:`immediate`,result:Eg(a.reason||`Tool execution was blocked`),isError:!0}}return i?.aborted?{kind:`immediate`,result:Eg(`Operation aborted`),isError:!0}:{kind:`prepared`,toolCall:n,tool:a,args:o}}catch(e){return{kind:`immediate`,result:Eg(e instanceof Error?e.message:String(e)),isError:!0}}}async function wg(e,t,n){let r=[],i=!0;try{let a=await e.tool.execute(e.toolCall.id,e.args,t,t=>{i&&r.push(Promise.resolve(n({type:`tool_execution_update`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,args:e.toolCall.arguments,partialResult:t})))});return i=!1,await Promise.all(r),{result:a,isError:!1}}catch(e){return i=!1,await Promise.all(r),{result:Eg(e instanceof Error?e.message:String(e)),isError:!0}}finally{i=!1}}async function Tg(e,t,n,r,i,a){let o=r.result,s=r.isError;if(i.afterToolCall)try{let r=await i.afterToolCall({assistantMessage:t,toolCall:n.toolCall,args:n.args,result:o,isError:s,context:e},a);r&&(o={...o,content:r.content??o.content,details:r.details??o.details,usage:r.usage??o.usage,terminate:r.terminate??o.terminate},s=r.isError??s)}catch(e){o=Eg(e instanceof Error?e.message:String(e)),s=!0}return{toolCall:n.toolCall,result:o,isError:s}}function Eg(e){return{content:[{type:`text`,text:e}],details:{}}}async function Dg(e,t){await t({type:`tool_execution_end`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError})}function Og(e){return{role:`toolResult`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,content:e.result.content??[],details:e.result.details,usage:e.result.usage,...e.result.addedToolNames?.length?{addedToolNames:e.result.addedToolNames}:{},isError:e.isError,timestamp:Date.now()}}async function kg(e,t){await t({type:`message_start`,message:e}),await t({type:`message_end`,message:e})}function cte(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`toolResult`)}const lte={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},ute={id:`unknown`,name:`unknown`,api:`unknown`,provider:`unknown`,baseUrl:``,reasoning:!1,input:[],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:0,maxTokens:0};function dte(e){let t=e?.tools?.slice()??[],n=e?.messages?.slice()??[];return{systemPrompt:e?.systemPrompt??``,model:e?.model??ute,thinkingLevel:e?.thinkingLevel??`off`,get tools(){return t},set tools(e){t=e.slice()},get messages(){return n},set messages(e){n=e.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}var Ag=class{messages=[];mode;constructor(e){this.mode=e}enqueue(e){this.messages.push(e)}hasItems(){return this.messages.length>0}drain(){if(this.mode===`all`){let e=this.messages.slice();return this.messages=[],e}let e=this.messages[0];return e?(this.messages=this.messages.slice(1),[e]):[]}clear(){this.messages=[]}},fte=class{_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFunction;getApiKey;onPayload;onResponse;beforeToolCall;afterToolCall;prepareNextTurn;prepareNextTurnWithContext;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e){let t=e??{};this._state=dte(t.initialState),this.convertToLlm=t.convertToLlm??cte,this.transformContext=t.transformContext,this.streamFunction=t.streamFn??fg(),this.getApiKey=t.getApiKey,this.onPayload=t.onPayload,this.onResponse=t.onResponse,this.beforeToolCall=t.beforeToolCall,this.afterToolCall=t.afterToolCall,this.prepareNextTurn=t.prepareNextTurn,this.prepareNextTurnWithContext=t.prepareNextTurnWithContext,this.steeringQueue=new Ag(t.steeringMode??`one-at-a-time`),this.followUpQueue=new Ag(t.followUpMode??`one-at-a-time`),this.sessionId=t.sessionId,this.thinkingBudgets=t.thinkingBudgets,this.transport=t.transport??`auto`,this.maxRetryDelayMs=t.maxRetryDelayMs,this.toolExecution=t.toolExecution??`parallel`}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){this._state.messages=[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,t){if(this.activeRun)throw Error(`Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.`);let n=this.normalizePromptInput(e,t);await this.runPromptMessages(n)}async continue(){if(this.activeRun)throw Error(`Agent is already processing. Wait for completion before continuing.`);let e=this._state.messages[this._state.messages.length-1];if(!e)throw Error(`No messages to continue from`);if(e.role===`assistant`){let e=this.steeringQueue.drain();if(e.length>0){await this.runPromptMessages(e,{skipInitialSteeringPoll:!0});return}let t=this.followUpQueue.drain();if(t.length>0){await this.runPromptMessages(t);return}throw Error(`Cannot continue from message role: assistant`)}await this.runContinuation()}normalizePromptInput(e,t){if(Array.isArray(e))return e;if(typeof e!=`string`)return[e];let n=[{type:`text`,text:e}];return t&&t.length>0&&n.push(...t),[{role:`user`,content:n,timestamp:Date.now()}]}async runPromptMessages(e,t={}){await this.runWithLifecycle(async n=>{await pg(e,this.createContextSnapshot(),this.createLoopConfig(t),e=>this.processEvents(e),n,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async e=>{await mg(this.createContextSnapshot(),this.createLoopConfig(),e=>this.processEvents(e),e,this.streamFunction)})}createContextSnapshot(){return{systemPrompt:this._state.systemPrompt,messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let t=e.skipInitialSteeringPoll===!0;return{model:this._state.model,reasoning:this._state.thinkingLevel===`off`?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async e=>this.prepareNextTurnWithContext?await this.prepareNextTurnWithContext(e,this.signal):await this.prepareNextTurn?.(this.signal):void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>t?(t=!1,[]):this.steeringQueue.drain(),getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error(`Agent is already processing.`);let t=new AbortController,n=()=>{},r=new Promise(e=>{n=e});this.activeRun={promise:r,resolve:n,abortController:t},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(t.signal)}catch(e){await this.handleRunFailure(e,t.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,t){let n={role:`assistant`,content:[{type:`text`,text:``}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:lte,stopReason:t?`aborted`:`error`,errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:`message_start`,message:n}),await this.processEvents({type:`message_end`,message:n}),await this.processEvents({type:`turn_end`,message:n,toolResults:[]}),await this.processEvents({type:`agent_end`,messages:[n]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case`message_start`:this._state.streamingMessage=e.message;break;case`message_update`:this._state.streamingMessage=e.message;break;case`message_end`:this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case`tool_execution_start`:{let t=new Set(this._state.pendingToolCalls);t.add(e.toolCallId),this._state.pendingToolCalls=t;break}case`tool_execution_end`:{let t=new Set(this._state.pendingToolCalls);t.delete(e.toolCallId),this._state.pendingToolCalls=t;break}case`turn_end`:e.message.role===`assistant`&&e.message.errorMessage&&(this._state.errorMessage=e.message.errorMessage);break;case`agent_end`:this._state.streamingMessage=void 0;break}let t=this.activeRun?.abortController.signal;if(!t)throw Error(`Agent listener invoked outside active run`);for(let n of this.listeners)await n(e,t)}};function pte(e){if(!Number.isFinite(e)||e<=0)return`0 B`;let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n>=10||r===0?Math.round(n):Math.round(n*10)/10} ${t[r]}`}function mte(e){let t=e.mimeType||`application/octet-stream`;return`${e.name} (${t}, ${pte(e.size)})`}function hte(e){let t=mte(e);return e.kind===`image`&&e.data?e.path?`[Attached image: ${t} — full-resolution copy saved to ${e.path}]`:`[Attached image: ${t}]`:e.kind===`text`&&e.text!==void 0?[`----- BEGIN ATTACHMENT ${t} -----`,e.text,`----- END ATTACHMENT ${e.name} -----`].join(`
@@ -5247,7 +5247,7 @@ Examples:
5247
5247
  skill list
5248
5248
  skill info bluebubbles
5249
5249
  skill read bluebubbles
5250
- `,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-Pt9eJlYW.js`).then(e=>e.t);try{switch(r){case`list`:{let t=await i.discoverSkills(e);return t.length===0?{stdout:`No discoverable skills found.\n\n${SG()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:wG(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
5250
+ `,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-D_Ep23NZ.js`).then(e=>e.t);try{switch(r){case`list`:{let t=await i.discoverSkills(e);return t.length===0?{stdout:`No discoverable skills found.\n\n${SG()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:wG(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
5251
5251
  `,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:TG(r),stderr:``,exitCode:0}:{stdout:``,stderr:`skill: "${n}" not found\n`,exitCode:1}}case`read`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: read requires a skill name
5252
5252
  `,exitCode:1};let r=await i.readSkillInstructions(e,n);return r===null?{stdout:``,stderr:`skill: no SKILL.md found for "${n}"\n`,exitCode:1}:{stdout:r+`
5253
5253
  `,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`skill: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`skill: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}async function OG(e,t){let n=`${_W}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=20`,r;try{r=await t(n,{headers:{Accept:`application/json`}})}catch(e){throw Error(PW(e,n))}if(r.status!==200)throw Error(`Tessl returned HTTP ${r.status}`);let i=Ft(r.body);if(!i.data)return[];let a=new Map;for(let e of i.data){if(e.type!==`skill`)continue;let t=e.attributes,n=ZW(t.sourceUrl),r=n?`${n.owner}/${n.repo}`:void 0,i=t.scores.aggregate==null?null:Math.round(t.scores.aggregate*100),o=t.sourceUrl||e.id,s=a.get(o);if(s&&s.qualityScore!=null&&i!=null&&s.qualityScore>=i)continue;let c=t.path.replace(/\/SKILL\.md$/i,``),l=c.split(`/`).pop()||t.name,u=n?`upskill ${n.owner}/${n.repo} --path ${c.split(`/`).slice(0,-1).join(`/`)||`.`} --skill ${l}`:`upskill tessl:${t.name}`;a.set(o,{name:t.name,displayName:t.name,summary:t.description||``,source:`tessl`,qualityScore:i,installHint:u,featured:t.featured,sourceRepo:r})}return Array.from(a.values())}async function kG(e,t){let n=`${_W}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=5`,r;try{r=await t(n,{headers:{Accept:`application/json`}})}catch(e){return{error:`Tessl search failed: ${PW(e,n)}`}}if(r.status!==200)return{error:`Tessl search failed (HTTP ${r.status})`};let i=Ft(r.body).data?.find(t=>t.type===`skill`&&t.attributes.name===e);if(!i)return{error:`skill "${e}" not found on Tessl registry`};let a=ZW(i.attributes.sourceUrl);if(!a)return{error:`skill "${e}" has no GitHub source URL`};let o=i.attributes.path.replace(/\/SKILL\.md$/i,``);return{owner:a.owner,repo:a.repo,skillPath:o,skillName:e}}const AG=[{label:`Tessl`,host:new URL(_W).host,fetch:OG},{label:`browse.sh`,host:new URL(vW).host,fetch:mG}];function jG(e){let t=[],n=e.reduce((e,t)=>Math.max(e,t.length),0);for(let r=0;r<n;r++)for(let n of e)r<n.length&&t.push(n[r]);return t}async function MG(e,t,n=1){let r=await Promise.allSettled(AG.map(n=>n.fetch(e,t))),i=r.map(e=>e.status===`fulfilled`?e.value:[]),a=r.every(e=>e.status===`rejected`),o=jG(i),s=``;for(let e=0;e<r.length;e++){let t=r[e];if(t.status===`rejected`){let n=AG[e],r=t.reason instanceof Error?t.reason.message:String(t.reason);s+=`warning: ${n.label} registry unavailable (${n.host}): ${r}\n`}}if(o.length===0){let t=a?`${s}upskill: registries failed to respond\n`:s;return{stdout:`No skills found for "${e}"\n\nTry a different search term or browse the registries at https://tessl.io/registry or https://browse.sh\n`,stderr:t,exitCode:+!!a}}let c=o.length,l=Math.ceil(c/10),u=Math.max(1,Math.min(n,l)),d=(u-1)*10,f=o.slice(d,d+10),p=`Search results for "${e}" (page ${u}/${l}, ${c} total):\n\n`;for(let e of f){let t=e.qualityScore==null?` `:String(e.qualityScore).padStart(3),n=`[${e.source}]`,r=e.sourceRepo?` ${e.sourceRepo}`:``;p+=` ${e.name.padEnd(30)} ${t} ${n.padEnd(10)}${r}\n`,e.summary&&(p+=` ${e.summary}\n`),p+=`
@@ -5273,7 +5273,7 @@ Examples:
5273
5273
  `,{stdout:s,stderr:``,exitCode:0}}function zG(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
5274
5274
  `,exitCode:1}:Ln(e)?null:{stdout:``,stderr:`upskill: --branch must be a git ref of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", trailing "/" or ".lock", or shell metacharacters
5275
5275
  `,exitCode:1}}function BG(e){let t={selectedSkills:[],listOnly:!1,installAll:!1,force:!1,sourceRef:``},n=0;for(;n<e.length;){let r=e[n];if(r===`--skill`)t.selectedSkills.push(e[++n]);else if(r===`--path`||r===`-p`){let r=e[++n];if(typeof r!=`string`||!Bn(r))return t.earlyReturn={stdout:``,stderr:`upskill: --path must be a repo-relative sub-path of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", or shell metacharacters
5276
- `,exitCode:1},t;t.subPath=r}else if(r===`--list`)t.listOnly=!0;else if(r===`--all`)t.installAll=!0;else if(r===`--force`)t.force=!0;else if(r===`--branch`||r===`-b`){let r=zG(e[n+1]);if(r)return t.earlyReturn=r,t;t.branch=e[++n]}else r.startsWith(`-`)||(t.sourceRef=r);n++}return t}async function VG(e){let t=await(await import(`./skills-Pt9eJlYW.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${SG()}`,stderr:``,exitCode:0}:{stdout:wG(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function HG(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-Pt9eJlYW.js`).then(e=>e.t);if(e===`info`){let e=await r.getSkillInfo(n,t);return e?{stdout:TG(e),stderr:``,exitCode:0}:{stdout:``,stderr:`upskill: skill "${t}" not found\n`,exitCode:1}}let i=await r.readSkillInstructions(n,t);return i===null?{stdout:``,stderr:`upskill: no SKILL.md found for "${t}"\n`,exitCode:1}:{stdout:i+`
5276
+ `,exitCode:1},t;t.subPath=r}else if(r===`--list`)t.listOnly=!0;else if(r===`--all`)t.installAll=!0;else if(r===`--force`)t.force=!0;else if(r===`--branch`||r===`-b`){let r=zG(e[n+1]);if(r)return t.earlyReturn=r,t;t.branch=e[++n]}else r.startsWith(`-`)||(t.sourceRef=r);n++}return t}async function VG(e){let t=await(await import(`./skills-D_Ep23NZ.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${SG()}`,stderr:``,exitCode:0}:{stdout:wG(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function HG(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-D_Ep23NZ.js`).then(e=>e.t);if(e===`info`){let e=await r.getSkillInfo(n,t);return e?{stdout:TG(e),stderr:``,exitCode:0}:{stdout:``,stderr:`upskill: skill "${t}" not found\n`,exitCode:1}}let i=await r.readSkillInstructions(n,t);return i===null?{stdout:``,stderr:`upskill: no SKILL.md found for "${t}"\n`,exitCode:1}:{stdout:i+`
5277
5277
  `,stderr:``,exitCode:0}}async function UG(e,t,n,r,i,a,o){let s=``,c=``,l=0,u=e.length;for(let d=0;d<e.length;d++){let f=e[d],p=await WW(f.path,f.name,r,i,a),m=d+1,h=((Date.now()-o)/1e3).toFixed(1),g=(Date.now()-o)/m,_=m<u?` (~${Math.round((u-m)*g/1e3)}s remaining)`:``;p.ok?(s+=`[${m}/${u}] Installed "${f.name}" from ${t}/${n} (${h}s)${_}\n`,l++):(s+=`[${m}/${u}] Failed "${f.name}": ${p.error}${_}\n`,c+=`upskill: ${p.error}\n`)}return{output:s,errors:c,successCount:l}}async function WG(e,t,n,r,i,a,o,s){let c=``,l=``,u=0,d=e.length;for(let f=0;f<e.length;f++){let p=e[f],m=await $W(t,n,p.path,p.name,i,r,a,void 0,o),h=f+1,g=((Date.now()-s)/1e3).toFixed(1),_=(Date.now()-s)/h,v=h<d?` (~${Math.round((d-h)*_/1e3)}s remaining)`:``;m.exitCode===0?(c+=`[${h}/${d}] Installed "${p.name}" from ${t}/${n} (${g}s)${v}\n`,u++):(c+=`[${h}/${d}] Failed "${p.name}": ${m.stderr.trim()}${v}\n`,l+=m.stderr)}return{output:c,errors:l,successCount:u}}async function GG(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await $W(t,n,d.path,d.name,i,r,a,o,s);e.exitCode===0?(c+=e.stdout,u++):l+=e.stderr}return{output:c,errors:l,successCount:u}}function KG(e,t,n){let r=`Available skills in ${t}/${n}:\n\n`;for(let t of e)r+=` ${t.name.padEnd(30)} ${t.path}\n`;return r+=`\nFound ${e.length} skill(s)\n`,r}async function qG(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await zW(r),l=await QW(i,a,c,s,r,o);if(l.error)return{stdout:``,stderr:`upskill: failed to list skills: ${l.error}\n`,exitCode:1};if(l.skills.length===0)return{stdout:`No skills found in ${i}/${a}${s?`/`+s:``}\n`,stderr:``,exitCode:0};if(t.listOnly)return{stdout:KG(l.skills,i,a)+`\nTo install: upskill ${t.sourceRef} --skill <name>\nTo install all: upskill ${t.sourceRef} --all\n`,stderr:``,exitCode:0};let u=l.skills;if(t.selectedSkills.length>0){u=l.skills.filter(e=>t.selectedSkills.includes(e.name));for(let e of t.selectedSkills)if(!l.skills.find(t=>t.name===e))return{stdout:``,stderr:`upskill: skill "${e}" not found in ${i}/${a}\n`,exitCode:1}}else if(!t.installAll)return{stdout:KG(l.skills,i,a)+`\nTo install specific skills: upskill ${t.sourceRef} --skill <name>\nTo install all: upskill ${t.sourceRef} --all\n`,stderr:``,exitCode:0};let d=u.length,f=Date.now(),p=``,m=``,h=0;if(d>1){let e=await qW(i,a,r,o);if(e.status===`ok`){let r=await UG(u,i,a,JW(e.files),n,t.force,f);({output:p,errors:m,successCount:h}=r)}else{let e=await WG(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await GG(u,i,a,c,n,t.force,r,o));let g=((Date.now()-f)/1e3).toFixed(1);return h>0&&(p+=`\nInstalled ${h} skill(s)${d>1?` in ${g}s`:``}\n`,await UW()),{stdout:p,stderr:m,exitCode:+!!m}}function JG(e,t,n){return W(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return EG();if(r[0]===`tabs`)return LG(e,t,n,r.includes(`--json`));if(r[0]===`recommendations`)return RG(e,t,r.includes(`--install`));if(r[0]===`list`)return VG(e);if(r[0]===`info`||r[0]===`read`)return HG(r[0],r[1],e);if(r[0]===`search`)return YG(r,t);let a=BG(r);if(a.earlyReturn)return a.earlyReturn;if(!a.sourceRef)return EG();if(a.sourceRef.startsWith(`tessl:`))return XG(a.sourceRef,a.force,e,t);let o=_G(a.sourceRef);if(o)return xG(o.hostname,o.task,e,t,a.force);let s=eG(a.sourceRef);return s?qG(s,a,e,t):{stdout:``,stderr:`upskill: unrecognized source "${a.sourceRef}"\n\nExpected: owner/repo, tessl:<name>, or browse:<hostname>/<task>\n`,exitCode:1}})}async function YG(e,t){let n=[...e.slice(1)],r=n.indexOf(`--page`),i=1;r>=0&&(i=parseInt(n[r+1],10)||1,n.splice(r,2));let a=n.join(` `);return a?MG(a,t,i):EG()}async function XG(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
5278
5278
  `,exitCode:1};let a=await kG(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await zW(r);return $W(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function ZG(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
5279
5279
 
@@ -6582,7 +6582,7 @@ Common base URLs:
6582
6582
  llama.cpp http://localhost:8080/v1
6583
6583
  vLLM http://localhost:8000/v1
6584
6584
  Jan http://localhost:1337/v1
6585
- `}function q4(){return W(G4,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:K4(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-FRENlwq7.js`),{verifyConnection:a}=await import(`./local-llm-BVGC0MAD.js`).then(e=>e.n),o=e[0]??`status`;if(o!==`status`&&o!==`discover`)return{stdout:``,stderr:`Unknown subcommand: ${o}. See \`local-llm --help\`.\n`,exitCode:2};let s=r(G4);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
6585
+ `}function q4(){return W(G4,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:K4(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-VxXaQXu5.js`),{verifyConnection:a}=await import(`./local-llm-CJRbK1cS.js`).then(e=>e.n),o=e[0]??`status`;if(o!==`status`&&o!==`discover`)return{stdout:``,stderr:`Unknown subcommand: ${o}. See \`local-llm --help\`.\n`,exitCode:2};let s=r(G4);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
6586
6586
  `,exitCode:1};let c=await a(s,t(G4)??void 0);if(!c.ok){let e=[`✗ Could not reach ${s}`,` runtime: ${c.runtime.kind}${c.runtime.version?` (${c.runtime.version})`:``}`,` error: ${c.error?.message??`unknown`}`];return c.error?.hint&&e.push(` hint: ${c.error.hint}`),{stdout:``,stderr:e.join(`
6587
6587
  `)+`
6588
6588
  `,exitCode:1}}if(o===`discover`){let e=n(G4)??``;return i(G4,e,s,c.models.join(`, `)),{stdout:[`✓ ${s} (${c.runtime.kind}${c.runtime.version?` ${c.runtime.version}`:``})`,` Saved ${c.models.length} model${c.models.length===1?``:`s`} to Settings:`,...c.models.map(e=>` • ${e}`)].join(`
@@ -6626,20 +6626,20 @@ authorization-code flow, stores the access token, and retries.
6626
6626
  On success, the server is persisted to /workspace/.mcp/servers.json and
6627
6627
  an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
6628
6628
  short name resolves on the PATH.
6629
- `);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return e3(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return e3(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return e3(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-CwkA0GJk.js`).then(e=>e.r);if(await a(i,t.fs))return e3(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BXN2qRve.js`).then(e=>e.n),l=new s({url:r,fetchImpl:t.fetchImpl}),u;try{await l.initialize()}catch(e){if(!(e instanceof c))throw e;u=await i3(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>w3(i)}),await l.initialize()}let d=await l.toolsList(),f=await l.appsList(),p=new Date().toISOString();await o(i,{url:r,tools:d,apps:f,addedAt:p,lastRefreshedAt:p,...u?{auth:u}:{}},t.fs),await A3(i,t);let m=await N3(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-BFnnJUNc.js`);e({name:i,serverUrl:r,auth:u})}return $4([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${Q4}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
6629
+ `);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return e3(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return e3(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return e3(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-CguDkxqH.js`).then(e=>e.r);if(await a(i,t.fs))return e3(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BXN2qRve.js`).then(e=>e.n),l=new s({url:r,fetchImpl:t.fetchImpl}),u;try{await l.initialize()}catch(e){if(!(e instanceof c))throw e;u=await i3(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>w3(i)}),await l.initialize()}let d=await l.toolsList(),f=await l.appsList(),p=new Date().toISOString();await o(i,{url:r,tools:d,apps:f,addedAt:p,lastRefreshedAt:p,...u?{auth:u}:{}},t.fs),await A3(i,t);let m=await N3(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-BCQiQFKs.js`);e({name:i,serverUrl:r,auth:u})}return $4([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${Q4}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
6630
6630
  `)+`
6631
- `)}async function i3(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./provider-settings-FRENlwq7.js`),c=await D3(r.oauthFetchImpl),l=r.oauthLauncher??await T3(),u=await i(e,n,c);Z4.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await E3(),f=await a(u,d,c),p=u.supportedScopes&&u.supportedScopes.length>0?u.supportedScopes.join(` `):void 0,m=await o({asMetadata:u,clientId:f.clientId,scope:p,redirectUri:d,launcher:l,fetchImpl:c}),h=`mcp:${t}`;return await s({providerId:h,accessToken:m.accessToken,refreshToken:m.refreshToken,tokenExpiresAt:m.expiresAt}),{providerId:h,authorizationServer:u.issuer,clientId:f.clientId,scope:m.scope??p,registrationClientUri:f.registrationClientUri}}async function a3(e,t){if(e.includes(`--help`)||e.includes(`-h`))return $4(`usage: mcp list
6632
- `);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-BFnnJUNc.js`);await n();let{listServers:r}=await import(`./store-CwkA0GJk.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return $4("No MCP servers configured. Use `mcp add <url> <name>`.\n");let o=[[`NAME`,`URL`,`AUTH`,`TOOLS`,`APPS`,`ADDED`]];for(let e of a){let t=i[e];o.push([e,t.url,t.auth?`yes`:`no`,String(t.tools?.length??0),String(t.apps?.length??0),t.addedAt?t.addedAt.slice(0,10):`-`])}return $4(o3(o))}function o3(e){let t=e[0].map((t,n)=>e.reduce((e,t)=>Math.max(e,(t[n]??``).length),0));return e.map(e=>e.map((e,n)=>e.padEnd(t[n])).join(` `).trimEnd()).join(`
6631
+ `)}async function i3(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./provider-settings-VxXaQXu5.js`),c=await D3(r.oauthFetchImpl),l=r.oauthLauncher??await T3(),u=await i(e,n,c);Z4.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await E3(),f=await a(u,d,c),p=u.supportedScopes&&u.supportedScopes.length>0?u.supportedScopes.join(` `):void 0,m=await o({asMetadata:u,clientId:f.clientId,scope:p,redirectUri:d,launcher:l,fetchImpl:c}),h=`mcp:${t}`;return await s({providerId:h,accessToken:m.accessToken,refreshToken:m.refreshToken,tokenExpiresAt:m.expiresAt}),{providerId:h,authorizationServer:u.issuer,clientId:f.clientId,scope:m.scope??p,registrationClientUri:f.registrationClientUri}}async function a3(e,t){if(e.includes(`--help`)||e.includes(`-h`))return $4(`usage: mcp list
6632
+ `);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-BCQiQFKs.js`);await n();let{listServers:r}=await import(`./store-CguDkxqH.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return $4("No MCP servers configured. Use `mcp add <url> <name>`.\n");let o=[[`NAME`,`URL`,`AUTH`,`TOOLS`,`APPS`,`ADDED`]];for(let e of a){let t=i[e];o.push([e,t.url,t.auth?`yes`:`no`,String(t.tools?.length??0),String(t.apps?.length??0),t.addedAt?t.addedAt.slice(0,10):`-`])}return $4(o3(o))}function o3(e){let t=e[0].map((t,n)=>e.reduce((e,t)=>Math.max(e,(t[n]??``).length),0));return e.map(e=>e.map((e,n)=>e.padEnd(t[n])).join(` `).trimEnd()).join(`
6633
6633
  `)+`
6634
6634
  `}async function s3(e,t){if(e[0]===`--help`||e[0]===`-h`)return $4(`usage: mcp search <query>
6635
6635
 
6636
6636
  Case-insensitive substring search across the cached tools of every
6637
6637
  registered MCP server. Matches tool name OR description and prints a
6638
6638
  table of (server, tool, description, match-field) rows.
6639
- `);if(e.length===0)return e3(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-BFnnJUNc.js`);await i();let{listServers:a}=await import(`./store-CwkA0GJk.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return $4("No MCP servers configured. Use `mcp add <url> <name>`.\n");let c=[];for(let e of s){let t=o[e].tools??[];for(let n of t){let t=n.description??``,i=n.name.toLowerCase().includes(r),a=t.toLowerCase().includes(r);if(!i&&!a)continue;let o=i&&a?`name+description`:i?`name`:`description`;c.push({server:e,tool:n.name,description:t,match:o})}}if(c.length===0)return $4(`No tools matched "${n}".\n`);c.sort((e,t)=>e.server===t.server?e.tool.localeCompare(t.tool):e.server.localeCompare(t.server));let l=[[`SERVER`,`TOOL`,`DESCRIPTION`,`MATCH`]];for(let e of c)l.push([e.server,e.tool,c3(e.description),e.match]);return $4(o3(l))}function c3(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function l3(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?e3(`mcp delete: expected <name>`):$4(`usage: mcp delete <name>
6640
- `);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-BFnnJUNc.js`);await r(n);let{deleteServer:a}=await import(`./store-CwkA0GJk.js`).then(e=>e.r),o=await a(n,t.fs);await j3(n,t),await M3(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./provider-settings-FRENlwq7.js`);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){Z4.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?e3(`mcp delete: no server, alias, or account found for "${n}"`):$4([`Removed MCP server "${n}"`,` servers.json: ${o?`removed`:`not present`}`,` alias: cleaned`,` sprinkles: cleaned`,` oauth: ${c?`removed`:`not present`}`,` provider: ${l?`unregistered`:`not registered`}`].join(`
6639
+ `);if(e.length===0)return e3(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-BCQiQFKs.js`);await i();let{listServers:a}=await import(`./store-CguDkxqH.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return $4("No MCP servers configured. Use `mcp add <url> <name>`.\n");let c=[];for(let e of s){let t=o[e].tools??[];for(let n of t){let t=n.description??``,i=n.name.toLowerCase().includes(r),a=t.toLowerCase().includes(r);if(!i&&!a)continue;let o=i&&a?`name+description`:i?`name`:`description`;c.push({server:e,tool:n.name,description:t,match:o})}}if(c.length===0)return $4(`No tools matched "${n}".\n`);c.sort((e,t)=>e.server===t.server?e.tool.localeCompare(t.tool):e.server.localeCompare(t.server));let l=[[`SERVER`,`TOOL`,`DESCRIPTION`,`MATCH`]];for(let e of c)l.push([e.server,e.tool,c3(e.description),e.match]);return $4(o3(l))}function c3(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function l3(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?e3(`mcp delete: expected <name>`):$4(`usage: mcp delete <name>
6640
+ `);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-BCQiQFKs.js`);await r(n);let{deleteServer:a}=await import(`./store-CguDkxqH.js`).then(e=>e.r),o=await a(n,t.fs);await j3(n,t),await M3(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./provider-settings-VxXaQXu5.js`);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){Z4.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?e3(`mcp delete: no server, alias, or account found for "${n}"`):$4([`Removed MCP server "${n}"`,` servers.json: ${o?`removed`:`not present`}`,` alias: cleaned`,` sprinkles: cleaned`,` oauth: ${c?`removed`:`not present`}`,` provider: ${l?`unregistered`:`not registered`}`].join(`
6641
6641
  `)+`
6642
- `)}async function u3(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?e3(`mcp invoke: expected <name>`):$4(p3());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-BFnnJUNc.js`);await i(n);let{getServer:a}=await import(`./store-CwkA0GJk.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return e3(`mcp invoke: unknown server "${n}" (run \`mcp add <url> ${n}\` first)`);let s=o.tools??[];if(r.length===0||r[0]===`--help`||r[0]===`-h`)return $4(m3(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return e3(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=d3(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return $4(h3(n,l));let p=g3(d,l.inputSchema);if(!p.ok)return e3(`mcp invoke: ${p.error}`);let{McpClient:m}=await import(`./client-BXN2qRve.js`).then(e=>e.n),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>w3(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=b3(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function d3(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=f3(a.slice(10));e.ok?r=e.value:n.push(e.error),i+=1;continue}if(a===`--timeout`){let t=e[i+1];if(t===void 0||t.startsWith(`--`)){n.push(`mcp invoke: --timeout requires a value (got ${t===void 0?`nothing`:`"${t}"`}); using default.`),i+=1;continue}let a=f3(t);a.ok?r=a.value:n.push(a.error),i+=2;continue}t.push(a),i+=1}return{timeoutMs:r,remaining:t,warnings:n}}function f3(e){if(!/^-?\d+$/.test(e))return{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (expected positive integer seconds); using default.`};let t=Number(e);return!Number.isFinite(t)||t<1?{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (must be >= 1 second); using default.`}:{ok:!0,value:t*1e3}}function p3(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
6642
+ `)}async function u3(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?e3(`mcp invoke: expected <name>`):$4(p3());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-BCQiQFKs.js`);await i(n);let{getServer:a}=await import(`./store-CguDkxqH.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return e3(`mcp invoke: unknown server "${n}" (run \`mcp add <url> ${n}\` first)`);let s=o.tools??[];if(r.length===0||r[0]===`--help`||r[0]===`-h`)return $4(m3(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return e3(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=d3(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return $4(h3(n,l));let p=g3(d,l.inputSchema);if(!p.ok)return e3(`mcp invoke: ${p.error}`);let{McpClient:m}=await import(`./client-BXN2qRve.js`).then(e=>e.n),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>w3(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=b3(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function d3(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=f3(a.slice(10));e.ok?r=e.value:n.push(e.error),i+=1;continue}if(a===`--timeout`){let t=e[i+1];if(t===void 0||t.startsWith(`--`)){n.push(`mcp invoke: --timeout requires a value (got ${t===void 0?`nothing`:`"${t}"`}); using default.`),i+=1;continue}let a=f3(t);a.ok?r=a.value:n.push(a.error),i+=2;continue}t.push(a),i+=1}return{timeoutMs:r,remaining:t,warnings:n}}function f3(e){if(!/^-?\d+$/.test(e))return{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (expected positive integer seconds); using default.`};let t=Number(e);return!Number.isFinite(t)||t<1?{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (must be >= 1 second); using default.`}:{ok:!0,value:t*1e3}}function p3(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
6643
6643
 
6644
6644
  mcp invoke <name> List tools on <name>.
6645
6645
  mcp invoke <name> <tool> --help Show flags for <tool>.
@@ -6669,7 +6669,7 @@ Arguments are coerced according to the tool's JSON Schema:
6669
6669
 
6670
6670
  Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
6671
6671
  OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
6672
- `);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-BFnnJUNc.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-CwkA0GJk.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return e3(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BXN2qRve.js`).then(e=>e.n),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>w3(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return e3(`mcp refresh: server "${n}" returned 401 — token may have expired. Run \`mcp auth ${n}\` to re-authenticate.`);throw e}let u=await l.toolsList(),d=await l.appsList();await a(n,{...o,sessionId:void 0,tools:u,apps:d,lastRefreshedAt:new Date().toISOString()},t.fs);let f=await N3(n,d,t);return $4(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function S3(e,t){if(e.includes(`--help`)||e.includes(`-h`))return $4(`usage: mcp auth <name> [--silent | --interactive]
6672
+ `);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-BCQiQFKs.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-CguDkxqH.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return e3(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BXN2qRve.js`).then(e=>e.n),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>w3(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return e3(`mcp refresh: server "${n}" returned 401 — token may have expired. Run \`mcp auth ${n}\` to re-authenticate.`);throw e}let u=await l.toolsList(),d=await l.appsList();await a(n,{...o,sessionId:void 0,tools:u,apps:d,lastRefreshedAt:new Date().toISOString()},t.fs);let f=await N3(n,d,t);return $4(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function S3(e,t){if(e.includes(`--help`)||e.includes(`-h`))return $4(`usage: mcp auth <name> [--silent | --interactive]
6673
6673
 
6674
6674
  Re-authenticate an existing MCP server. By default, attempts a silent
6675
6675
  token renewal using the persisted refresh_token; if that returns no
@@ -6681,7 +6681,7 @@ Options:
6681
6681
  -i, --interactive Skip silent renewal and open the OAuth popup
6682
6682
  directly. Use after revoking a refresh token or
6683
6683
  when the AS no longer accepts the cached one.
6684
- `);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return e3(`mcp auth: expected <name>`);let r=n[0],i=e.includes(`--silent`)||e.includes(`-s`),a=e.includes(`--interactive`)||e.includes(`-i`);if(i&&a)return e3(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-BFnnJUNc.js`),s=await o(r),{getServer:c}=await import(`./store-CwkA0GJk.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return e3(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return e3(`mcp auth: server "${r}" does not use OAuth`);if(!s)return e3(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-CfZWac9Z.js`).then(e=>e.r),f=d(u);if(!f)return e3(`mcp auth: provider "${u}" is not registered`);if(a)return await C3(r,f,t);if(!f.onSilentRenew)return i?e3(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await C3(r,f,t);let p=null;try{p=await f.onSilentRenew()}catch(e){let t=e instanceof Error?e.message:String(e);if(i)return e3(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);Z4.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?$4(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?e3(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await C3(r,f,t)}async function C3(e,t,n){if(!t.onOAuthLogin)return e3(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await T3(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?$4(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):e3(`mcp auth: interactive login for "${e}" did not complete`)}async function w3(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./provider-settings-FRENlwq7.js`),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-CfZWac9Z.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){Z4.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function T3(){let{createOAuthLauncher:e}=await import(`./oauth-service-bKcyWLK0.js`);return e()}async function E3(){if(Nt()){let e=chrome;return e.identity?.getRedirectURL?.(`mcp-callback`)??`https://${e.runtime?.id??``}.chromiumapp.org/mcp-callback`}let{getOAuthPageOrigin:e}=await import(`./oauth-service-bKcyWLK0.js`),{origin:t}=await e();return`${t}/auth/callback`}async function D3(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-GabK83LB.js`).then(e=>e.o),n=t();return async(e,t)=>{let r=await n(e,{method:t?.method,headers:t?.headers,body:t?.body}),i=new TextDecoder().decode(r.body);return{ok:r.status>=200&&r.status<300,status:r.status,statusText:r.statusText,text:async()=>i,json:async()=>JSON.parse(i),headers:{get:e=>r.headers[e.toLowerCase()]??null}}}}async function O3(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-C5eoK5vJ.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await import(`./global-db-DvmmimLY.js`).then(e=>e.n);return await t.create({dbName:n})}function k3(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
6684
+ `);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return e3(`mcp auth: expected <name>`);let r=n[0],i=e.includes(`--silent`)||e.includes(`-s`),a=e.includes(`--interactive`)||e.includes(`-i`);if(i&&a)return e3(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-BCQiQFKs.js`),s=await o(r),{getServer:c}=await import(`./store-CguDkxqH.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return e3(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return e3(`mcp auth: server "${r}" does not use OAuth`);if(!s)return e3(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-BwP_K_jW.js`).then(e=>e.r),f=d(u);if(!f)return e3(`mcp auth: provider "${u}" is not registered`);if(a)return await C3(r,f,t);if(!f.onSilentRenew)return i?e3(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await C3(r,f,t);let p=null;try{p=await f.onSilentRenew()}catch(e){let t=e instanceof Error?e.message:String(e);if(i)return e3(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);Z4.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?$4(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?e3(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await C3(r,f,t)}async function C3(e,t,n){if(!t.onOAuthLogin)return e3(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await T3(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?$4(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):e3(`mcp auth: interactive login for "${e}" did not complete`)}async function w3(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./provider-settings-VxXaQXu5.js`),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-BwP_K_jW.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){Z4.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function T3(){let{createOAuthLauncher:e}=await import(`./oauth-service-bKcyWLK0.js`);return e()}async function E3(){if(Nt()){let e=chrome;return e.identity?.getRedirectURL?.(`mcp-callback`)??`https://${e.runtime?.id??``}.chromiumapp.org/mcp-callback`}let{getOAuthPageOrigin:e}=await import(`./oauth-service-bKcyWLK0.js`),{origin:t}=await e();return`${t}/auth/callback`}async function D3(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-GabK83LB.js`).then(e=>e.o),n=t();return async(e,t)=>{let r=await n(e,{method:t?.method,headers:t?.headers,body:t?.body}),i=new TextDecoder().decode(r.body);return{ok:r.status>=200&&r.status<300,status:r.status,statusText:r.statusText,text:async()=>i,json:async()=>JSON.parse(i),headers:{get:e=>r.headers[e.toLowerCase()]??null}}}}async function O3(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-CvnWZ6Jt.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await import(`./global-db-DvmmimLY.js`).then(e=>e.n);return await t.create({dbName:n})}function k3(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
6685
6685
  // Auto-generated by \`mcp add ${e}\`; do not edit by hand.
6686
6686
  const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
6687
6687
  const escape = (s) => {
@@ -6695,7 +6695,7 @@ const r = await exec(cmd);
6695
6695
  if (r.stdout) process.stdout.write(r.stdout);
6696
6696
  if (r.stderr) process.stderr.write(r.stderr);
6697
6697
  process.exit(r.exitCode || 0);
6698
- `}async function A3(e,t){let n=await O3(t.fs);await n.mkdir(Q4,{recursive:!0}),await n.writeFile(`${Q4}/${e}.jsh`,k3(e)),t.scriptCatalog?.invalidateJsh()}async function j3(e,t){let n=await O3(t.fs),r=`${Q4}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){Z4.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function M3(e,t){let{removeAppSprinkles:n}=await import(`./apps-AV5a8hlw.js`);await n(e,t.fs)}async function N3(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-AV5a8hlw.js`);return(await r(e,t,n.fs)).length}catch(t){return Z4.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}const P3=`/.cache/artificial-analysis.json`;async function F3(e,t=!1){if(e&&!t)try{let t=await e.readFile(P3),n=JSON.parse(t);if(Date.now()-n.fetchedAt<864e5)return n.models}catch{}let n=null;try{n=localStorage.getItem(`aa_api_key`)}catch{}let r={Accept:`application/json`};n&&(r[`x-api-key`]=n);let i=Dt(),a;try{a=await i(`https://artificialanalysis.ai/api/v2/data/llms/models`,{method:`GET`,headers:r})}catch{return[]}if(a.status===401||a.status<200||a.status>=300)return[];let o;try{let e=new TextDecoder().decode(a.body);o=JSON.parse(e)}catch{return[]}let s=(Array.isArray(o)?o:o?.data??o?.models??[]).map(e=>({slug:e.slug??``,name:e.name??``,creator_slug:e.model_creator?.slug??``,intelligence_index:e.evaluations?.artificial_analysis_intelligence_index??null,coding_index:e.evaluations?.artificial_analysis_coding_index??null,speed_tps:e.median_output_tokens_per_second??null}));if(e&&s.length>0){let t={fetchedAt:Date.now(),models:s};try{await e.mkdir(`/.cache`,{recursive:!0}),await e.writeFile(P3,JSON.stringify(t))}catch{}}return s}function I3(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function L3(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=I3(e),a=t.find(e=>I3(e.slug)===i);if(a)return a;let o=t.filter(e=>n.includes(e.slug)||e.slug.includes(n));if(o.length>0)return o.sort((e,t)=>t.slug.length-e.slug.length),o[0]}function R3(){return`models - list available LLM models
6698
+ `}async function A3(e,t){let n=await O3(t.fs);await n.mkdir(Q4,{recursive:!0}),await n.writeFile(`${Q4}/${e}.jsh`,k3(e)),t.scriptCatalog?.invalidateJsh()}async function j3(e,t){let n=await O3(t.fs),r=`${Q4}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){Z4.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function M3(e,t){let{removeAppSprinkles:n}=await import(`./apps-Bie0e1m2.js`);await n(e,t.fs)}async function N3(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-Bie0e1m2.js`);return(await r(e,t,n.fs)).length}catch(t){return Z4.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}const P3=`/.cache/artificial-analysis.json`;async function F3(e,t=!1){if(e&&!t)try{let t=await e.readFile(P3),n=JSON.parse(t);if(Date.now()-n.fetchedAt<864e5)return n.models}catch{}let n=null;try{n=localStorage.getItem(`aa_api_key`)}catch{}let r={Accept:`application/json`};n&&(r[`x-api-key`]=n);let i=Dt(),a;try{a=await i(`https://artificialanalysis.ai/api/v2/data/llms/models`,{method:`GET`,headers:r})}catch{return[]}if(a.status===401||a.status<200||a.status>=300)return[];let o;try{let e=new TextDecoder().decode(a.body);o=JSON.parse(e)}catch{return[]}let s=(Array.isArray(o)?o:o?.data??o?.models??[]).map(e=>({slug:e.slug??``,name:e.name??``,creator_slug:e.model_creator?.slug??``,intelligence_index:e.evaluations?.artificial_analysis_intelligence_index??null,coding_index:e.evaluations?.artificial_analysis_coding_index??null,speed_tps:e.median_output_tokens_per_second??null}));if(e&&s.length>0){let t={fetchedAt:Date.now(),models:s};try{await e.mkdir(`/.cache`,{recursive:!0}),await e.writeFile(P3,JSON.stringify(t))}catch{}}return s}function I3(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function L3(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=I3(e),a=t.find(e=>I3(e.slug)===i);if(a)return a;let o=t.filter(e=>n.includes(e.slug)||e.slug.includes(n));if(o.length>0)return o.sort((e,t)=>t.slug.length-e.slug.length),o[0]}function R3(){return`models - list available LLM models
6699
6699
 
6700
6700
  Usage: models [options]
6701
6701
 
@@ -6709,7 +6709,7 @@ Options:
6709
6709
  -h, --help Show this help message
6710
6710
  `}function z3(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function B3(e){return`$${e.toFixed(2)}`}const V3=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function H3(e){let t=`${e.id} ${e.name??``}`;return!V3.test(t)}function U3(e){let t=e.toLowerCase();t=t.replace(/-\d{8}$/,``),t=t.replace(/-\d{4}$/,``),t=t.replace(/-(preview|latest)$/,``);let n=t.match(/^(claude-(?:opus|sonnet|haiku))/);if(n)return n[1];let r=t.match(/^(gpt-\d+)(?:\.\d+)?(-[a-z][-a-z]*)?$/);if(r)return r[1]+(r[2]??``);let i=t.match(/^gemini-[\d.]+-(.+)$/);if(i)return`gemini-${i[1]}`;let a=t.match(/^gemini-(\d+)-(.+)$/);if(a)return`gemini-${a[2]}`;let o=t.match(/^grok-[\d.]+-([\w-]+)$/);if(o)return`grok-${o[1]}`;if(t.match(/^(grok)-[\d.]+$/))return`grok`;let s=t.match(/^(o\d+(?:-[a-z]+)?)(?:-\d.*)?$/);return s?s[1]:t.replace(/-[\d.]+$/,``)}function W3(e){let t=new Map;for(let n of e){let e=U3(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function G3(e,t,n,r,i){let a=i?L3(e.id,i):void 0,o={id:e.id,name:e.name,provider:t,cost:e.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??0,maxTokens:e.maxTokens??0,reasoning:!!e.reasoning,input:e.input??[`text`],selected:e.id===n&&t===r};return a?.intelligence_index!=null&&(o.intelligence=a.intelligence_index),a?.coding_index!=null&&(o.codingScore=a.coding_index),a?.speed_tps!=null&&(o.speed=a.speed_tps),o}function K3(e,t,n,r){let i=[];i.push(`Models for "${e}" (${t}):\n`);for(let e of n){let t=e.selected?` ► `:` `,n=e.id.padEnd(30),r=`${B3(e.cost.input)} / ${B3(e.cost.output)}`,a=`${z3(e.contextWindow)} ctx`,o=e.intelligence==null?``:`IQ:${e.intelligence}`,s=e.speed==null?``:`${Math.round(e.speed)} t/s`,c=e.reasoning?`reasoning`:``,l=o||s?`${o.padEnd(6)} ${s.padEnd(8)}`:``;i.push(`${t}${n} ${r.padEnd(16)} ${a.padEnd(10)} ${l} ${c}`)}return i.push(`\n ${n.length} model${n.length===1?``:`s`} available.`),r&&i.push(` Intelligence data: artificialanalysis.ai`),i.join(`
6711
6711
  `)+`
6712
- `}function q3(e){return W(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-FRENlwq7.js`);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:R3(),stderr:``,exitCode:0};let l=t.includes(`--json`),u=t.includes(`--all`),d=t.includes(`--all-versions`),f=t.includes(`--refresh`),p=t.includes(`--no-benchmarks`),m=t.indexOf(`--provider`),h=m>=0?t[m+1]:void 0,g=o(),_=s(),v=n();if(v.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
6712
+ `}function q3(e){return W(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-VxXaQXu5.js`);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:R3(),stderr:``,exitCode:0};let l=t.includes(`--json`),u=t.includes(`--all`),d=t.includes(`--all-versions`),f=t.includes(`--refresh`),p=t.includes(`--no-benchmarks`),m=t.indexOf(`--provider`),h=m>=0?t[m+1]:void 0,g=o(),_=s(),v=n();if(v.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
6713
6713
  `,exitCode:1};let y=c(),b=y.id,x=y.provider,S;p||(S=await F3(e,f),S.length===0&&(S=void 0));let C;if(h){let e=r();if(!e.includes(h))return{stdout:``,stderr:`Unknown provider: ${h}. Available: ${e.join(`, `)}\n`,exitCode:1};C=[h]}else C=u?[...new Set(v.map(e=>e.providerId))]:[g];let w=[],T=[];for(let e of C){let t=a(e).filter(H3);if(t.length===0){if(!u)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>G3(t,e,b,x,S)).sort((e,t)=>t.cost.input-e.cost.input);if(d||(n=W3(n)),w.push(...n),!l){let t=i(e);T.push(K3(t.name,e,n,!!S))}}if(l)return{stdout:JSON.stringify(w,null,2)+`
6714
6714
  `,stderr:``,exitCode:0};!d&&!l&&T.push(`Showing latest versions only. Use --all-versions to see all.
6715
6715
  `);let E=`${x}:${b}`,D=`${g}:${_}`;return T.push(E===D?`Currently using: ${E}\n`:`Currently using: ${E} (selected ${D} — resolved to a different model)\n`),{stdout:T.join(`
@@ -6749,7 +6749,7 @@ Examples:
6749
6749
  oauth-domain add adobe '*.da.live'
6750
6750
  oauth-domain list adobe
6751
6751
  oauth-domain remove adobe admin.da.live
6752
- `}function n6(){return W(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:t6(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-FRENlwq7.js`),[i,a,o]=e;try{switch(i){case`list`:{if(a){let e=t(a);return e.length===0?{stdout:`(no extra domains configured for ${a})\n`,stderr:``,exitCode:0}:{stdout:e.join(`
6752
+ `}function n6(){return W(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:t6(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-VxXaQXu5.js`),[i,a,o]=e;try{switch(i){case`list`:{if(a){let e=t(a);return e.length===0?{stdout:`(no extra domains configured for ${a})\n`,stderr:``,exitCode:0}:{stdout:e.join(`
6753
6753
  `)+`
6754
6754
  `,stderr:``,exitCode:0}}let e=r(),n=Object.entries(e).filter(([,e])=>e.length>0);return n.length===0?{stdout:`(no extra OAuth domains configured)
6755
6755
  `,stderr:``,exitCode:0}:{stdout:n.map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
@@ -6813,7 +6813,7 @@ Examples:
6813
6813
  --authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
6814
6814
  --redirect-pattern 'http://127.0.0.1:56121/*'
6815
6815
  curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
6816
- `}function i6(){return W(`oauth-token`,a6)}async function a6(e,t){let n=await import(`./provider-settings-FRENlwq7.js`),r=await import(`./providers-CfZWac9Z.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:r6(),stderr:``,exitCode:0};if(e.includes(`--list`))return D6(n.getAccounts,r.getRegisteredProviderIds,r.getRegisteredProviderConfig,n.getOAuthAccountInfo);if(e.includes(`--expire`))return _6(e);if(e.includes(`--renew`))return v6(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return b6(e,t);let i=o6(e);if(!i.ok)return i.result;let a=s6(e,n,r);if(!a.ok)return a.result;let o=l6(a.value,r.getRegisteredProviderConfig);if(!o.ok)return o.result;if(!i.value){let e=await u6(a.value,o.value,n.getOAuthAccountInfo);if(e)return e}return f6(a.value,o.value,i.value,n.getOAuthAccountInfo)}function o6(e){let t=e.indexOf(`--scope`);if(t<0)return{ok:!0,value:void 0};let n=e[t+1]?.trim();return!n||n.startsWith(`-`)?{ok:!1,result:E6(`oauth-token: --scope requires a value`)}:(e.splice(t,2),{ok:!0,value:n})}function s6(e,t,n){let r=e.indexOf(`--provider`);if(r>=0){let t=e[r+1];return t?{ok:!0,value:t}:{ok:!1,result:E6(`oauth-token: --provider requires a value`)}}if(e.length>0)return{ok:!0,value:e[0]};let i=t.getSelectedProvider();if(c6(n.getRegisteredProviderConfig(i)))return{ok:!0,value:i};let a=n.getRegisteredProviderIds().find(e=>c6(n.getRegisteredProviderConfig(e)));return a?{ok:!0,value:a}:{ok:!1,result:E6(`oauth-token: no OAuth providers configured`)}}function c6(e){return!!(e?.isOAuth&&(e.onOAuthLogin||e.onOAuthLoginIntercepted))}function l6(e,t){let n=t(e);return n?c6(n)?{ok:!0,value:n}:{ok:!1,result:E6(`oauth-token: provider "${e}" is not an OAuth provider`)}:{ok:!1,result:E6(`oauth-token: unknown provider "${e}"`)}}async function u6(e,t,n){let r=n(e);return r&&!r.expired?d6(e,r.maskedValue):!r?.expired||!t.onSilentRenew?null:h6(e,t.onSilentRenew,n)}function d6(e,t){return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:E6(`oauth-token: no masked value for ${e} (try logging in again)`)}async function f6(e,t,n,r){try{return await p6(e,t,n)||m6(e,r)}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(`[oauth-token] Provider ${e}: login failed:`,n),E6(`oauth-token: login failed: ${n}`)}}async function p6(e,t,n){let r=n?{scopes:n}:void 0;if(t.onOAuthLoginIntercepted){let{createInterceptingOAuthLauncherForCurrentRuntime:n}=await import(`./oauth-service-bKcyWLK0.js`),i=await n();return i?(await t.onOAuthLoginIntercepted(i,()=>{},r),null):E6(`oauth-token: provider "${e}" needs the controlled-browser interceptor, but no CDP transport is available in this runtime.`)}if(t.onOAuthLogin){let{createOAuthLauncher:e}=await import(`./oauth-service-bKcyWLK0.js`);return await t.onOAuthLogin(e(),()=>{},r),null}return E6(`oauth-token: provider "${e}" has no OAuth login hook`)}function m6(e,t){let n=t(e);return n?.token?d6(e,n.maskedValue):(console.error(`[oauth-token] Provider ${e}: login completed but no token was saved`),E6(`oauth-token: login completed but no token was saved`))}async function h6(e,t,n){try{return await t()===null?null:d6(e,n(e)?.maskedValue)}catch{return null}}function g6(e,t,n,r){let i=e.filter(e=>!e.startsWith(`-`))[0];if(i)return i;let a=t();return n(a)?.onSilentRenew?a:r().find(e=>n(e)?.onSilentRenew)}async function _6(e){let{getAccounts:t,getSelectedProvider:n,saveOAuthAccount:r}=await import(`./provider-settings-FRENlwq7.js`),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await import(`./providers-CfZWac9Z.js`).then(e=>e.r),o=g6(e,n,i,a);if(!o)return E6(`oauth-token --expire: no provider supports silent renewal`);let s=i(o);if(!s)return E6(`oauth-token --expire: unknown provider "${o}"`);if(!s.onSilentRenew)return E6(`oauth-token --expire: provider "${o}" has no onSilentRenew hook`);let c=t().find(e=>e.providerId===o);if(!c?.accessToken)return E6(`oauth-token --expire: no stored OAuth account for "${o}"`);try{await r({...c,accessToken:c.accessToken,tokenExpiresAt:Date.now()-1e3})}catch(e){return E6(`oauth-token --expire: failed to update "${o}": ${e instanceof Error?e.message:String(e)}`)}return{stdout:`oauth-token ${o}: stored token marked expired; next network op will trigger silent renewal.\n`,stderr:``,exitCode:0}}async function v6(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./provider-settings-FRENlwq7.js`),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-CfZWac9Z.js`).then(e=>e.r),a=g6(e,t,r,i);if(!a)return E6(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return E6(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return E6(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${y6(s)}`);let u=null,d=null;try{u=await o.onSilentRenew()}catch(e){d=e instanceof Error?e.message:String(e)}if(d)l.push(` silent renewal: ERROR — ${d}`);else if(u){let e=n(a),t=!!(c&&e?.token&&c!==e.token);l.push(` silent renewal: SUCCESS${t?` — token refreshed`:` (token unchanged)`}`),l.push(` after: ${y6(e)}`)}else l.push(` silent renewal: FAILED (onSilentRenew returned null)`),l.push(` → no window should have appeared. Open DevTools console and`),l.push(` look for "[oauth-service] Extension OAuth error" / "[adobe]" to see`),l.push(` the IMS/Chrome reason (e.g. login_required).`);return{stdout:l.join(`
6816
+ `}function i6(){return W(`oauth-token`,a6)}async function a6(e,t){let n=await import(`./provider-settings-VxXaQXu5.js`),r=await import(`./providers-BwP_K_jW.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:r6(),stderr:``,exitCode:0};if(e.includes(`--list`))return D6(n.getAccounts,r.getRegisteredProviderIds,r.getRegisteredProviderConfig,n.getOAuthAccountInfo);if(e.includes(`--expire`))return _6(e);if(e.includes(`--renew`))return v6(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return b6(e,t);let i=o6(e);if(!i.ok)return i.result;let a=s6(e,n,r);if(!a.ok)return a.result;let o=l6(a.value,r.getRegisteredProviderConfig);if(!o.ok)return o.result;if(!i.value){let e=await u6(a.value,o.value,n.getOAuthAccountInfo);if(e)return e}return f6(a.value,o.value,i.value,n.getOAuthAccountInfo)}function o6(e){let t=e.indexOf(`--scope`);if(t<0)return{ok:!0,value:void 0};let n=e[t+1]?.trim();return!n||n.startsWith(`-`)?{ok:!1,result:E6(`oauth-token: --scope requires a value`)}:(e.splice(t,2),{ok:!0,value:n})}function s6(e,t,n){let r=e.indexOf(`--provider`);if(r>=0){let t=e[r+1];return t?{ok:!0,value:t}:{ok:!1,result:E6(`oauth-token: --provider requires a value`)}}if(e.length>0)return{ok:!0,value:e[0]};let i=t.getSelectedProvider();if(c6(n.getRegisteredProviderConfig(i)))return{ok:!0,value:i};let a=n.getRegisteredProviderIds().find(e=>c6(n.getRegisteredProviderConfig(e)));return a?{ok:!0,value:a}:{ok:!1,result:E6(`oauth-token: no OAuth providers configured`)}}function c6(e){return!!(e?.isOAuth&&(e.onOAuthLogin||e.onOAuthLoginIntercepted))}function l6(e,t){let n=t(e);return n?c6(n)?{ok:!0,value:n}:{ok:!1,result:E6(`oauth-token: provider "${e}" is not an OAuth provider`)}:{ok:!1,result:E6(`oauth-token: unknown provider "${e}"`)}}async function u6(e,t,n){let r=n(e);return r&&!r.expired?d6(e,r.maskedValue):!r?.expired||!t.onSilentRenew?null:h6(e,t.onSilentRenew,n)}function d6(e,t){return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:E6(`oauth-token: no masked value for ${e} (try logging in again)`)}async function f6(e,t,n,r){try{return await p6(e,t,n)||m6(e,r)}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(`[oauth-token] Provider ${e}: login failed:`,n),E6(`oauth-token: login failed: ${n}`)}}async function p6(e,t,n){let r=n?{scopes:n}:void 0;if(t.onOAuthLoginIntercepted){let{createInterceptingOAuthLauncherForCurrentRuntime:n}=await import(`./oauth-service-bKcyWLK0.js`),i=await n();return i?(await t.onOAuthLoginIntercepted(i,()=>{},r),null):E6(`oauth-token: provider "${e}" needs the controlled-browser interceptor, but no CDP transport is available in this runtime.`)}if(t.onOAuthLogin){let{createOAuthLauncher:e}=await import(`./oauth-service-bKcyWLK0.js`);return await t.onOAuthLogin(e(),()=>{},r),null}return E6(`oauth-token: provider "${e}" has no OAuth login hook`)}function m6(e,t){let n=t(e);return n?.token?d6(e,n.maskedValue):(console.error(`[oauth-token] Provider ${e}: login completed but no token was saved`),E6(`oauth-token: login completed but no token was saved`))}async function h6(e,t,n){try{return await t()===null?null:d6(e,n(e)?.maskedValue)}catch{return null}}function g6(e,t,n,r){let i=e.filter(e=>!e.startsWith(`-`))[0];if(i)return i;let a=t();return n(a)?.onSilentRenew?a:r().find(e=>n(e)?.onSilentRenew)}async function _6(e){let{getAccounts:t,getSelectedProvider:n,saveOAuthAccount:r}=await import(`./provider-settings-VxXaQXu5.js`),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await import(`./providers-BwP_K_jW.js`).then(e=>e.r),o=g6(e,n,i,a);if(!o)return E6(`oauth-token --expire: no provider supports silent renewal`);let s=i(o);if(!s)return E6(`oauth-token --expire: unknown provider "${o}"`);if(!s.onSilentRenew)return E6(`oauth-token --expire: provider "${o}" has no onSilentRenew hook`);let c=t().find(e=>e.providerId===o);if(!c?.accessToken)return E6(`oauth-token --expire: no stored OAuth account for "${o}"`);try{await r({...c,accessToken:c.accessToken,tokenExpiresAt:Date.now()-1e3})}catch(e){return E6(`oauth-token --expire: failed to update "${o}": ${e instanceof Error?e.message:String(e)}`)}return{stdout:`oauth-token ${o}: stored token marked expired; next network op will trigger silent renewal.\n`,stderr:``,exitCode:0}}async function v6(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./provider-settings-VxXaQXu5.js`),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-BwP_K_jW.js`).then(e=>e.r),a=g6(e,t,r,i);if(!a)return E6(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return E6(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return E6(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${y6(s)}`);let u=null,d=null;try{u=await o.onSilentRenew()}catch(e){d=e instanceof Error?e.message:String(e)}if(d)l.push(` silent renewal: ERROR — ${d}`);else if(u){let e=n(a),t=!!(c&&e?.token&&c!==e.token);l.push(` silent renewal: SUCCESS${t?` — token refreshed`:` (token unchanged)`}`),l.push(` after: ${y6(e)}`)}else l.push(` silent renewal: FAILED (onSilentRenew returned null)`),l.push(` → no window should have appeared. Open DevTools console and`),l.push(` look for "[oauth-service] Extension OAuth error" / "[adobe]" to see`),l.push(` the IMS/Chrome reason (e.g. login_required).`);return{stdout:l.join(`
6817
6817
  `)+`
6818
6818
  `,stderr:``,exitCode:+!u}}function y6(e){if(!e)return`no token`;if(e.expired)return`expired`;if(e.expiresAt){let t=e.expiresAt-Date.now();if(t>0){let e=Math.floor(t/36e5),n=Math.floor(t%36e5/6e4);return e>0?`valid, expires in ${e}h ${n}m`:`valid, expires in ${n}m`}}return`valid`}async function b6(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-CaCw-rJ5.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-bKcyWLK0.js`),i=await x6(e,t);if(!i.ok)return i.result;let a=n(i.value);if(!a.ok)return E6(`oauth-token: invalid intercept config: ${a.error}`);let o=await r();if(!o)return E6(`oauth-token: no CDP transport available in this runtime; --intercept needs the controlled browser.`);let s=await o(a.config);return s?{stdout:`${s}\n`,stderr:``,exitCode:0}:E6(`oauth-token: intercept timed out or was cancelled`)}function x6(e,t){let n=e.indexOf(`--from-file`);return n>=0?S6(e[n+1],t):C6(e)}async function S6(e,t){if(!e)return{ok:!1,result:E6(`oauth-token: --from-file requires a path`)};try{let n=t.fs.resolvePath(t.cwd,e),r=await t.fs.readFile(n),i=typeof r==`string`?r:new TextDecoder().decode(r);return{ok:!0,value:JSON.parse(i)}}catch(t){return{ok:!1,result:E6(`oauth-token: failed to read ${e}: ${t instanceof Error?t.message:String(t)}`)}}}function C6(e){let t=T6(e,`--authorize-url`),n=T6(e,`--redirect-pattern`);if(!t)return{ok:!1,result:E6(`oauth-token: --authorize-url is required`)};if(!n)return{ok:!1,result:E6(`oauth-token: --redirect-pattern is required`)};let r=w6(e);return r.ok?{ok:!0,value:{authorizeUrl:t,redirectUriPattern:n,onCapture:e.includes(`--leave-tab`)?`leave`:`close`,...r.value.length>0?{rewrite:r.value}:{}}}:r}function w6(e){let t=[];for(let n=0;n<e.length;n++){if(e[n]!==`--rewrite`)continue;let r=e[n+1];if(!r)return{ok:!1,result:E6(`oauth-token: --rewrite requires a value`)};let i=r.split(`=`);if(i.length<3)return{ok:!1,result:E6(`oauth-token: --rewrite "${r}" must be "<match>=<key>=<value>"`)};let[a,o,...s]=i;t.push({match:a,appendParams:{[o]:s.join(`=`)}})}return{ok:!0,value:t}}function T6(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function E6(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function D6(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
6819
6819
  `,stderr:``,exitCode:0};let a=[];for(let e of i){let t=r(e);if(!t)a.push(`${e} (no token)`);else if(t.expired){let n=t.userName?` as ${t.userName}`:``;a.push(`${e} (expired${n})`)}else{let n=[];if(t.userName?n.push(`logged in as ${t.userName}`):n.push(`logged in`),t.expiresAt){let e=t.expiresAt-Date.now();if(e>0){let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4);t>0?n.push(`expires in ${t}h`):n.push(`expires in ${r}m`)}}a.push(`${e} (${n.join(`, `)})`)}}return{stdout:a.join(`
@@ -8545,8 +8545,8 @@ ${e}
8545
8545
  ---
8546
8546
  ${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
8547
8547
  ${t}
8548
- ---`);let a=rb(n);return a&&(i+=a),i}};const R9=r(`scoop-lifecycle-manager`);var joe=class{deps;tabs=new Map;contexts=new Map;scoopObservers=new Map;constructor(e){this.deps=e}getContexts(){return this.contexts}getContext(e){return this.contexts.get(e)}getTab(e){return this.tabs.get(e)}observe(e,t){let n=this.scoopObservers.get(e);return n||(n=new Set,this.scoopObservers.set(e,n)),n.add(t),()=>{let n=this.scoopObservers.get(e);n&&(n.delete(t),n.size===0&&this.scoopObservers.delete(e))}}dispatch(e,t,...n){let r=this.scoopObservers.get(e);if(r)for(let i of r){let r=i[t];if(r)try{r(...n)}catch(n){R9.warn(`scoop observer threw`,{jid:e,event:t,error:n instanceof Error?n.message:String(n)})}}}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager(),n=this.deps.getSharedFs();if(!(!t||!n))try{let r=`/scoops/${e.folder}/etc/sudoers`;await n.exists(r)?await t.reloadScoopPolicyByFolder(e.folder):await t.seedScoopSudoers(e.folder,e.config)}catch(t){R9.warn(`Failed to seed per-scoop sudoers; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)R9.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{R9.debug(`Context already exists`,{jid:e});return}let n=this.deps.getSharedFs();if(!n)throw Error(`Shared filesystem not initialized`);let r=`scoop-${t.folder}-${Date.now()}`,i=t.isCone?n:new nr(n,t.config?.writablePaths?[...t.config.writablePaths]:[],t.config?.visiblePaths?[...t.config.visiblePaths]:[],`sudo-delegated`);t.isCone||await this.ensureSudoersLoaded(t);let a=this.buildContextCallbacks(e,t),o=Array.from(this.deps.getScoops().values()).find(e=>e.isCone)?.jid,s=new Aoe(t,a,i,this.deps.getSessionStore()??void 0,n??void 0,o,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());this.contexts.set(e,s),this.tabs.set(e,{jid:e,contextId:r,status:`initializing`,lastActivity:new Date().toISOString()}),await s.init();let c=this.tabs.get(e);c&&c.status===`initializing`&&(c.status=`ready`,this.tabs.set(e,c),this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{R9.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let l=this.deps.getScoops().get(e);l&&!l.isCone&&this.deps.idleTimers.start(e),R9.info(`Scoop context created`,{jid:e,contextId:r})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),this.scoopObservers.delete(e),R9.info(`Scoop context destroyed`,{jid:e}))}forgetObservers(e){this.scoopObservers.delete(e)}getTabsMap(){return this.tabs}setTab(e,t){this.tabs.set(e,t)}markTabError(e,t){let n=this.tabs.get(e);this.tabs.set(e,{jid:e,contextId:n?.contextId??`scoop-error-${e}`,status:`error`,error:t,lastActivity:new Date().toISOString()})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let[e,t]of this.contexts.entries())this.deps.idleTimers.clear(e),t.stop(),this.contexts.delete(e)}async destroyAllTabs(){for(let e of Array.from(this.contexts.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.tabs.get(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return R9.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.contexts.get(e);o||=(await this.createTab(e),this.contexts.get(e));let s=this.tabs.get(e);if(s?.status===`initializing`){if(R9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){R9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}o=this.contexts.get(e),s=this.tabs.get(e)}if(!o){R9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),s&&(s.status=`processing`,s.lastActivity=new Date().toISOString(),this.tabs.set(e,s),this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),R9.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await o.prompt(t,i,a)}async register(e){let t=this.deps.getScoops();await this.deps.db.saveScoop(e),t.set(e.jid,e),this.deps.messageRouter.ensureQueue(e.jid),R9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.isCone||Vt(`spawn`,e.folder)}catch(n){R9.error(`Scoop init failed`,{jid:e.jid,name:e.name,error:n instanceof Error?n.message:String(n)});try{this.destroyTab(e.jid)}catch(t){R9.warn(`Failed to destroy scoop runtime during init rollback`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}throw t.delete(e.jid),this.deps.messageRouter.forgetScoop(e.jid),await this.deps.db.deleteScoop(e.jid).catch(t=>{R9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}async unregister(e){let t=this.deps.getScoops(),n=t.get(e),r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=await r.getLicksForScoopFromDb(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.dropForScoop(e).catch(t=>{R9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.deps.idleTimers.clear(e),this.destroyTab(e),this.deps.getSessionStore()?.delete(e).catch(t=>{R9.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.scoopObservers.delete(e),this.deps.completionService.forgetScoop(e,`unregister`);let a=this.deps.approvalRouter.failScoop(e);if(a>0&&R9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),R9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){R9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}updateModelOnAll(){for(let e of this.contexts.values())e.updateModel();R9.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{R9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),R9.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.contexts.get(e),a=i?i.setThinkingLevel(t,n):null;if(t===void 0){if(r.config&&r.config.thinkingLevel!==void 0){let{thinkingLevel:e,effortOverride:t,...n}=r.config;r.config=n}}else r.config={...r.config??{},thinkingLevel:t,effortOverride:n};try{await this.deps.db.saveScoop(r)}catch(t){R9.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops();return{onResponse:(i,o)=>{a().has(e)&&(n.onResponse(e,i,o),this.dispatch(e,`onResponse`,i,o),t.isCone||(o?r.appendResponseChunk(e,i):r.setResponseFull(e,i)))},onResponseDone:()=>{if(!a().has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),n.onResponseDone(e)},onError:r=>{if(!a().has(e))return;let i=this.tabs.get(e);i&&(i.status=`error`,i.error=r,this.tabs.set(e,i)),Vt(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`)},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:i=>{if(!a().has(e))return;let o=this.tabs.get(e);o&&(o.status=i,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o)),n.onStatusChange(e,i),this.dispatch(e,`onStatusChange`,i),i===`ready`&&this.deps.messageRouter.flushOnIdle(e),i===`ready`&&!t.isCone&&r.notifyCompletion(e)},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r)=>{n.onToolStart?.(e,t,r)},onToolEnd:(t,r,i)=>{n.onToolEnd?.(e,t,r,i)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i)},onToolUIDone:t=>{n.onToolUIDone?.(e,t)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return await i.registerScoop(n),n}:void 0,onDropScoop:t.isCone?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:t.isCone?e=>i.muteScoops(e):void 0,onUnmuteScoops:t.isCone?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:t.isCone?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:t.isCone?e=>i.setGlobalMemory(e):void 0,appendConeMemory:t.isCone?(e,t)=>i.appendConeMemory(e,t):void 0,onSudoRequest:t.isCone?void 0:t=>i.enqueueSudoRequest(e,t),onSudoResolve:t.isCone?(e,t)=>i.resolveActionableLick(e,t):void 0,onListSudoRequests:t.isCone?()=>i.listPendingSudoRequests():void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);R9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),Vt(`error`,r.folder,t);let i=this.tabs.get(e);if(i&&(i.status=`error`,i.error=t,this.tabs.set(e,i)),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),r.isCone)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let a=Array.from(n.values()).find(e=>e.isCone);if(!a)return;let o={id:`scoop-error-${e}-${Date.now()}`,chatJid:a.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(a.jid,o)}catch(e){R9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(o).catch(e=>{R9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const z9=r(`scoop-message-router`);var Moe=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;debounceStates=new Map;processing=new Map;busyDeferrals=new Map;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.cancelDebounce(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.busyDeferrals.delete(e)}async handleMessage(e){if(z9.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)}),this.deps.isExternalLickChannel(e.channel))try{this.deps.notifyIncomingMessage(e.chatJid,e)}catch(t){z9.warn(`onIncomingMessage for external lick channel threw`,{channel:e.channel,error:t instanceof Error?t.message:String(t)})}await this.deps.db.saveMessage(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.deps.getScoops().get(e);if(!r)throw Error(`Scoop not found: ${e}`);Vt(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`delegation`};await this.deps.db.saveMessage(i),this.deps.notifyIncomingMessage(e,i),z9.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.deps.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);z9.error(`Delegation failed`,{scoopJid:e,error:n}),this.deps.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.deps.getScoops().get(e.chatJid);if(!t){z9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){z9.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let n=this.messageQueues.get(e.chatJid)??[];n.push(e),this.messageQueues.set(e.chatJid,n);let r=this.deps.getTabs().get(e.chatJid);if(z9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){z9.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),r=this.deps.getTabs().get(e.chatJid)}catch{z9.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}if(!(r?.status!==`ready`&&r?.status!==`processing`)){if(this.deps.isExternalLickChannel(e.channel)){await this.scheduleScoopQueue(e.chatJid,e.id);return}await this.flushScoopQueue(e.chatJid)}}passesTriggerGate(e,t){let n=t.channel===`webhook`||t.channel===`cron`||t.channel===`fswatch`||t.channel===`sprinkle`;return!e||e.isCone||!e.requiresTrigger||!e.trigger||n||t.content.includes(e.trigger)}scheduleScoopQueue(e,t){let n=this.debounceStates.get(e)??{startedAt:Date.now(),waiters:[]};n.timer!==void 0&&clearTimeout(n.timer);let r=new Promise((e,r)=>{n.waiters.push({messageId:t,resolve:e,reject:r})}),i=Math.max(0,3e3-(Date.now()-n.startedAt));return n.timer=setTimeout(()=>{n.timer=void 0,this.flushScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);z9.error(`Debounced message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},Math.min(1e3,i)),this.debounceStates.set(e,n),r}async flushScoopQueue(e){let t=this.takeDebounce(e);if(t&&this.processing.has(e)&&this.shouldDeferQueuedLicks(e)){for(let e of t.waiters)e.resolve();this.recordBusyDeferral(e);return}try{await this.processScoopQueue(e);for(let e of t?.waiters??[])e.resolve()}catch(e){for(let n of t?.waiters??[])n.reject(e);throw e}}async flushOnIdle(e){if(this.messageQueues.has(e))try{await this.flushScoopQueue(e)}catch(t){let n=t instanceof Error?t.message:String(t);z9.error(`Idle message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)}}shouldDeferQueuedLicks(e){let t=this.messageQueues.get(e);return t!==void 0&&t.length>0&&t.every(e=>this.deps.isExternalLickChannel(e.channel))}recordBusyDeferral(e){let t=this.busyDeferrals.get(e)??{startedAt:Date.now(),reported:!1};if(this.busyDeferrals.set(e,t),t.reported||Date.now()-t.startedAt<6e4)return;t.reported=!0;let n=`Lick queue remained deferred while scoop was busy for ${6e4/1e3}s`;z9.warn(`Busy lick queue may be starved`,{jid:e,error:n});try{this.deps.onError(e,n)}catch(t){z9.warn(`Busy lick queue error callback failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}}takeDebounce(e){let t=this.debounceStates.get(e);return t?.timer!==void 0&&clearTimeout(t.timer),this.debounceStates.delete(e),t}cancelDebounce(e){let t=this.takeDebounce(e);for(let e of t?.waiters??[])e.resolve()}cancelDebounces(){for(let e of this.debounceStates.keys())this.cancelDebounce(e)}cancelDebounceWaiter(e,t){let n=this.debounceStates.get(e);if(!n)return;let r=[];for(let e of n.waiters)e.messageId===t?e.resolve():r.push(e);n.waiters=r,r.length===0&&this.cancelDebounce(e)}async processScoopQueue(e){let t=this.processing.get(e);if(t){t.rerun=!0,await t.done.catch(()=>{});return}let n={rerun:!1,done:Promise.resolve()};return this.processing.set(e,n),n.done=this.drainScoopQueue(e,n),n.done}async drainScoopQueue(e,t){let n=!1,r;try{do{t.rerun=!1;try{await this.runScoopQueue(e)}catch(e){n||(n=!0,r=e)}}while(t.rerun)}finally{this.processing.delete(e)}if(n)throw r}async runScoopQueue(e){let t=this.messageQueues.get(e);if(!t){z9.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){z9.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.deps.getScoops().get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await this.deps.db.getMessagesSince(e,a,i),s=o.filter(e=>this.passesTriggerGate(r,e));if(z9.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,eligibleMessageCount:s.length,queueLength:t.length}),o.length===0){z9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.busyDeferrals.delete(e);return}if(s.length===0){z9.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.busyDeferrals.delete(e);let t=gn(kn(bn(a),o));this.lastAgentTimestamp.set(e,t),await this.deps.db.setState(`lastAgentTs_${e}`,t);return}if(s.every(e=>this.deps.isExternalLickChannel(e.channel))&&this.deps.getContexts().get(e)?.isBusy){z9.debug(`processScoopQueue: deferring lick batch while scoop is busy`,{jid:e,messageCount:s.length}),this.recordBusyDeferral(e);return}this.busyDeferrals.delete(e);let c=s.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${gte(e.content,e.attachments)}`).join(`
8549
- `),l=s.flatMap(e=>_te(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=gn(kn(bn(a),o));this.lastAgentTimestamp.set(e,d),await this.deps.db.setState(`lastAgentTs_${e}`,d);let f=s.some(e=>e.steer);await this.deps.sendPrompt(e,c,u.senderId,u.senderName,l,{steer:f})}startMessageLoop(){this.pollInterval||=setInterval(()=>{for(let e of this.deps.getScoops().keys()){let t=this.deps.getTabs().get(e);this.recordBusyDeferralIfPresent(e);let n=(this.messageQueues.get(e)?.length??0)>0;t?.status===`ready`&&n&&!this.debounceStates.has(e)&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);z9.error(`Message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){if(this.cancelDebounce(e),t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{z9.warn(`Failed to clear agent session for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})})}}await this.deps.db.clearMessagesForScoop(e).catch(t=>{z9.warn(`Failed to clear persisted channel history for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.lastAgentTimestamp.delete(e),this.messageQueues.set(e,[]),this.busyDeferrals.delete(e),z9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){this.cancelDebounces(),await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{z9.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.deps.getContexts().values())e.clearMessages();this.lastAgentTimestamp.clear(),this.busyDeferrals.clear();for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),z9.info(`All messages cleared`)}async clearQueuedMessages(e){this.cancelDebounce(e);let t=this.messageQueues.get(e)??[],n=this.deps.getScoops().get(e)?.assistantLabel??e,r=this.lastAgentTimestamp.get(e)??``,i=await this.deps.db.getMessagesSince(e,r,n),a=new Set([...t,...i].map(e=>e.id));for(let e of a)await this.deps.db.deleteMessage(e);this.messageQueues.set(e,[]),this.busyDeferrals.delete(e)}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let r=n.findIndex(e=>e.id===t);r!==-1&&n.splice(r,1),n.length===0&&this.busyDeferrals.delete(e)}this.cancelDebounceWaiter(e,t),await this.deps.db.deleteMessage(t)}};const B9=r(`orchestrator`);var Noe=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new cb({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new jb({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new kb({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Cb({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findCone:()=>Array.from(this.scoops.values()).find(e=>e.isCone),hasScoop:e=>this.scoops.has(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),handleMessage:e=>this.handleMessage(e),reportError:(e,t)=>this.callbacks.onError(e,t)});processManager=null;unregisterExportService=null;approvalRouter=new hb({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>wn(e),saveMessage:e=>_n(e)});lickRegistry=new db({getConeShell:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new Moe({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i,a)=>this.sendPrompt(e,t,n,r,i??[],a),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),onError:(e,t)=>this.callbacks.onError(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>_n(e),deleteMessage:e=>yn(e),clearMessagesForScoop:e=>Dn(e),clearAllMessages:()=>Tn(),getMessagesSince:(e,t,n)=>Cn(e,t,n),setState:(e,t)=>hn(e,t)},isExternalLickChannel:$i});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new joe({getScoops:()=>this.scoops,getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>mn(e),deleteScoop:e=>En(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>Wn(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e),flushOnIdle:e=>this.messageRouter.flushOnIdle(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t)=>this.scheduleScoopWait(e,t),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t)=>this.resolveActionableLick(e,t),listPendingSudoRequests:()=>this.listPendingSudoRequests()},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async init(){await aee(),this.sharedFs=await tr.create({dbName:`slicc-fs`}),this.sessionStore=new yte,this.fsWatcher=new er,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new j_({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await iee();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.migrateScoopConfig(t),this.scoops.set(t.jid,t),this.messageRouter.ensureQueue(t.jid);let e=await Sn(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new pb({onTaskRun:async(e,t)=>{B9.info(`Running scheduled task`,{taskId:e.id,scoop:t.name}),await this.sendPrompt(t.jid,`[SCHEDULED TASK]\n\n${e.prompt}`,`scheduler`,`Scheduled Task`)},getScoop:e=>{for(let t of this.scoops.values())if(t.folder===e)return t}}),this.scheduler.start(),B9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())try{await this.createScoopTab(e.jid)}catch(t){let n=t instanceof Error?t.message:String(t);B9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:e.jid,folder:e.folder,isCone:e.isCone,error:n}),e.isCone||this.lifecycle.markTabError(e.jid,n)}ir(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=N_(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}migrateScoopConfig(e){if(e.isCone)return;let t=e.configSchemaVersion??0;t>=2||(t<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),t<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),e.configSchemaVersion=2)}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setScoopExistenceResolver(e=>this.getScoops().some(t=>Vn(e,t.name,t.folder))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t){return this.completionService.scheduleScoopWait(e,t)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t){return this.approvalRouter.resolveSudoRequestAndPersist(e,t)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}async resolveActionableLick(e,t){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(){return this.approvalRouter.listPendingSudoRequests()}registerScoop(e){return this.lifecycle.register(e)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await tr.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await ib(this.sharedFs).catch(e=>{B9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new j_({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init(),this.costTracker.reset(),B9.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e))}clearAllMessages(){return this.messageRouter.clearAllMessages()}handleMessage(e){return this.messageRouter.handleMessage(e)}delegateToScoop(e,t,n){return this.messageRouter.delegateToScoop(e,t,n)}createScoopTab(e){return this.lifecycle.createTab(e)}async destroyScoopTab(e){this.lifecycle.destroyTab(e)}isProcessing(e){return this.lifecycle.getTab(e)?.status===`processing`}getScoopContext(e){return this.lifecycle.getContext(e)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return wn(e)}sendPrompt(e,t,n,r,i=[],a){return this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}updateModel(){this.lifecycle.updateModelOnAll()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await import(`./frozen-archive-format-CqpMlNNW.js`).then(e=>e.t),r=await n(this.sharedFs);return[...t,...r.map(cr)]}getModelCosts(e){return this.costTracker.getModelCosts(e)}getBurnRate(e){return this.costTracker.getBurnRate(e)}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&B9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.sudoManager?.dispose(),this.sudoManager=null,this.unregisterExportService?.(),this.unregisterExportService=null,B9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new Zi,t=this.sharedFs;return new Uv({collection:{listScoops:()=>this.getScoops(),isProcessing:e=>this.isProcessing(e),getAgentMessages:e=>this.getScoopContext(e)?.getAgentMessages()??null,loadPersistedSessions:()=>this.sessionStore?.loadAll()??Promise.resolve([]),loadUiChatSessions:async()=>{let t=await e.list();return(await Promise.all(t.map(t=>e.load(t)))).filter(e=>e!==null)},wait:e=>new Promise(t=>setTimeout(t,e))},knownSecrets:sy(),snapshotStore:{read:e=>ey(t,e),write:(e,n)=>$v(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.2.0`})}};function Poe(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var Foe=class{kind=`proc`;source=void 0;profile=void 0;mountId;pm;closed=!1;constructor(e,t={}){this.pm=e,this.mountId=t.mountId??`proc-${Date.now().toString(36)}`}async readDir(e){this.assertOpen(e);let t=H9(e);if(t.length===0){let e=this.pm.list(),t=e.map(e=>({name:String(e.pid),kind:`directory`}));return e.some(e=>e.pid===1)||t.push({name:`1`,kind:`directory`}),t.sort((e,t)=>Number(e.name)-Number(t.name))}if(t.length===1){let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new nn(`ENOENT`,`no such file or directory`,e);return V9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new nn(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=H9(e);if(t.length!==2)throw new nn(`EISDIR`,`is a directory`,e);let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new nn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new nn(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new nn(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=H9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new nn(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new nn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new nn(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new nn(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new nn(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new nn(`EACCES`,`read-only filesystem`,e)}async refresh(){return{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:`/proc`,extra:`kernel processes (read-only)`}}async close(){this.closed=!0}assertOpen(e){if(this.closed)throw new nn(`EBADF`,`mount closed`,e)}pidExists(e){return e===1||this.pm.get(e)!==null}fileSize(e,t){return this.renderProcFile(e,t).length}fileMtime(e){if(e===1)return 0;let t=this.pm.get(e);return t?t.finishedAt??t.startedAt:0}renderProcFile(e,t){if(e===1)return Voe(t);let n=this.pm.get(e);switch(t){case`status`:return Ioe(n);case`cmdline`:return Loe(n);case`cwd`:return Roe(n);case`stat`:return zoe(n)}}};const V9=[`status`,`cmdline`,`cwd`,`stat`];function H9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function U9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function Ioe(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${W9(e.status)} (${e.status})`,`Owner:\t${Boe(e)}`,`StartedAt:\t${new Date(e.startedAt).toISOString()}`];return e.finishedAt!==null&&t.push(`FinishedAt:\t${new Date(e.finishedAt).toISOString()}`),e.terminatedBy!==null&&t.push(`TerminatedBy:\t${e.terminatedBy}`),e.exitCode!==null&&t.push(`ExitCode:\t${e.exitCode}`),t.push(`Cmdline:\t${e.argv.join(` `)}`),t.join(`
8548
+ ---`);let a=rb(n);return a&&(i+=a),i}};const R9=r(`scoop-lifecycle-manager`);var joe=class{deps;tabs=new Map;contexts=new Map;scoopObservers=new Map;constructor(e){this.deps=e}getContexts(){return this.contexts}getContext(e){return this.contexts.get(e)}getTab(e){return this.tabs.get(e)}observe(e,t){let n=this.scoopObservers.get(e);return n||(n=new Set,this.scoopObservers.set(e,n)),n.add(t),()=>{let n=this.scoopObservers.get(e);n&&(n.delete(t),n.size===0&&this.scoopObservers.delete(e))}}dispatch(e,t,...n){let r=this.scoopObservers.get(e);if(r)for(let i of r){let r=i[t];if(r)try{r(...n)}catch(n){R9.warn(`scoop observer threw`,{jid:e,event:t,error:n instanceof Error?n.message:String(n)})}}}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager(),n=this.deps.getSharedFs();if(!(!t||!n))try{let r=`/scoops/${e.folder}/etc/sudoers`;await n.exists(r)?await t.reloadScoopPolicyByFolder(e.folder):await t.seedScoopSudoers(e.folder,e.config)}catch(t){R9.warn(`Failed to seed per-scoop sudoers; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)R9.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{R9.debug(`Context already exists`,{jid:e});return}let n=this.deps.getSharedFs();if(!n)throw Error(`Shared filesystem not initialized`);let r=`scoop-${t.folder}-${Date.now()}`,i=t.isCone?n:new nr(n,t.config?.writablePaths?[...t.config.writablePaths]:[],t.config?.visiblePaths?[...t.config.visiblePaths]:[],`sudo-delegated`);t.isCone||await this.ensureSudoersLoaded(t);let a=this.buildContextCallbacks(e,t),o=Array.from(this.deps.getScoops().values()).find(e=>e.isCone)?.jid,s=new Aoe(t,a,i,this.deps.getSessionStore()??void 0,n??void 0,o,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());this.contexts.set(e,s),this.tabs.set(e,{jid:e,contextId:r,status:`initializing`,lastActivity:new Date().toISOString()}),await s.init();let c=this.tabs.get(e);c&&c.status===`initializing`&&(c.status=`ready`,this.tabs.set(e,c),this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{R9.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let l=this.deps.getScoops().get(e);l&&!l.isCone&&this.deps.idleTimers.start(e),R9.info(`Scoop context created`,{jid:e,contextId:r})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),this.scoopObservers.delete(e),R9.info(`Scoop context destroyed`,{jid:e}))}forgetObservers(e){this.scoopObservers.delete(e)}getTabsMap(){return this.tabs}setTab(e,t){this.tabs.set(e,t)}markTabError(e,t){let n=this.tabs.get(e);this.tabs.set(e,{jid:e,contextId:n?.contextId??`scoop-error-${e}`,status:`error`,error:t,lastActivity:new Date().toISOString()})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let[e,t]of this.contexts.entries())this.deps.idleTimers.clear(e),t.stop(),this.contexts.delete(e)}async destroyAllTabs(){for(let e of Array.from(this.contexts.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.tabs.get(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return R9.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.contexts.get(e);o||=(await this.createTab(e),this.contexts.get(e));let s=this.tabs.get(e);if(s?.status===`initializing`){if(R9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){R9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}o=this.contexts.get(e),s=this.tabs.get(e)}if(!o){R9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),s&&(s.status=`processing`,s.lastActivity=new Date().toISOString(),this.tabs.set(e,s),this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),R9.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await o.prompt(t,i,a)}async register(e){let t=this.deps.getScoops();await this.deps.db.saveScoop(e),t.set(e.jid,e),this.deps.messageRouter.ensureQueue(e.jid),R9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.isCone||Vt(`spawn`,e.folder)}catch(n){R9.error(`Scoop init failed`,{jid:e.jid,name:e.name,error:n instanceof Error?n.message:String(n)});try{this.destroyTab(e.jid)}catch(t){R9.warn(`Failed to destroy scoop runtime during init rollback`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}throw t.delete(e.jid),this.deps.messageRouter.forgetScoop(e.jid),await this.deps.db.deleteScoop(e.jid).catch(t=>{R9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}async unregister(e){let t=this.deps.getScoops(),n=t.get(e),r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=await r.getLicksForScoopFromDb(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.dropForScoop(e).catch(t=>{R9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.deps.idleTimers.clear(e),this.destroyTab(e),this.deps.getSessionStore()?.delete(e).catch(t=>{R9.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.scoopObservers.delete(e),this.deps.completionService.forgetScoop(e,`unregister`);let a=this.deps.approvalRouter.failScoop(e);if(a>0&&R9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),R9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){R9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}updateModelOnAll(){for(let e of this.contexts.values())e.updateModel();R9.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{R9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),R9.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.contexts.get(e),a=i?i.setThinkingLevel(t,n):null;if(t===void 0){if(r.config&&r.config.thinkingLevel!==void 0){let{thinkingLevel:e,effortOverride:t,...n}=r.config;r.config=n}}else r.config={...r.config??{},thinkingLevel:t,effortOverride:n};try{await this.deps.db.saveScoop(r)}catch(t){R9.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops();return{onResponse:(i,o)=>{a().has(e)&&(n.onResponse(e,i,o),this.dispatch(e,`onResponse`,i,o),t.isCone||(o?r.appendResponseChunk(e,i):r.setResponseFull(e,i)))},onResponseDone:()=>{if(!a().has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),n.onResponseDone(e)},onError:r=>{if(!a().has(e))return;let i=this.tabs.get(e);i&&(i.status=`error`,i.error=r,this.tabs.set(e,i)),Vt(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`)},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:i=>{if(!a().has(e))return;let o=this.tabs.get(e);o&&(o.status=i,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o)),n.onStatusChange(e,i),this.dispatch(e,`onStatusChange`,i),i===`ready`&&this.deps.messageRouter.flushOnIdle(e),i===`ready`&&!t.isCone&&r.notifyCompletion(e)},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r)=>{n.onToolStart?.(e,t,r)},onToolEnd:(t,r,i)=>{n.onToolEnd?.(e,t,r,i)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i)},onToolUIDone:t=>{n.onToolUIDone?.(e,t)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return await i.registerScoop(n),n}:void 0,onDropScoop:t.isCone?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:t.isCone?e=>i.muteScoops(e):void 0,onUnmuteScoops:t.isCone?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:t.isCone?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:t.isCone?e=>i.setGlobalMemory(e):void 0,appendConeMemory:t.isCone?(e,t)=>i.appendConeMemory(e,t):void 0,onSudoRequest:t.isCone?void 0:t=>i.enqueueSudoRequest(e,t),onSudoResolve:t.isCone?(e,t)=>i.resolveActionableLick(e,t):void 0,onListSudoRequests:t.isCone?()=>i.listPendingSudoRequests():void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);R9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),Vt(`error`,r.folder,t);let i=this.tabs.get(e);if(i&&(i.status=`error`,i.error=t,this.tabs.set(e,i)),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),r.isCone)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let a=Array.from(n.values()).find(e=>e.isCone);if(!a)return;let o={id:`scoop-error-${e}-${Date.now()}`,chatJid:a.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(a.jid,o)}catch(e){R9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(o).catch(e=>{R9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const z9=r(`scoop-message-router`);var Moe=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;debounceStates=new Map;processing=new Map;busyDeferrals=new Map;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.cancelDebounce(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.clearBusyDeferral(e)}async handleMessage(e){if(z9.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)}),this.deps.isExternalLickChannel(e.channel))try{this.deps.notifyIncomingMessage(e.chatJid,e)}catch(t){z9.warn(`onIncomingMessage for external lick channel threw`,{channel:e.channel,error:t instanceof Error?t.message:String(t)})}await this.deps.db.saveMessage(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.deps.getScoops().get(e);if(!r)throw Error(`Scoop not found: ${e}`);Vt(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`delegation`};await this.deps.db.saveMessage(i),this.deps.notifyIncomingMessage(e,i),z9.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.deps.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);z9.error(`Delegation failed`,{scoopJid:e,error:n}),this.deps.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.deps.getScoops().get(e.chatJid);if(!t){z9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){z9.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let n=this.messageQueues.get(e.chatJid)??[];n.push(e),this.messageQueues.set(e.chatJid,n);let r=this.deps.getTabs().get(e.chatJid);if(z9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){z9.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),r=this.deps.getTabs().get(e.chatJid)}catch{z9.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}if(!(r?.status!==`ready`&&r?.status!==`processing`)){if(this.deps.isExternalLickChannel(e.channel)){await this.scheduleScoopQueue(e.chatJid,e.id);return}await this.flushScoopQueue(e.chatJid)}}passesTriggerGate(e,t){let n=t.channel===`webhook`||t.channel===`cron`||t.channel===`fswatch`||t.channel===`sprinkle`;return!e||e.isCone||!e.requiresTrigger||!e.trigger||n||t.content.includes(e.trigger)}scheduleScoopQueue(e,t){let n=this.debounceStates.get(e)??{startedAt:Date.now(),waiters:[]};n.timer!==void 0&&clearTimeout(n.timer);let r=new Promise((e,r)=>{n.waiters.push({messageId:t,resolve:e,reject:r})}),i=Math.max(0,3e3-(Date.now()-n.startedAt));return n.timer=setTimeout(()=>{n.timer=void 0,this.flushScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);z9.error(`Debounced message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},Math.min(1e3,i)),this.debounceStates.set(e,n),r}async flushScoopQueue(e){let t=this.takeDebounce(e);if(t&&this.processing.has(e)&&this.shouldDeferQueuedLicks(e)){for(let e of t.waiters)e.resolve();this.recordBusyDeferral(e,this.messageQueues.get(e)?.length??0);return}try{await this.processScoopQueue(e);for(let e of t?.waiters??[])e.resolve()}catch(e){for(let n of t?.waiters??[])n.reject(e);throw e}}async flushOnIdle(e){if(this.messageQueues.has(e))try{await this.flushScoopQueue(e)}catch(t){let n=t instanceof Error?t.message:String(t);z9.error(`Idle message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)}}shouldDeferQueuedLicks(e){let t=this.messageQueues.get(e);return t!==void 0&&t.length>0&&t.every(e=>this.deps.isExternalLickChannel(e.channel))}recordBusyDeferral(e,t){let n=this.busyDeferrals.get(e)??{startedAt:Date.now(),reported:!1,count:t??0};t!==void 0&&(n.count=t),this.busyDeferrals.set(e,n);let r=Date.now()-n.startedAt;if(n.reported||r<3e5)return;n.reported=!0;let i=`Lick queue remained deferred while scoop was busy for ${3e5/1e3}s`;z9.warn(`Busy lick queue may be starved`,{jid:e,error:i}),this.emitLickBackpressure(e,{count:n.count,waitingMs:r})}clearBusyDeferral(e){let t=this.busyDeferrals.get(e);this.busyDeferrals.delete(e),t?.reported&&this.emitLickBackpressure(e,{count:0,waitingMs:Date.now()-t.startedAt})}emitLickBackpressure(e,t){try{this.deps.onLickBackpressure?.(e,t)}catch(t){z9.warn(`Lick backpressure callback failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}}takeDebounce(e){let t=this.debounceStates.get(e);return t?.timer!==void 0&&clearTimeout(t.timer),this.debounceStates.delete(e),t}cancelDebounce(e){let t=this.takeDebounce(e);for(let e of t?.waiters??[])e.resolve()}cancelDebounces(){for(let e of this.debounceStates.keys())this.cancelDebounce(e)}cancelDebounceWaiter(e,t){let n=this.debounceStates.get(e);if(!n)return;let r=[];for(let e of n.waiters)e.messageId===t?e.resolve():r.push(e);n.waiters=r,r.length===0&&this.cancelDebounce(e)}async processScoopQueue(e){let t=this.processing.get(e);if(t){t.rerun=!0,await t.done.catch(()=>{});return}let n={rerun:!1,done:Promise.resolve()};return this.processing.set(e,n),n.done=this.drainScoopQueue(e,n),n.done}async drainScoopQueue(e,t){let n=!1,r;try{do{t.rerun=!1;try{await this.runScoopQueue(e)}catch(e){n||(n=!0,r=e)}}while(t.rerun)}finally{this.processing.delete(e)}if(n)throw r}async runScoopQueue(e){let t=this.messageQueues.get(e);if(!t){z9.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){z9.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.deps.getScoops().get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await this.deps.db.getMessagesSince(e,a,i),s=o.filter(e=>this.passesTriggerGate(r,e));if(z9.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,eligibleMessageCount:s.length,queueLength:t.length}),o.length===0){z9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){z9.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=gn(kn(bn(a),o));this.lastAgentTimestamp.set(e,t),await this.deps.db.setState(`lastAgentTs_${e}`,t);return}if(s.every(e=>this.deps.isExternalLickChannel(e.channel))&&this.deps.getContexts().get(e)?.isBusy){z9.debug(`processScoopQueue: deferring lick batch while scoop is busy`,{jid:e,messageCount:s.length}),this.recordBusyDeferral(e,s.length);return}this.clearBusyDeferral(e);let c=s.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${gte(e.content,e.attachments)}`).join(`
8549
+ `),l=s.flatMap(e=>_te(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=gn(kn(bn(a),o));this.lastAgentTimestamp.set(e,d),await this.deps.db.setState(`lastAgentTs_${e}`,d);let f=s.some(e=>e.steer);await this.deps.sendPrompt(e,c,u.senderId,u.senderName,l,{steer:f})}startMessageLoop(){this.pollInterval||=setInterval(()=>{for(let e of this.deps.getScoops().keys()){let t=this.deps.getTabs().get(e);this.recordBusyDeferralIfPresent(e);let n=(this.messageQueues.get(e)?.length??0)>0;t?.status===`ready`&&n&&!this.debounceStates.has(e)&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);z9.error(`Message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){if(this.cancelDebounce(e),t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{z9.warn(`Failed to clear agent session for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})})}}await this.deps.db.clearMessagesForScoop(e).catch(t=>{z9.warn(`Failed to clear persisted channel history for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.lastAgentTimestamp.delete(e),this.messageQueues.set(e,[]),this.clearBusyDeferral(e),z9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){this.cancelDebounces(),await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{z9.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.deps.getContexts().values())e.clearMessages();this.lastAgentTimestamp.clear();for(let e of this.busyDeferrals.keys())this.clearBusyDeferral(e);for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),z9.info(`All messages cleared`)}async clearQueuedMessages(e){this.cancelDebounce(e);let t=this.messageQueues.get(e)??[],n=this.deps.getScoops().get(e)?.assistantLabel??e,r=this.lastAgentTimestamp.get(e)??``,i=await this.deps.db.getMessagesSince(e,r,n),a=new Set([...t,...i].map(e=>e.id));for(let e of a)await this.deps.db.deleteMessage(e);this.messageQueues.set(e,[]),this.clearBusyDeferral(e)}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let r=n.findIndex(e=>e.id===t);r!==-1&&n.splice(r,1),n.length===0&&this.clearBusyDeferral(e)}this.cancelDebounceWaiter(e,t),await this.deps.db.deleteMessage(t)}};const B9=r(`orchestrator`);var Noe=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new cb({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new jb({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new kb({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Cb({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findCone:()=>Array.from(this.scoops.values()).find(e=>e.isCone),hasScoop:e=>this.scoops.has(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),handleMessage:e=>this.handleMessage(e),reportError:(e,t)=>this.callbacks.onError(e,t)});processManager=null;unregisterExportService=null;approvalRouter=new hb({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>wn(e),saveMessage:e=>_n(e)});lickRegistry=new db({getConeShell:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new Moe({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i,a)=>this.sendPrompt(e,t,n,r,i??[],a),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),onError:(e,t)=>this.callbacks.onError(e,t),onLickBackpressure:(e,t)=>this.callbacks.onLickBackpressure?.(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>_n(e),deleteMessage:e=>yn(e),clearMessagesForScoop:e=>Dn(e),clearAllMessages:()=>Tn(),getMessagesSince:(e,t,n)=>Cn(e,t,n),setState:(e,t)=>hn(e,t)},isExternalLickChannel:$i});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new joe({getScoops:()=>this.scoops,getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>mn(e),deleteScoop:e=>En(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>Wn(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e),flushOnIdle:e=>this.messageRouter.flushOnIdle(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t)=>this.scheduleScoopWait(e,t),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t)=>this.resolveActionableLick(e,t),listPendingSudoRequests:()=>this.listPendingSudoRequests()},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async init(){await aee(),this.sharedFs=await tr.create({dbName:`slicc-fs`}),this.sessionStore=new yte,this.fsWatcher=new er,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new j_({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await iee();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.migrateScoopConfig(t),this.scoops.set(t.jid,t),this.messageRouter.ensureQueue(t.jid);let e=await Sn(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new pb({onTaskRun:async(e,t)=>{B9.info(`Running scheduled task`,{taskId:e.id,scoop:t.name}),await this.sendPrompt(t.jid,`[SCHEDULED TASK]\n\n${e.prompt}`,`scheduler`,`Scheduled Task`)},getScoop:e=>{for(let t of this.scoops.values())if(t.folder===e)return t}}),this.scheduler.start(),B9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())try{await this.createScoopTab(e.jid)}catch(t){let n=t instanceof Error?t.message:String(t);B9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:e.jid,folder:e.folder,isCone:e.isCone,error:n}),e.isCone||this.lifecycle.markTabError(e.jid,n)}ir(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=N_(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}migrateScoopConfig(e){if(e.isCone)return;let t=e.configSchemaVersion??0;t>=2||(t<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),t<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),e.configSchemaVersion=2)}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setScoopExistenceResolver(e=>this.getScoops().some(t=>Vn(e,t.name,t.folder))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t){return this.completionService.scheduleScoopWait(e,t)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t){return this.approvalRouter.resolveSudoRequestAndPersist(e,t)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}async resolveActionableLick(e,t){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(){return this.approvalRouter.listPendingSudoRequests()}registerScoop(e){return this.lifecycle.register(e)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await tr.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await ib(this.sharedFs).catch(e=>{B9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new j_({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init(),this.costTracker.reset(),B9.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e))}clearAllMessages(){return this.messageRouter.clearAllMessages()}handleMessage(e){return this.messageRouter.handleMessage(e)}delegateToScoop(e,t,n){return this.messageRouter.delegateToScoop(e,t,n)}createScoopTab(e){return this.lifecycle.createTab(e)}async destroyScoopTab(e){this.lifecycle.destroyTab(e)}isProcessing(e){return this.lifecycle.getTab(e)?.status===`processing`}getScoopContext(e){return this.lifecycle.getContext(e)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return wn(e)}sendPrompt(e,t,n,r,i=[],a){return this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}updateModel(){this.lifecycle.updateModelOnAll()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await import(`./frozen-archive-format-CqpMlNNW.js`).then(e=>e.t),r=await n(this.sharedFs);return[...t,...r.map(cr)]}getModelCosts(e){return this.costTracker.getModelCosts(e)}getBurnRate(e){return this.costTracker.getBurnRate(e)}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&B9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.sudoManager?.dispose(),this.sudoManager=null,this.unregisterExportService?.(),this.unregisterExportService=null,B9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new Zi,t=this.sharedFs;return new Uv({collection:{listScoops:()=>this.getScoops(),isProcessing:e=>this.isProcessing(e),getAgentMessages:e=>this.getScoopContext(e)?.getAgentMessages()??null,loadPersistedSessions:()=>this.sessionStore?.loadAll()??Promise.resolve([]),loadUiChatSessions:async()=>{let t=await e.list();return(await Promise.all(t.map(t=>e.load(t)))).filter(e=>e!==null)},wait:e=>new Promise(t=>setTimeout(t,e))},knownSecrets:sy(),snapshotStore:{read:e=>ey(t,e),write:(e,n)=>$v(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.3.0`})}};function Poe(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var Foe=class{kind=`proc`;source=void 0;profile=void 0;mountId;pm;closed=!1;constructor(e,t={}){this.pm=e,this.mountId=t.mountId??`proc-${Date.now().toString(36)}`}async readDir(e){this.assertOpen(e);let t=H9(e);if(t.length===0){let e=this.pm.list(),t=e.map(e=>({name:String(e.pid),kind:`directory`}));return e.some(e=>e.pid===1)||t.push({name:`1`,kind:`directory`}),t.sort((e,t)=>Number(e.name)-Number(t.name))}if(t.length===1){let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new nn(`ENOENT`,`no such file or directory`,e);return V9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new nn(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=H9(e);if(t.length!==2)throw new nn(`EISDIR`,`is a directory`,e);let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new nn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new nn(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new nn(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=H9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new nn(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new nn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new nn(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new nn(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new nn(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new nn(`EACCES`,`read-only filesystem`,e)}async refresh(){return{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:`/proc`,extra:`kernel processes (read-only)`}}async close(){this.closed=!0}assertOpen(e){if(this.closed)throw new nn(`EBADF`,`mount closed`,e)}pidExists(e){return e===1||this.pm.get(e)!==null}fileSize(e,t){return this.renderProcFile(e,t).length}fileMtime(e){if(e===1)return 0;let t=this.pm.get(e);return t?t.finishedAt??t.startedAt:0}renderProcFile(e,t){if(e===1)return Voe(t);let n=this.pm.get(e);switch(t){case`status`:return Ioe(n);case`cmdline`:return Loe(n);case`cwd`:return Roe(n);case`stat`:return zoe(n)}}};const V9=[`status`,`cmdline`,`cwd`,`stat`];function H9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function U9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function Ioe(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${W9(e.status)} (${e.status})`,`Owner:\t${Boe(e)}`,`StartedAt:\t${new Date(e.startedAt).toISOString()}`];return e.finishedAt!==null&&t.push(`FinishedAt:\t${new Date(e.finishedAt).toISOString()}`),e.terminatedBy!==null&&t.push(`TerminatedBy:\t${e.terminatedBy}`),e.exitCode!==null&&t.push(`ExitCode:\t${e.exitCode}`),t.push(`Cmdline:\t${e.argv.join(` `)}`),t.join(`
8550
8550
  `)+`
8551
8551
  `}function Loe(e){return e.argv.join(`\0`)+`\0`}function Roe(e){return e.cwd+`
8552
8552
  `}function zoe(e){return[e.pid,`(${e.kind})`,W9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
@@ -8555,4 +8555,4 @@ ${t}
8555
8555
  `;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
8556
8556
  `;case`stat`:return`1 (kernel-host) R 0 - 0 -
8557
8557
  `}}function Hoe(e={}){let t=e.channel===void 0;if(t&&!e.nonce)throw Error(`installSyncFsResponder: a nonce (or a test channel) is required`);let n=e.channel??new BroadcastChannel(pB(e.nonce)),r=e=>n.postMessage(e),i=new Map,a=e=>{let t=e.data;if(t?.type!==`sync-fs-req`||typeof t.id!=`string`)return;let n=t;if(!cB(n.token))return;let a=i.get(n.id);if(a){r({type:mB,id:n.id}),a.result&&r({type:hB,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:mB,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:hB,id:n.id,...e})};(vB(n)?xB(n):fB(n)).then(s).catch(e=>s({ok:!1,errno:`EIO`,message:e instanceof Error?e.message:String(e)}))};return n.addEventListener(`message`,a),{dispose:()=>{n.removeEventListener(`message`,a);for(let e of i.values())e.timer&&clearTimeout(e.timer);i.clear(),t&&n.close?.()}}}function Uoe(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`mount-recovery`;case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;case`preview`:return e.previewOrigin??`preview`;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function Woe(e){switch(e.type){case`webhook`:return e.webhookId;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchId;case`navigate`:return e.navigateUrl;case`upgrade`:return`upgrade-${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`session-reload-${e.timestamp}`;case`workflow`:return`workflow-${e.workflowRunId??`unknown`}`;case`preview`:return e.previewConnId??`preview-${e.timestamp}`;case`discovery`:return e.discoveryUrl??`discovery-${e.timestamp}`;default:return e.cronId}}function Goe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Koe(e,t)}function Koe(e,{orchestrator:t,log:n}){e.type===`navigate`?e.lickId=t.registerNavigateLick(e):e.type===`session-reload`?e.lickId=t.registerSessionReloadLick(e):e.type===`upgrade`&&(e.lickId=t.registerUpgradeLick(e));let r=fa(e);if(r===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let i=Uoe(e),a=Woe(e),o=e.type,s=t.getScoops(),c;if(c=e.targetScoop?s.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):s.find(e=>e.isCone),!c){n.warn(`Lick target scoop not found`,e.targetScoop);return}let l={id:`${o}-${a}-${Date.now()}`,chatJid:c.jid,senderId:o,senderName:`${o}:${i}`,content:r.content,timestamp:e.timestamp,fromAssistant:!1,channel:o,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(l)}async function qoe(e,t,n,r){let i=new Kr,a=new Noe(e,{...r,getBrowserAPI:()=>t});a.setProcessManager(i),globalThis.__slicc_pm=i,globalThis.__slicc_browser=t,await n.bind(a,t);let o=lee(()=>n.emitTrayRuntimeStatus()),s=ree(()=>n.emitTrayRuntimeStatus());return await a.init(),await n.seedBuffersFromAgentState(),{processManager:i,orchestrator:a,unsubLeader:o,unsubFollower:s,sharedFs:a.getSharedFS()}}async function Joe(e,t,n){let{registerSessionCostsProvider:r}=await import(`./cost-command-_BMgmnMI.js`).then(e=>e.t);r(t=>e.getSessionCostsForCommand(t));let{getLickManager:i}=await import(`./lick-manager-Ce_d4NxJ.js`).then(e=>e.r),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??Goe,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function Yoe(e){e.getScoops().some(e=>e.isCone)||await e.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()})}function Xoe(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;Uie({sharedFs:i,getConeJid:()=>t.getScoops().find(e=>e.isCone)?.jid,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>uW(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>p9().slice(10,22),splitResult:(e,t)=>m9(e,t)})}async function Zoe(e){let{browser:t,lickManager:n,orchestrator:r,sharedFs:i,log:a}=e,{CdpWsPageBridge:o}=await import(`./cdp-ws-page-bridge-D_PY6ku1.js`),{WsSubscriberRegistry:s}=await import(`./ws-subscribers-Dzuxa2F7.js`),c=new o({browser:t});return{wsBridge:c,wsRegistry:new s({bridge:c,webhooks:{has:e=>n.getWebhook(e)!==void 0},dispatcher:{webhook:(e,t)=>{n.handleWebhookEvent(e,{},t)},scoop:(e,t)=>{if(!r.getScoops().find(t=>t.jid===e)){a.warn?.(`browser.websocket: scoop sink not found`,{jid:e});return}let n={id:`ws-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:e,senderId:`browser.websocket`,senderName:`browser.websocket`,content:typeof t==`string`?t:JSON.stringify(t,null,2),timestamp:new Date().toISOString(),fromAssistant:!1,channel:`browser.websocket`};r.handleMessage(n)},vfs:async(e,t)=>{if(!i)return;let n=(typeof t==`string`?t:JSON.stringify(t))+`
8558
- `,r=``;try{let t=await i.readFile(e);r=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await i.writeFile(e,r+n)},log:e=>{a.info?.(`browser.websocket frame`,{payload:e})}}})}}async function Qoe(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-eytKxVOP.js`);return t(e,{locationHref:self.location.href,lickWsUrl:n??null}).stop}catch(e){return(t.error?.bind(t)??t.warn.bind(t)??((e,t)=>console.error(`[lick-ws-bridge]`,e,t)))(`Failed to start lick-ws bridge — webhook / crontask / handoff lick delivery is non-functional in this session`,{error:e instanceof Error?e.message:String(e)}),null}}function $oe(e,t,n){let r=e.getTransport();if(r.isExtensionBridge)return n.debug?.(`Skipping NavigationWatcher: extension-bridge transport rejects sessionless Target.* discovery; the service worker observes handoffs via chrome.webRequest`),null;try{let e=new Na(r,e=>{let n={url:e.url,verb:e.verb,target:e.target};e.instruction!=null&&(n.instruction=e.instruction),e.branch!=null&&(n.branch=e.branch),e.path!=null&&(n.path=e.path),e.title!=null&&(n.title=e.title),t.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:new Date().toISOString(),body:n})},ese(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function ese(e){let t=Dt();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>Poe()}}function tse(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-CTrzlrNn.js`).then(e=>e.r),{recoverMounts:i}=await import(`./mount-recovery-5zqnhxot.js`).then(e=>e.n),a=await r();if(a.length===0)return;let{needsRecovery:o}=await i(a,e,n);if(o.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:o}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function nse(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-Bjglwm5C.js`),r=await t();if(!r.isUpgrade||r.lastSeen===null)return;e.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp:new Date().toISOString(),upgradeFromVersion:r.lastSeen,upgradeToVersion:r.bundled.version,body:{from:r.lastSeen,to:r.bundled.version,releasedAt:r.bundled.releasedAt}}),await n(r.bundled.version)}catch(e){t.warn(`Upgrade detection failed`,e)}})()}async function rse(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DTKmVPld.js`),{ScriptCatalog:r}=await import(`./script-catalog-BYXhqRAc.js`).then(e=>e.n),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function ise(){return A()}async function ase(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,{processManager:s,orchestrator:c,unsubLeader:l,unsubFollower:u,sharedFs:d}=await qoe(t,n,r,i);if(d?Lg(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new Foe(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await Joe(c,e,o);d&&Xoe({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await Zoe({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;ise()&&(h=await Qoe(f,o,e.localLickWsUrl??null));let g=$oe(n,f,o);d&&tse(d,f,o),a||await Yoe(c),d&&nse(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await rse(d,n,o));let y=null;d&&e.syncFsChannelNonce&&(y=Hoe({nonce:e.syncFsChannelNonce}).dispose);let b=!1;return{orchestrator:c,browser:n,bridge:r,lickManager:f,sharedFs:d??null,processManager:s,async dispose(){b||(b=!0,await ose({unsubLeader:l,unsubFollower:u,bshWatchdogStop:_,scriptCatalogDispose:v,lickWsBridgeStop:h,navigationWatcherStop:g,syncFsResponderDispose:y,sharedFs:d,wsRegistry:m,wsBridge:p,processManager:s,lickManager:f,browser:n,log:o}))}}}async function ose(e){let{sharedFs:t,wsRegistry:n,wsBridge:r,processManager:i,lickManager:a,browser:o,log:s}=e;if(e.unsubLeader?.(),e.unsubFollower?.(),e.bshWatchdogStop?.(),e.scriptCatalogDispose?.(),e.lickWsBridgeStop?.(),e.syncFsResponderDispose?.(),e.navigationWatcherStop)try{await e.navigationWatcherStop()}catch(e){s.warn(`NavigationWatcher.stop() failed`,e)}if(t)try{await t.unmountInternal(`/proc`)}catch{}try{n.dispose()}catch(e){s.warn(`WsSubscriberRegistry.dispose() failed`,e)}try{r.dispose()}catch(e){s.warn(`CdpWsPageBridge.dispose() failed`,e)}sse({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function sse(e){let t=globalThis;t.__slicc_pm===e.processManager&&delete t.__slicc_pm,t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[u9]}const G9=`x-bypass-llm-proxy`;function cse(e,t,n){return t?(r,i)=>{if(!lse(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(G9)||a.set(G9,`1`),e(r,{...i,headers:a})}:e}function lse(e,t,n){if(dse(e,t))return!0;let r=n?.()??null;return r?use(e,r,t):!1}function use(e,t,n){let r=K9(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function dse(e,t){let n=K9(e);try{return new URL(n,t).origin===t}catch{return!0}}function K9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function fse(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}var pse=class{transport;createShell;log;pm;defaultOwner;sessions=new Map;unsubscribe=null;constructor(e){this.transport=e.transport,this.createShell=e.createShell,this.log=e.logger??console,this.pm=e.processManager??null,this.defaultOwner=e.defaultOwner??{kind:`system`}}start(){return this.unsubscribe||=this.transport.onMessage(e=>{if(!mse(e)||e.source!==`panel`)return;let t=e.payload;hse(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n;let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=await t.shell.executeCommand(e.command,n.signal,r?.pid);await this.emitExecSuccess(e,i,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?q9(r?.terminatedBy??`SIGINT`):t.exitCode;n.signal.aborted||(r&&await r.gate.wait(),t.stdout&&this.emitStream(e,`stdout`,t.stdout),t.stderr&&this.emitStream(e,`stderr`,t.stderr)),this.emitExit(e,i),r&&this.pm&&this.pm.exit(r.pid,n.signal.aborted?null:t.exitCode)}emitExecError(e,t,n,r){if(n.signal.aborted){this.emitExit(e,q9(r?.terminatedBy??`SIGINT`)),r&&this.pm&&this.pm.exit(r.pid,null);return}let i=t instanceof Error?t.message:String(t);this.emitStream(e,`stderr`,`Error: ${i}\n`),this.emitExit(e,1),r&&this.pm&&this.pm.exit(r.pid,1)}async handleSignal(e){let t=this.sessions.get(e.sid);if(!t){this.log.warn(`[terminal-session-host] signal on unknown session`,e.sid);return}(e.signal===`SIGINT`||e.signal===`SIGTERM`||e.signal===`SIGKILL`)&&(t.currentProcess&&this.pm?this.pm.signal(t.currentProcess.pid,e.signal):t.currentExec?.abort())}emit(e){this.transport.send(e)}emitStatus(e,t,n){let r=n?{type:`terminal-status`,sid:e,state:t,error:n}:{type:`terminal-status`,sid:e,state:t};this.emit(r)}};function mse(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function q9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function hse(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`terminal-open`||t===`terminal-close`||t===`terminal-exec`||t===`terminal-signal`||t===`terminal-stdin`||t===`terminal-resize`}var gse=class extends w9{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};function _se(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new pse({transport:t,processManager:i,createShell:(e,a)=>new gse(e,t,{fs:n,cwd:a.cwd,env:a.env,browserAPI:r,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function vse(e){let t=new yse(e);return t.start(),{stop:()=>t.dispose()}}var yse=class{transport;client;writableClient;log;unsubscribe=null;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!bse(e)||e.source!==`panel`)return;let t=e.payload;if(xse(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(Sse(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null}async handleRequest(e){switch(e.type){case`vfs-read-dir`:return this.handleReadDir(e);case`vfs-read-file`:return this.handleReadFile(e);case`vfs-stat`:return this.handleStat(e)}}async handleReadDir(e){try{let t=await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e.requestId,new nn(`EIO`,`readFile(binary) did not return Uint8Array`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`binary`,data:n},r=n.buffer,i=typeof ArrayBuffer<`u`&&r instanceof ArrayBuffer?[r]:void 0;this.transport.send(t,i)}else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new nn(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async handleStat(e){try{let t=await this.client.stat(e.path),n={type:`vfs-stat-result`,requestId:e.requestId,ok:!0,stats:t};this.transport.send(n)}catch(t){this.emitError(`vfs-stat-result`,e.requestId,t,e.path)}}async handleWriteRequest(e){if(!this.writableClient){this.emitWriteError(Cse(e.type),e.requestId,new nn(`EACCES`,`vfs-rpc-host has no writable backend wired`),wse(e));return}switch(e.type){case`vfs-write-file`:return this.handleWriteFile(e,this.writableClient);case`vfs-mkdir`:return this.handleMkdir(e,this.writableClient);case`vfs-rm`:return this.handleRm(e,this.writableClient);case`vfs-flush`:return this.handleFlush(e,this.writableClient);case`vfs-list-mount-points`:return this.handleListMountPoints(e,this.writableClient)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new nn(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new nn(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}async handleListMountPoints(e,t){if(!t.listMountPoints){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,new nn(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=J9(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=J9(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function bse(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function xse(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-read-dir`||t===`vfs-read-file`||t===`vfs-stat`}function Sse(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-write-file`||t===`vfs-mkdir`||t===`vfs-rm`||t===`vfs-flush`||t===`vfs-list-mount-points`}function Cse(e){switch(e){case`vfs-write-file`:return`vfs-write-file-result`;case`vfs-mkdir`:return`vfs-mkdir-result`;case`vfs-rm`:return`vfs-rm-result`;case`vfs-flush`:return`vfs-flush-result`;case`vfs-list-mount-points`:return`vfs-list-mount-points-result`}}function wse(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof nn?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Tse(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=cse(e.bind(globalThis),t,Ese)}function Ese(){let e=Tt();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Dse(e){let t=new Map(Object.entries(e));Object.defineProperty(globalThis,"localStorage",{value:{get length(){return t.size},key(e){return Array.from(t.keys())[e]??null},getItem(e){return t.has(e)?t.get(e):null},setItem(e,n){t.set(e,n)},removeItem(e){t.delete(e)},clear(){t.clear()}},configurable:!0,writable:!0})}let Y9=null,X9=null,Z9=null,Q9=null,$9=null;const Ose=fse(e=>kse(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Ose.handle(e.data)});async function kse(e){Hi(e.instanceId);try{Tse(),Mt(e.localApiBaseUrl??null),St(e.bridgeToken??null),iW(e.syncFsBridgeEnabled??!1),Et(e.extensionDelegateId??null),Dse(e.localStorageSeed??{}),Rt().catch(()=>{}),await s();let t=qi(e.kernelPort),n=new wa(t),r=wa.createCallbacks(n),a=new Ji(e.cdpPort);await a.connect();let o=new Mi(a);Y9=await ase({container:{},browser:o,bridge:n,callbacks:r,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let u=Y9.sharedFs?.getWatcher();if(u){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)u.watch(r,e=>e.endsWith(`.shtml`),e=>{for(let t of e){let e=t.path.split(`/`).pop()?.replace(/\.shtml$/,``);e&&n.add(e)}t||=setTimeout(()=>{t=null;for(let e of n)l.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:d}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);$9=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,o.setTrayTargetProvider(Ri(i));let f=await Ase({host:Y9,transport:t,browser:o,instanceId:e.instanceId});f&&(X9=f.stopTerminalHost,Z9=f.stopVfsRpcHost,Q9=f.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw Wi(e),e}}async function Ase(e){let t=e.host.sharedFs;if(!t)return console.warn(`[kernel-worker] shared FS unavailable; terminal sessions will fail to open`),null;let n=_se({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=vse({transport:e.transport,client:t,writableClient:t,logger:console}),i=await jse(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function jse(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-CzwTkGxm.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-GabK83LB.js`).then(e=>e.o),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(X9?.(),X9=null,Z9?.(),Z9=null,Q9?.(),Q9=null,$9?.dispose(),$9=null,Y9?.dispose())});
8558
+ `,r=``;try{let t=await i.readFile(e);r=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await i.writeFile(e,r+n)},log:e=>{a.info?.(`browser.websocket frame`,{payload:e})}}})}}async function Qoe(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-eytKxVOP.js`);return t(e,{locationHref:self.location.href,lickWsUrl:n??null}).stop}catch(e){return(t.error?.bind(t)??t.warn.bind(t)??((e,t)=>console.error(`[lick-ws-bridge]`,e,t)))(`Failed to start lick-ws bridge — webhook / crontask / handoff lick delivery is non-functional in this session`,{error:e instanceof Error?e.message:String(e)}),null}}function $oe(e,t,n){let r=e.getTransport();if(r.isExtensionBridge)return n.debug?.(`Skipping NavigationWatcher: extension-bridge transport rejects sessionless Target.* discovery; the service worker observes handoffs via chrome.webRequest`),null;try{let e=new Na(r,e=>{let n={url:e.url,verb:e.verb,target:e.target};e.instruction!=null&&(n.instruction=e.instruction),e.branch!=null&&(n.branch=e.branch),e.path!=null&&(n.path=e.path),e.title!=null&&(n.title=e.title),t.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:new Date().toISOString(),body:n})},ese(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function ese(e){let t=Dt();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>Poe()}}function tse(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-CTrzlrNn.js`).then(e=>e.r),{recoverMounts:i}=await import(`./mount-recovery-B6-FEnb7.js`).then(e=>e.n),a=await r();if(a.length===0)return;let{needsRecovery:o}=await i(a,e,n);if(o.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:o}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function nse(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-CGfE8fu7.js`),r=await t();if(!r.isUpgrade||r.lastSeen===null)return;e.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp:new Date().toISOString(),upgradeFromVersion:r.lastSeen,upgradeToVersion:r.bundled.version,body:{from:r.lastSeen,to:r.bundled.version,releasedAt:r.bundled.releasedAt}}),await n(r.bundled.version)}catch(e){t.warn(`Upgrade detection failed`,e)}})()}async function rse(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DTKmVPld.js`),{ScriptCatalog:r}=await import(`./script-catalog-BYXhqRAc.js`).then(e=>e.n),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function ise(){return A()}async function ase(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,{processManager:s,orchestrator:c,unsubLeader:l,unsubFollower:u,sharedFs:d}=await qoe(t,n,r,i);if(d?Lg(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new Foe(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await Joe(c,e,o);d&&Xoe({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await Zoe({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;ise()&&(h=await Qoe(f,o,e.localLickWsUrl??null));let g=$oe(n,f,o);d&&tse(d,f,o),a||await Yoe(c),d&&nse(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await rse(d,n,o));let y=null;d&&e.syncFsChannelNonce&&(y=Hoe({nonce:e.syncFsChannelNonce}).dispose);let b=!1;return{orchestrator:c,browser:n,bridge:r,lickManager:f,sharedFs:d??null,processManager:s,async dispose(){b||(b=!0,await ose({unsubLeader:l,unsubFollower:u,bshWatchdogStop:_,scriptCatalogDispose:v,lickWsBridgeStop:h,navigationWatcherStop:g,syncFsResponderDispose:y,sharedFs:d,wsRegistry:m,wsBridge:p,processManager:s,lickManager:f,browser:n,log:o}))}}}async function ose(e){let{sharedFs:t,wsRegistry:n,wsBridge:r,processManager:i,lickManager:a,browser:o,log:s}=e;if(e.unsubLeader?.(),e.unsubFollower?.(),e.bshWatchdogStop?.(),e.scriptCatalogDispose?.(),e.lickWsBridgeStop?.(),e.syncFsResponderDispose?.(),e.navigationWatcherStop)try{await e.navigationWatcherStop()}catch(e){s.warn(`NavigationWatcher.stop() failed`,e)}if(t)try{await t.unmountInternal(`/proc`)}catch{}try{n.dispose()}catch(e){s.warn(`WsSubscriberRegistry.dispose() failed`,e)}try{r.dispose()}catch(e){s.warn(`CdpWsPageBridge.dispose() failed`,e)}sse({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function sse(e){let t=globalThis;t.__slicc_pm===e.processManager&&delete t.__slicc_pm,t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[u9]}const G9=`x-bypass-llm-proxy`;function cse(e,t,n){return t?(r,i)=>{if(!lse(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(G9)||a.set(G9,`1`),e(r,{...i,headers:a})}:e}function lse(e,t,n){if(dse(e,t))return!0;let r=n?.()??null;return r?use(e,r,t):!1}function use(e,t,n){let r=K9(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function dse(e,t){let n=K9(e);try{return new URL(n,t).origin===t}catch{return!0}}function K9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function fse(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}var pse=class{transport;createShell;log;pm;defaultOwner;sessions=new Map;unsubscribe=null;constructor(e){this.transport=e.transport,this.createShell=e.createShell,this.log=e.logger??console,this.pm=e.processManager??null,this.defaultOwner=e.defaultOwner??{kind:`system`}}start(){return this.unsubscribe||=this.transport.onMessage(e=>{if(!mse(e)||e.source!==`panel`)return;let t=e.payload;hse(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n;let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=await t.shell.executeCommand(e.command,n.signal,r?.pid);await this.emitExecSuccess(e,i,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?q9(r?.terminatedBy??`SIGINT`):t.exitCode;n.signal.aborted||(r&&await r.gate.wait(),t.stdout&&this.emitStream(e,`stdout`,t.stdout),t.stderr&&this.emitStream(e,`stderr`,t.stderr)),this.emitExit(e,i),r&&this.pm&&this.pm.exit(r.pid,n.signal.aborted?null:t.exitCode)}emitExecError(e,t,n,r){if(n.signal.aborted){this.emitExit(e,q9(r?.terminatedBy??`SIGINT`)),r&&this.pm&&this.pm.exit(r.pid,null);return}let i=t instanceof Error?t.message:String(t);this.emitStream(e,`stderr`,`Error: ${i}\n`),this.emitExit(e,1),r&&this.pm&&this.pm.exit(r.pid,1)}async handleSignal(e){let t=this.sessions.get(e.sid);if(!t){this.log.warn(`[terminal-session-host] signal on unknown session`,e.sid);return}(e.signal===`SIGINT`||e.signal===`SIGTERM`||e.signal===`SIGKILL`)&&(t.currentProcess&&this.pm?this.pm.signal(t.currentProcess.pid,e.signal):t.currentExec?.abort())}emit(e){this.transport.send(e)}emitStatus(e,t,n){let r=n?{type:`terminal-status`,sid:e,state:t,error:n}:{type:`terminal-status`,sid:e,state:t};this.emit(r)}};function mse(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function q9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function hse(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`terminal-open`||t===`terminal-close`||t===`terminal-exec`||t===`terminal-signal`||t===`terminal-stdin`||t===`terminal-resize`}var gse=class extends w9{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};function _se(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new pse({transport:t,processManager:i,createShell:(e,a)=>new gse(e,t,{fs:n,cwd:a.cwd,env:a.env,browserAPI:r,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function vse(e){let t=new yse(e);return t.start(),{stop:()=>t.dispose()}}var yse=class{transport;client;writableClient;log;unsubscribe=null;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!bse(e)||e.source!==`panel`)return;let t=e.payload;if(xse(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(Sse(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null}async handleRequest(e){switch(e.type){case`vfs-read-dir`:return this.handleReadDir(e);case`vfs-read-file`:return this.handleReadFile(e);case`vfs-stat`:return this.handleStat(e)}}async handleReadDir(e){try{let t=await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e.requestId,new nn(`EIO`,`readFile(binary) did not return Uint8Array`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`binary`,data:n},r=n.buffer,i=typeof ArrayBuffer<`u`&&r instanceof ArrayBuffer?[r]:void 0;this.transport.send(t,i)}else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new nn(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async handleStat(e){try{let t=await this.client.stat(e.path),n={type:`vfs-stat-result`,requestId:e.requestId,ok:!0,stats:t};this.transport.send(n)}catch(t){this.emitError(`vfs-stat-result`,e.requestId,t,e.path)}}async handleWriteRequest(e){if(!this.writableClient){this.emitWriteError(Cse(e.type),e.requestId,new nn(`EACCES`,`vfs-rpc-host has no writable backend wired`),wse(e));return}switch(e.type){case`vfs-write-file`:return this.handleWriteFile(e,this.writableClient);case`vfs-mkdir`:return this.handleMkdir(e,this.writableClient);case`vfs-rm`:return this.handleRm(e,this.writableClient);case`vfs-flush`:return this.handleFlush(e,this.writableClient);case`vfs-list-mount-points`:return this.handleListMountPoints(e,this.writableClient)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new nn(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new nn(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}async handleListMountPoints(e,t){if(!t.listMountPoints){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,new nn(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=J9(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=J9(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function bse(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function xse(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-read-dir`||t===`vfs-read-file`||t===`vfs-stat`}function Sse(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-write-file`||t===`vfs-mkdir`||t===`vfs-rm`||t===`vfs-flush`||t===`vfs-list-mount-points`}function Cse(e){switch(e){case`vfs-write-file`:return`vfs-write-file-result`;case`vfs-mkdir`:return`vfs-mkdir-result`;case`vfs-rm`:return`vfs-rm-result`;case`vfs-flush`:return`vfs-flush-result`;case`vfs-list-mount-points`:return`vfs-list-mount-points-result`}}function wse(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof nn?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Tse(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=cse(e.bind(globalThis),t,Ese)}function Ese(){let e=Tt();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Dse(e){let t=new Map(Object.entries(e));Object.defineProperty(globalThis,"localStorage",{value:{get length(){return t.size},key(e){return Array.from(t.keys())[e]??null},getItem(e){return t.has(e)?t.get(e):null},setItem(e,n){t.set(e,n)},removeItem(e){t.delete(e)},clear(){t.clear()}},configurable:!0,writable:!0})}let Y9=null,X9=null,Z9=null,Q9=null,$9=null;const Ose=fse(e=>kse(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Ose.handle(e.data)});async function kse(e){Hi(e.instanceId);try{Tse(),Mt(e.localApiBaseUrl??null),St(e.bridgeToken??null),iW(e.syncFsBridgeEnabled??!1),Et(e.extensionDelegateId??null),Dse(e.localStorageSeed??{}),Rt().catch(()=>{}),await s();let t=qi(e.kernelPort),n=new wa(t),r=wa.createCallbacks(n),a=new Ji(e.cdpPort);await a.connect();let o=new Mi(a);Y9=await ase({container:{},browser:o,bridge:n,callbacks:r,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let u=Y9.sharedFs?.getWatcher();if(u){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)u.watch(r,e=>e.endsWith(`.shtml`),e=>{for(let t of e){let e=t.path.split(`/`).pop()?.replace(/\.shtml$/,``);e&&n.add(e)}t||=setTimeout(()=>{t=null;for(let e of n)l.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:d}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);$9=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,o.setTrayTargetProvider(Ri(i));let f=await Ase({host:Y9,transport:t,browser:o,instanceId:e.instanceId});f&&(X9=f.stopTerminalHost,Z9=f.stopVfsRpcHost,Q9=f.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw Wi(e),e}}async function Ase(e){let t=e.host.sharedFs;if(!t)return console.warn(`[kernel-worker] shared FS unavailable; terminal sessions will fail to open`),null;let n=_se({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=vse({transport:e.transport,client:t,writableClient:t,logger:console}),i=await jse(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function jse(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-CzwTkGxm.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-GabK83LB.js`).then(e=>e.o),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(X9?.(),X9=null,Z9?.(),Z9=null,Q9?.(),Q9=null,$9?.dispose(),$9=null,Y9?.dispose())});