sliccy 6.141.0 → 6.141.1
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.
- package/dist/ui/.vite/manifest.json +155 -155
- package/dist/ui/assets/{account-store-CW3jE2sF.js → account-store-BOfP1pcJ.js} +1 -1
- package/dist/ui/assets/{account-store-lxoAGWoo.js → account-store-nmT3gu2H.js} +1 -1
- package/dist/ui/assets/adobe-CTBukfKM.js +1 -0
- package/dist/ui/assets/adobe-eSxtA5dP.js +2 -0
- package/dist/ui/assets/{agent-bridge-DClELdY1.js → agent-bridge-G4SJSVj_.js} +1 -1
- package/dist/ui/assets/{agent-panels-Cmyd2b4K.js → agent-panels-BNxH0Lg1.js} +1 -1
- package/dist/ui/assets/{apply-layout-D66WbFkT.js → apply-layout-Hdj6QPFv.js} +1 -1
- package/dist/ui/assets/{apps-Bh_w9HOv.js → apps-DgoFisXN.js} +1 -1
- package/dist/ui/assets/{azure-openai-B9gQTUIy.js → azure-openai-8wfMaJX7.js} +1 -1
- package/dist/ui/assets/{azure-openai-BTOUPEim.js → azure-openai-CQ0ZJueS.js} +1 -1
- package/dist/ui/assets/{budget-usage-source-8V_0_Lud.js → budget-usage-source-CjET0w7O.js} +1 -1
- package/dist/ui/assets/{cdp-B-Tb1RrY.js → cdp-BFQdJYIn.js} +1 -1
- package/dist/ui/assets/{cerebras-C60nLw-V.js → cerebras-CIMucbnc.js} +1 -1
- package/dist/ui/assets/{cerebras-BFNeV8W4.js → cerebras-Cl6E13YS.js} +1 -1
- package/dist/ui/assets/{composer-speech-tbFuevfm.js → composer-speech-O-m-KTHH.js} +1 -1
- package/dist/ui/assets/{connect-surface-BWV5zd7D.js → connect-surface-BvHV7Qep.js} +1 -1
- package/dist/ui/assets/{directed-approval-BdcRpqjJ.js → directed-approval-BcWsqbqY.js} +1 -1
- package/dist/ui/assets/{fs-CA1eGBjq.js → fs-D-gRojJc.js} +1 -1
- package/dist/ui/assets/{fs-DgWyb2zr.js → fs-kM-ND3oY.js} +2 -2
- package/dist/ui/assets/{github-BnVI-Ric.js → github-BRY5hHDh.js} +2 -2
- package/dist/ui/assets/{github-BeNtOuZs.js → github-KQdanunG.js} +1 -1
- package/dist/ui/assets/{github-copilot-CyCKuKZj.js → github-copilot-BebJ2ytj.js} +1 -1
- package/dist/ui/assets/{github-copilot-DexJoQxv.js → github-copilot-DVapEhyn.js} +1 -1
- package/dist/ui/assets/{github-install-D_hW3Upl.js → github-install-WakGuTn3.js} +1 -1
- package/dist/ui/assets/{github-zip-B9lV3nxS.js → github-zip-Cn_DhUkt.js} +1 -1
- package/dist/ui/assets/{hear-BnXHHP3B.js → hear-DqvVBB3H.js} +1 -1
- package/dist/ui/assets/{help-CoC7qDFN.js → help-CDxwLbqk.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-DXyLExOV.js → js-realm-worker-CoOVJsfl.js} +1 -1
- package/dist/ui/assets/{kernel-worker-l5bqAeZu.js → kernel-worker-HLzxir27.js} +31 -31
- package/dist/ui/assets/{local-llm-CPxw769h.js → local-llm-DOoj67px.js} +1 -1
- package/dist/ui/assets/{local-llm-BSwhSOD7.js → local-llm-DleizWkm.js} +1 -1
- package/dist/ui/assets/{main-BM_U535K.js → main-DgfitWIR.js} +3 -3
- package/dist/ui/assets/{main-cherry-dPJsvicv.js → main-cherry-jk6QIZqX.js} +1 -1
- package/dist/ui/assets/{mount-CD47fnQP.js → mount-CJjAtfYn.js} +1 -1
- package/dist/ui/assets/{mount-BkvJQUCm.js → mount-CevkPA01.js} +3 -3
- package/dist/ui/assets/{mount-recovery-B1OZnCNp.js → mount-recovery-BbM7KXdZ.js} +1 -1
- package/dist/ui/assets/{new-session-CQ1A7aX8.js → new-session-B7whi9gh.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-D3Iei3Zi.js → oauth-bootstrap-DqJDy1ud.js} +2 -2
- package/dist/ui/assets/{onboarding-orchestrator-DGMltmI2.js → onboarding-orchestrator-7rRWHqLO.js} +1 -1
- package/dist/ui/assets/{openai-codex-B-NKToAX.js → openai-codex-CM0i15lF.js} +1 -1
- package/dist/ui/assets/{openai-codex-CEFY1RZQ.js → openai-codex-x05MSHCO.js} +1 -1
- package/dist/ui/assets/{openrouter-tfJth7Fv.js → openrouter-D6bYOaOx.js} +1 -1
- package/dist/ui/assets/{openrouter-BwMSsjrv.js → openrouter-L4-3N-l_.js} +1 -1
- package/dist/ui/assets/{openrouter-free-BGaKcxNa.js → openrouter-free-BJ7s9b2s.js} +1 -1
- package/dist/ui/assets/{openrouter-free-DIf8PqRY.js → openrouter-free-DiYmrPS6.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-Df0fJUGO.js → openrouter-oauth-C_3bf50h.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-DzILOImT.js → openrouter-oauth-DQNNeXqL.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-Dfr8nTRt.js → panel-rpc-handlers-Bi5-nj-7.js} +2 -2
- package/dist/ui/assets/{panelize-shell-BdklWMUU.js → panelize-shell-0efJXoqQ.js} +1 -1
- package/dist/ui/assets/{provider-C8soaib4.js → provider-CSn_GER4.js} +1 -1
- package/dist/ui/assets/{provider-h58TGW7D.js → provider-CkaGupdk.js} +2 -2
- package/dist/ui/assets/provider-settings-Dbb2mGJL.js +1 -0
- package/dist/ui/assets/provider-store-access-21JnkHrs.js +1 -0
- package/dist/ui/assets/provider-store-access-BdHwjNxC.js +1 -0
- package/dist/ui/assets/{providers-_GHbVO2y.js → providers-CKnaRi9f.js} +2 -2
- package/dist/ui/assets/{providers-B9G2bMde.js → providers-Cse0ZxeX.js} +1 -1
- package/dist/ui/assets/{quick-llm-bHa2oqGs.js → quick-llm-D0yXZLwM.js} +1 -1
- package/dist/ui/assets/{recovery-screen-xN1A_3mu.js → recovery-screen-BUl2n2Le.js} +1 -1
- package/dist/ui/assets/{run--1CF_9e0.js → run-CdoLZ5WY.js} +1 -1
- package/dist/ui/assets/{run-DWnB4CKu.js → run-DPmOLroa.js} +2 -2
- package/dist/ui/assets/{run-S0cfYmJs.js → run-cPelajgY.js} +1 -1
- package/dist/ui/assets/{setup-feature-flags-remote-BPdpV20y.js → setup-feature-flags-remote-CdfzJ0yn.js} +1 -1
- package/dist/ui/assets/sidecar-repair-B7c0WqjG.js +1 -0
- package/dist/ui/assets/{silent-renew-backoff-iLJU1iEI.js → silent-renew-backoff-BYIA7R-L.js} +1 -1
- package/dist/ui/assets/{skills-B4AcVnHX.js → skills-DxNa4Xoh.js} +1 -1
- package/dist/ui/assets/slicc-version-tRk2NmiN.js +1 -0
- package/dist/ui/assets/{snapshot-CnPDMiyS.js → snapshot-Ctd5h8ek.js} +1 -1
- package/dist/ui/assets/{snapshot-features-DFeOru8I.js → snapshot-features-DqQzJ2V2.js} +1 -1
- package/dist/ui/assets/{soundscape-DaGKjr14.js → soundscape-DcUFN6S7.js} +1 -1
- package/dist/ui/assets/{speak-DLb73QOR.js → speak-DrdZiGCl.js} +1 -1
- package/dist/ui/assets/{sprinkle-manager-BvDUG75y.js → sprinkle-manager-aR6v9O-2.js} +1 -1
- package/dist/ui/assets/{sprinkle-renderer-C3YzieNR.js → sprinkle-renderer-Q9VuoZT2.js} +1 -1
- package/dist/ui/assets/{state-CVrrA2OS.js → state-CZURVOkM.js} +1 -1
- package/dist/ui/assets/{store-l8lAck84.js → store-QKk0BB_L.js} +1 -1
- package/dist/ui/assets/{store-DOh745T1.js → store-TOhACrgy.js} +1 -1
- package/dist/ui/assets/{sudo-Cjr4qYWs.js → sudo-C2MeYxQv.js} +1 -1
- package/dist/ui/assets/{sync-dialog-D1BCRX-_.js → sync-dialog-CX_GFpuD.js} +1 -1
- package/dist/ui/assets/{transformers-env-C-3qKvFJ.js → transformers-env-CsMKMVLA.js} +1 -1
- package/dist/ui/assets/{tray-sidecar-CMNiM9jc.js → tray-sidecar-DGsLbjMW.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-1FdN6g-s.js → upgrade-detection-CAAKwVc2.js} +1 -1
- package/dist/ui/assets/{voice-reply-Cf-6qPVU.js → voice-reply-Ct4t1Hew.js} +1 -1
- package/dist/ui/assets/{wc-attach-BO5oVNEK.js → wc-attach-BBKNaAcO.js} +2 -2
- package/dist/ui/assets/{wc-extension-BHT1dE4q.js → wc-extension-DRciOuQ3.js} +2 -2
- package/dist/ui/assets/{wc-follower-DbtQT-q2.js → wc-follower-e3R0SxB1.js} +3 -3
- package/dist/ui/assets/{wc-follower-oauth-kJXHbCAd.js → wc-follower-oauth-BKF5A2z9.js} +1 -1
- package/dist/ui/assets/{wc-live-BEgauFg4.js → wc-live-BCzW5d6j.js} +6 -6
- package/dist/ui/assets/{wc-nav-Tk-HlDK1.js → wc-nav-CZlrMA5U.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-Hmnu5dDs.js → wc-onboarding-I4HEKolY.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-CEivPNy0.js → wc-placeholder-lbNLdUvV.js} +3 -3
- package/dist/ui/assets/{wc-settings-DEAKPCX_.js → wc-settings-UrBSocw5.js} +3 -3
- package/dist/ui/assets/{wc-shell-CzfjGWqF.js → wc-shell-BIZ7adcn.js} +3 -3
- package/dist/ui/assets/{wc-shortcut-config-CWEfOJqF.js → wc-shortcut-config-h7gI7ho-.js} +1 -1
- package/dist/ui/assets/{wc-shortcuts-B76JiuPn.js → wc-shortcuts-2HCq_0JV.js} +1 -1
- package/dist/ui/assets/{wc-sprinkles-JYa1gihw.js → wc-sprinkles-odiMuyUG.js} +2 -2
- package/dist/ui/assets/{wc-transcript-export-8vlKlVH3.js → wc-transcript-export-CwCZ7DGe.js} +2 -2
- package/dist/ui/assets/{wc-tray-B76S5VYB.js → wc-tray-kvYCqUrN.js} +4 -4
- package/dist/ui/assets/welcome-detection-CretH3iG.js +1 -0
- package/dist/ui/assets/{whisper-session-IRFMfzfE.js → whisper-session-CA0z08tl.js} +2 -2
- package/dist/ui/assets/{xai-grok-BCQxFHDD.js → xai-grok-B0FZQAhv.js} +1 -1
- package/dist/ui/assets/{xai-grok-D1MYSPx5.js → xai-grok-C_RSjGYK.js} +1 -1
- package/dist/ui/index.html +3 -3
- package/dist/ui/llm-proxy-sw.js +1 -1
- package/dist/ui/packages/webapp/index.html +3 -3
- package/package.json +1 -1
- package/dist/ui/assets/adobe-CMsAmLgr.js +0 -2
- package/dist/ui/assets/adobe-Ctii1c2c.js +0 -1
- package/dist/ui/assets/provider-settings-CMhb9uDe.js +0 -1
- package/dist/ui/assets/provider-store-access-DFLRLZG9.js +0 -1
- package/dist/ui/assets/provider-store-access-DmAUjGS4.js +0 -1
- package/dist/ui/assets/sidecar-repair-DacCJIQE.js +0 -1
- package/dist/ui/assets/slicc-version-gM32b-cO.js +0 -1
- package/dist/ui/assets/welcome-detection-Bdv20Fw6.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,n as t,t as n}from"./rolldown-runtime-Dd_uD5pT.js";import{t as r}from"./logger-LESFN7Hj.js";import{a as i,i as a,n as o,o as s,r as c,t as l}from"./snapshot-CnPDMiyS.js";import{n as u,r as d,t as f}from"./panel-rpc-BPwAqRch.js";import{a as p,t as m}from"./providers-B9G2bMde.js";import{r as h,t as g}from"./base64-DzRgusa4.js";import{n as _}from"./bridge-protocol-DdqxTTSu.js";import{t as v}from"./content-type-_QKWY0B2.js";import{a as y,c as b,i as x,l as S,o as C,r as w,s as T,t as E,u as D}from"./lick-manager-ULemXDKa.js";import{a as ee,b as te,d as ne,f as re,g as O,h as ie,i as ae,m as oe,p as se,u as ce,v as le,x as ue,y as de}from"./account-store-CW3jE2sF.js";import{n as fe,s as pe}from"./proxied-fetch-DUC7X0GS.js";import{t as k}from"./runtime-env-DadgceZk.js";import{t as me}from"./slugify-BYJ6QVAt.js";import{r as he}from"./binary-cache-bSOhqXB1.js";import{i as ge,n as _e,r as ve,t as ye}from"./fetch-body-COdvQyTD.js";import{a as be,c as xe,i as Se,o as A,s as j,t as Ce}from"./api-endpoint-Lx_FU5cP.js";import{$ as we,A as M,At as Te,B as N,Bt as P,C as F,Ct as I,D as Ee,Dt as De,E as Oe,Et as ke,F as L,Ft as Ae,G as je,H as Me,I as Ne,It as Pe,J as Fe,K as Ie,L as Le,Lt as Re,M as ze,Mt as Be,N as Ve,Nt as He,O as Ue,Ot as We,P as Ge,Pt as Ke,Q as qe,R as Je,Rt as Ye,S as Xe,St as Ze,T as eee,Tt as Qe,U as $e,V as et,Vt as tt,W as nt,X as rt,Y as it,Z as at,_ as ot,_t as st,a as ct,at as lt,b as ut,bt as dt,c as ft,ct as pt,d as tee,dt as mt,et as nee,f as ht,ft as gt,g as _t,gt as R,h as vt,ht as z,i as yt,it as bt,j as xt,jt as St,k as Ct,kt as wt,l as Tt,lt as Et,m as Dt,mt as Ot,nt as kt,o as At,ot as jt,p as Mt,pt as Nt,q as Pt,rt as ree,s as Ft,st as iee,t as It,tt as Lt,u as Rt,ut as zt,v as Bt,vt as Vt,w as Ht,wt as Ut,x as Wt,xt as B,y as Gt,yt as Kt,z as qt,zt as Jt}from"./core-CbzVRzJt.js";import{a as Yt}from"./models-4WTk3EBD.js";import{o as Xt,t as Zt}from"./compat-uEPf6-XW.js";import{t as Qt}from"./__vite-browser-external-5eBdwsFd.js";import{n as $t,r as en}from"./attachments-u2K0aIPI.js";import{i as tn,n as nn,r as rn,t as aee}from"./context-compaction-DRymamfD.js";import{n as oee,t as see}from"./mime-types-D7IV6i7k.js";import{t as an}from"./secrets-bridge-client-C3MaYf_O.js";import{t as on}from"./image-markers-DuyWsic3.js";import{i as sn,r as cee}from"./budget-usage-source-8V_0_Lud.js";import{a as cn,i as ln,n as un,t as dn}from"./path-utils-DNJG-zQf.js";import{a as fn,i as pn,n as mn,r as hn,t as gn}from"./agent-bridge-DClELdY1.js";import{C as _n,D as vn,O as yn,S as bn,T as xn,_ as Sn,a as Cn,c as wn,d as Tn,f as En,g as Dn,h as On,k as kn,l as An,m as jn,n as Mn,o as Nn,p as Pn,r as Fn,s as In,t as lee,u as uee,v as Ln,w as Rn,x as dee}from"./record-CUBwpX6h.js";import{a as zn,c as Bn,i as fee,l as Vn,n as Hn,o as pee,r as Un,s as mee,t as Wn,u as Gn}from"./descriptor-ZWA6ck4d.js";import{a as Kn,c as qn,i as Jn,l as Yn,o as Xn,r as Zn,s as Qn,u as $n}from"./agent-message-to-chat-xGeYopQz.js";import{n as er,t as tr}from"./thinking-level-5x0UAu9N.js";import{n as nr,t as rr}from"./types-Dgm4REV3.js";import{i as ir}from"./mount-index-D9w_zMSm.js";import{a as ar,c as or,i as sr,l as cr,n as lr,o as ur,r as dr,s as fr,u as pr}from"./mount-CD47fnQP.js";import{o as mr}from"./mount-table-store-DrF_Ifaz.js";import{t as hr}from"./remote-cache-BE5T1-53.js";import{i as gr,n as _r,r as vr}from"./fs-CA1eGBjq.js";import{r as yr,t as br}from"./mount-recovery-B1OZnCNp.js";import{r as xr,t as Sr}from"./key-CRGEBjHQ.js";import{a as Cr,c as wr,i as Tr,n as Er,o as Dr,r as Or,s as kr}from"./lick-urls-BX4Jyu_T.js";import{C as Ar,D as jr,E as Mr,S as Nr,_ as Pr,a as Fr,b as Ir,d as Lr,g as Rr,h as zr,m as Br,n as Vr,o as Hr,r as Ur,s as Wr,t as Gr,u as Kr,w as qr,y as Jr}from"./db-DSIYsBgP.js";import"./tray-storage-keys-DbThbnIh.js";import"./tray-runtime-config-C3Ti4Pik.js";import{n as Yr,r as Xr,t as Zr}from"./slicc-version-gM32b-cO.js";import{a as Qr,i as hee,n as V,r as $r,t as gee}from"./browser-q8slJ96R.js";import{t as H}from"./subcommand-flags-BZi7j78Q.js";import{n as ei,r as ti,t as ni}from"./subcommand-help-CgO7wRS5.js";import{a as _ee,i as vee,n as yee,r as bee}from"./cost-command-B5aRQX4l.js";import{a as xee,c as ri,d as See,f as ii,h as ai,i as Cee,l as oi,m as si,n as ci,o as wee,p as li,r as ui,s as Tee,t as Eee,u as Dee}from"./sudoers-KgJRnN4b.js";import{a as di,i as fi,n as pi,o as mi,r as hi,s as gi}from"./skills-B4AcVnHX.js";import{a as _i,c as vi,i as yi,l as bi,n as xi,o as Si,r as Ci,t as wi}from"./types-BfwydWt7.js";import{n as Ti,t as Ei}from"./boundary-Cp9c_bPu.js";import"./rest-paths-Dia19u9P.js";import{t as Di}from"./html-B_Hg2WOy.js";import{n as Oi,t as ki}from"./llm-session-id-BZyXP_j2.js";import{a as Ai,i as ji}from"./frozen-archive-format-CP0rleV0.js";import{n as Mi,r as Ni}from"./derive-TWFNEJkb.js";import{i as Pi,r as Fi}from"./browser-2rCVqcqy.js";import{n as Ii,t as Li}from"./safe-buffer-OLJ0qaLt.js";import"./global-db-DJXlpNui.js";import{S as Ri,_ as zi,a as Bi,b as Vi,c as Hi,d as Ui,f as Wi,g as Gi,h as Ki,i as qi,l as Ji,n as Yi,o as Xi,p as Zi,r as Qi,s as $i,t as ea,u as ta,v as U,x as na,y as ra}from"./state-CVrrA2OS.js";import{a as ia,i as aa,r as oa,t as sa}from"./git-config-Bdgu8kD2.js";import{a as ca,c as la,i as ua,o as da,r as fa,s as pa,t as ma}from"./script-catalog-Bt94D0RP.js";import{t as ha}from"./process-manager-BkhAohXT.js";import{A as ga,C as _a,F as va,N as ya,P as ba,_ as xa,a as Sa,b as Ca,c as wa,d as Ta,f as Ea,g as Da,h as Oa,i as ka,j as Aa,l as ja,m as Ma,n as Na,o as Pa,p as Fa,r as Ia,s as La,t as Ra,u as za,v as Ba,x as Va,y as Ha}from"./shared-vu5AooI5.js";import{t as Ua}from"./realm-browser-fetch-V3uggGbM.js";import{n as Wa,t as Ga}from"./esbuild-wasm-L2Rk3D-4.js";import{n as Ka,t as qa}from"./wasm-compiler-Ct7QZURL.js";import{n as Ja,r as Ya,t as Xa}from"./just-bash-compat-_TMo8UnL.js";import{_ as Za,a as Qa,c as $a,f as eo,g as to,h as no,l as ro,m as io,n as ao,p as oo,r as so,u as co,v as lo,y as uo}from"./github-zip-B9lV3nxS.js";import{a as fo,c as po,d as mo,f as ho,i as go,l as _o,n as vo,o as yo,p as bo,r as xo,s as So,u as Co}from"./github-install-D_hW3Upl.js";import{n as Oee,t as kee}from"./magick-wasm-IdXcHdTy.js";import{i as Aee,n as wo,r as jee,t as To}from"./pdf-raster-BWk6ezTX.js";import{a as Mee,c as Nee,d as Pee,f as Fee,i as Iee,l as Lee,n as Ree,o as zee,p as Bee,r as Eo,s as Vee,t as Hee,u as Uee}from"./installer-DK4dNFOa.js";import{n as Do,r as Oo,t as Wee}from"./extension-media-capture-I_fwSF5G.js";import{t as Gee}from"./local-llm-CPxw769h.js";import{t as Kee}from"./client-C6Cmi9c4.js";import{t as qee}from"./redirect-uri-BKkf61lT.js";let ko=null;function Jee(e){ko=e!==null&&Number.isFinite(e)&&e>0?e:null}function Yee(){if(ko!==null)return ko;let e=globalThis.performance?.timeOrigin;return typeof e==`number`&&Number.isFinite(e)&&e>0?e:Date.now()}const Xee=[`/workspace`,`/shared`,`/scoops`,`/home`];var Ao=class{pending=new Map;issue(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{this.pending.delete(e),i(Error(n))},t);this.pending.set(e,{resolve:r,reject:i,timer:a})})}has(e){return this.pending.has(e)}resolve(e,t){this.take(e)?.resolve(t)}reject(e,t){this.take(e)?.reject(t)}rejectAll(e){for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}get size(){return this.pending.size}take(e){let t=this.pending.get(e);if(t)return this.pending.delete(e),clearTimeout(t.timer),t}};function jo(e,t,n,r){return new Promise((i,a)=>{if(r?.signal?.aborted){a(r.error());return}let o=null,s=!1,c,l=()=>{s=!0,clearTimeout(u),c&&r?.signal?.removeEventListener(`abort`,c),o?.()},u=setTimeout(()=>{l(),a(Error(n))},t);r?.signal&&(c=()=>{l(),a(r.error())},r.signal.addEventListener(`abort`,c,{once:!0})),o=e(e=>{l(),i(e)}),s&&o()})}const Mo=r(`cdp`);function Zee(e){return e===4001?`CDP connection superseded by another SLICC tab/window on this instance`:e===4002?`CDP connection reset by proxy (upstream Chrome connection was re-established)`:`CDP connection closed`}var Qee=class{ws=null;nextId=1;_superseded=!1;pending=new Ao;listeners=new Map;_state=`disconnected`;stateListeners=new Set;lastNotifiedState=`disconnected`;lastNotifiedReason;get state(){return this._state}onStateChange(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}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,Mo.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Mo.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(),Mo.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};t&&(a.params=t),n&&(a.sessionId=n),Mo.debug(`Send`,{method:e,id:i,sessionId:n});let o=this.pending.issue(i,r,`CDP command timed out after ${r}ms: ${e}`);return this.ws.send(JSON.stringify(a)),o}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 jo(t=>(this.on(e,t),()=>this.off(e,t)),t,`Timed out waiting for event: ${e}`)}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Mo.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Mo.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;Mo.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){e===4001?(this._superseded=!0,Mo.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?Mo.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):Mo.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(Zee(e))}cleanup(e=`CDP client disconnected`){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(e),this.notifyState(`disconnected`,e)}notifyState(e,t){if(e!==this.lastNotifiedState||t!==this.lastNotifiedReason){this.lastNotifiedState=e,this.lastNotifiedReason=t;for(let n of this.stateListeners)try{n(e,t)}catch{}}}},No=class extends Error{step;name=`CommandAbortedError`;constructor(e){super(`Browser command aborted while ${e}. A CDP round trip already in flight cannot be cancelled, so it may still have been applied to the page; nothing after it was started.`),this.step=e}};function Po(e,t){if(e?.aborted)throw new No(t)}function $ee(e,t){return e?{signal:e,error:()=>new No(t)}:void 0}function ete(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new No(n));return}let a=()=>{clearTimeout(o),i(new No(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function tte(e,t,n){return t?t.aborted?Promise.reject(new No(n)):new Promise((r,i)=>{let a=()=>i(new No(n));t.addEventListener(`abort`,a,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})}):e}const Fo=r(`har-recorder`);var nte=class{recordings=new Map;client;fs;eventCleanup=new Map;constructor(e,t){this.client=e,this.fs=t}async startRecording(e,t,n,r){let i=`rec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;Po(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Po(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Po(r,`about to read the URL of tab ${e}`);let a=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,o={id:i,targetId:e,sessionId:t,filterCode:n,pendingRequests:new Map,entries:[],startTime:Date.now(),currentUrl:a,snapshotCount:0};return this.recordings.set(i,o),this.setupEventListeners(o),await this.ensureDir(`/recordings/${i}`),Fo.debug(`Started recording`,{recordingId:i,targetId:e,currentUrl:a}),i}setupEventListeners(e){let{sessionId:t,id:n}=e,r=n=>{let r=n;r.sessionId===t&&this.handleRequestWillBeSent(e,r)},i=n=>{let r=n;r.sessionId===t&&this.handleResponseReceived(e,r)},a=r=>{let i=r;i.sessionId===t&&this.handleLoadingFinished(e,i).catch(e=>{Fo.error(`Failed to process loadingFinished event`,{recordingId:n,requestId:i.requestId,error:e instanceof Error?e.message:String(e)})})},o=n=>{let r=n;r.sessionId===t&&this.handleLoadingFailed(e,r)},s=r=>{let i=r;if(i.sessionId!==t)return;let a=i.frame;if(!a?.parentId&&a?.url){let t=[...e.entries],r=e.currentUrl;e.currentUrl=a.url,e.entries=[],e.pendingRequests.clear(),this.saveSnapshotWithEntries(e,`navigation`,t,r).catch(e=>{Fo.error(`Failed to save navigation snapshot`,{recordingId:n,error:e instanceof Error?e.message:String(e)})})}};this.client.on(`Network.requestWillBeSent`,r),this.client.on(`Network.responseReceived`,i),this.client.on(`Network.loadingFinished`,a),this.client.on(`Network.loadingFailed`,o),this.client.on(`Page.frameNavigated`,s),this.eventCleanup.set(n,()=>{this.client.off(`Network.requestWillBeSent`,r),this.client.off(`Network.responseReceived`,i),this.client.off(`Network.loadingFinished`,a),this.client.off(`Network.loadingFailed`,o),this.client.off(`Page.frameNavigated`,s)})}handleRequestWillBeSent(e,t){let{requestId:n,request:r,timestamp:i}=t;!n||!r||i==null||e.pendingRequests.set(n,{requestId:n,startTime:i*1e3,request:{method:r.method,url:r.url,headers:r.headers,postData:r.postData}})}handleResponseReceived(e,t){let{requestId:n,response:r}=t;if(!n||!r)return;let i=e.pendingRequests.get(n);i&&(i.response={status:r.status,statusText:r.statusText,headers:r.headers,mimeType:r.mimeType},i.timing=r.timing)}async handleLoadingFinished(e,t){let{requestId:n,timestamp:r}=t;if(!n||r==null)return;let i=e.pendingRequests.get(n);if(!i)return;i.endTime=r*1e3;try{let t=await this.client.send(`Network.getResponseBody`,{requestId:n},e.sessionId);i.responseBody=t.body,i.responseBodyBase64=t.base64Encoded===!0}catch{}let a=this.buildHarEntry(i);a&&e.entries.push(a),e.pendingRequests.delete(n)}handleLoadingFailed(e,t){let{requestId:n}=t;n&&e.pendingRequests.delete(n)}buildHarEntry(e){if(!e.response)return null;let{request:t,response:n,timing:r,startTime:i,endTime:a,responseBody:o,responseBodyBase64:s}=e,c=a?a-i:0,l=[];try{let e=new URL(t.url);l=Array.from(e.searchParams.entries()).map(([e,t])=>({name:e,value:t}))}catch{}let u=r?(()=>{let e=(e,t)=>{if(e==null||t==null||e<0||t<0)return-1;let n=t-e;return n>=0?n:-1},t=r.dnsStart>=0?r.dnsStart:r.connectStart>=0?r.connectStart:0;return{blocked:t>0?t:-1,dns:e(r.dnsStart,r.dnsEnd),connect:e(r.connectStart,r.connectEnd),ssl:e(r.sslStart,r.sslEnd),send:e(r.sendStart,r.sendEnd),wait:e(r.sendEnd,r.receiveHeadersStart),receive:e(r.receiveHeadersStart,r.receiveHeadersEnd)}})():{blocked:-1,dns:-1,connect:-1,ssl:-1,send:0,wait:c,receive:0},d={size:o?.length??0,mimeType:n.mimeType??`application/octet-stream`};o&&(d.text=o,s&&(d.encoding=`base64`));let f;return t.postData&&(f={mimeType:t.headers[`content-type`]??t.headers[`Content-Type`]??`text/plain`,text:t.postData}),{startedDateTime:new Date(i).toISOString(),time:c,request:{method:t.method,url:t.url,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(t.headers).map(([e,t])=>({name:e,value:t})),queryString:l,postData:f,headersSize:-1,bodySize:t.postData?.length??0},response:{status:n.status,statusText:n.statusText,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(n.headers).map(([e,t])=>({name:e,value:t})),content:d,redirectURL:n.headers.location??n.headers.Location??``,headersSize:-1,bodySize:d.size},cache:{},timings:u}}async saveSnapshot(e,t){return this.saveSnapshotWithEntries(e,t,e.entries,e.currentUrl)}async applyFilter(e,t){return rte(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Fo.debug(`No entries to save`,{recordingId:e.id,trigger:t}),null;let i=e.filterCode?await this.applyFilter(n,e.filterCode):n;if(i.length===0)return Fo.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=new Date().toISOString().replace(/[:.]/g,`-`),o=this.urlToSlug(r),s=`${e.snapshotCount.toString().padStart(3,`0`)}-${a}-${t}-${o}.har`,c=`/recordings/${e.id}/${s}`,l={log:{version:`1.2`,creator:{name:`SLICC HAR Recorder`,version:`1.0.0`},entries:i}};return await this.fs.writeFile(c,JSON.stringify(l,null,2)),Fo.debug(`Saved HAR snapshot`,{recordingId:e.id,path:c,entryCount:i.length}),c}urlToSlug(e){try{let t=new URL(e);return`${t.hostname}${t.pathname}`.replace(/[^a-zA-Z0-9]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).slice(0,50)||`page`}catch{return`page`}}async stopRecording(e){let t=this.recordings.get(e);if(!t)throw Error(`Recording not found: ${e}`);await this.saveSnapshot(t,`close`);let n=this.eventCleanup.get(e);n&&(n(),this.eventCleanup.delete(e));try{await this.client.send(`Network.disable`,{},t.sessionId)}catch{}this.recordings.delete(e);let r=`/recordings/${e}`;return Fo.debug(`Stopped recording`,{recordingId:e,snapshotCount:t.snapshotCount}),r}getRecording(e){return this.recordings.get(e)}getRecordingByTarget(e){for(let[t,n]of this.recordings)if(n.targetId===e)return t}async ensureDir(e){await this.fs.mkdir(e,{recursive:!0})}};function rte(e,t){try{let n=Function(`entry`,`return (${t})(entry);`),r=[];for(let t of e)try{let e=n(t);if(e===!1)continue;typeof e==`object`&&e?r.push(e):r.push(t)}catch(e){Fo.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Fo.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const Io=`(function() {
|
|
1
|
+
import{i as e,n as t,t as n}from"./rolldown-runtime-Dd_uD5pT.js";import{t as r}from"./logger-LESFN7Hj.js";import{a as i,i as a,n as o,o as s,r as c,t as l}from"./snapshot-Ctd5h8ek.js";import{n as u,r as d,t as f}from"./panel-rpc-BPwAqRch.js";import{a as p,t as m}from"./providers-Cse0ZxeX.js";import{r as h,t as g}from"./base64-DzRgusa4.js";import{n as _}from"./bridge-protocol-DdqxTTSu.js";import{t as v}from"./content-type-_QKWY0B2.js";import{a as y,c as b,i as x,l as S,o as C,r as w,s as T,t as E,u as D}from"./lick-manager-ULemXDKa.js";import{a as ee,b as te,d as ne,f as re,g as O,h as ie,i as ae,m as oe,p as se,u as ce,v as le,x as ue,y as de}from"./account-store-BOfP1pcJ.js";import{n as fe,s as pe}from"./proxied-fetch-DUC7X0GS.js";import{t as k}from"./runtime-env-DadgceZk.js";import{t as me}from"./slugify-BYJ6QVAt.js";import{r as he}from"./binary-cache-bSOhqXB1.js";import{i as ge,n as _e,r as ve,t as ye}from"./fetch-body-COdvQyTD.js";import{a as be,c as xe,i as Se,o as A,s as j,t as Ce}from"./api-endpoint-Lx_FU5cP.js";import{$ as we,A as M,At as Te,B as N,Bt as P,C as F,Ct as I,D as Ee,Dt as De,E as Oe,Et as ke,F as L,Ft as Ae,G as je,H as Me,I as Ne,It as Pe,J as Fe,K as Ie,L as Le,Lt as Re,M as ze,Mt as Be,N as Ve,Nt as He,O as Ue,Ot as We,P as Ge,Pt as Ke,Q as qe,R as Je,Rt as Ye,S as Xe,St as Ze,T as eee,Tt as Qe,U as $e,V as et,Vt as tt,W as nt,X as rt,Y as it,Z as at,_ as ot,_t as st,a as ct,at as lt,b as ut,bt as dt,c as ft,ct as pt,d as tee,dt as mt,et as nee,f as ht,ft as gt,g as _t,gt as R,h as vt,ht as z,i as yt,it as bt,j as xt,jt as St,k as Ct,kt as wt,l as Tt,lt as Et,m as Dt,mt as Ot,nt as kt,o as At,ot as jt,p as Mt,pt as Nt,q as Pt,rt as ree,s as Ft,st as iee,t as It,tt as Lt,u as Rt,ut as zt,v as Bt,vt as Vt,w as Ht,wt as Ut,x as Wt,xt as B,y as Gt,yt as Kt,z as qt,zt as Jt}from"./core-CbzVRzJt.js";import{a as Yt}from"./models-4WTk3EBD.js";import{o as Xt,t as Zt}from"./compat-uEPf6-XW.js";import{t as Qt}from"./__vite-browser-external-5eBdwsFd.js";import{n as $t,r as en}from"./attachments-u2K0aIPI.js";import{i as tn,n as nn,r as rn,t as aee}from"./context-compaction-DRymamfD.js";import{n as oee,t as see}from"./mime-types-D7IV6i7k.js";import{t as an}from"./secrets-bridge-client-C3MaYf_O.js";import{t as on}from"./image-markers-DuyWsic3.js";import{i as sn,r as cee}from"./budget-usage-source-CjET0w7O.js";import{a as cn,i as ln,n as un,t as dn}from"./path-utils-DNJG-zQf.js";import{a as fn,i as pn,n as mn,r as hn,t as gn}from"./agent-bridge-G4SJSVj_.js";import{C as _n,D as vn,O as yn,S as bn,T as xn,_ as Sn,a as Cn,c as wn,d as Tn,f as En,g as Dn,h as On,k as kn,l as An,m as jn,n as Mn,o as Nn,p as Pn,r as Fn,s as In,t as lee,u as uee,v as Ln,w as Rn,x as dee}from"./record-CUBwpX6h.js";import{a as zn,c as Bn,i as fee,l as Vn,n as Hn,o as pee,r as Un,s as mee,t as Wn,u as Gn}from"./descriptor-ZWA6ck4d.js";import{a as Kn,c as qn,i as Jn,l as Yn,o as Xn,r as Zn,s as Qn,u as $n}from"./agent-message-to-chat-xGeYopQz.js";import{n as er,t as tr}from"./thinking-level-5x0UAu9N.js";import{n as nr,t as rr}from"./types-Dgm4REV3.js";import{i as ir}from"./mount-index-D9w_zMSm.js";import{a as ar,c as or,i as sr,l as cr,n as lr,o as ur,r as dr,s as fr,u as pr}from"./mount-CJjAtfYn.js";import{o as mr}from"./mount-table-store-DrF_Ifaz.js";import{t as hr}from"./remote-cache-BE5T1-53.js";import{i as gr,n as _r,r as vr}from"./fs-D-gRojJc.js";import{r as yr,t as br}from"./mount-recovery-BbM7KXdZ.js";import{r as xr,t as Sr}from"./key-CRGEBjHQ.js";import{a as Cr,c as wr,i as Tr,n as Er,o as Dr,r as Or,s as kr}from"./lick-urls-BX4Jyu_T.js";import{C as Ar,D as jr,E as Mr,S as Nr,_ as Pr,a as Fr,b as Ir,d as Lr,g as Rr,h as zr,m as Br,n as Vr,o as Hr,r as Ur,s as Wr,t as Gr,u as Kr,w as qr,y as Jr}from"./db-DSIYsBgP.js";import"./tray-storage-keys-DbThbnIh.js";import"./tray-runtime-config-C3Ti4Pik.js";import{n as Yr,r as Xr,t as Zr}from"./slicc-version-tRk2NmiN.js";import{a as Qr,i as hee,n as V,r as $r,t as gee}from"./browser-q8slJ96R.js";import{t as H}from"./subcommand-flags-BZi7j78Q.js";import{n as ei,r as ti,t as ni}from"./subcommand-help-CgO7wRS5.js";import{a as _ee,i as vee,n as yee,r as bee}from"./cost-command-B5aRQX4l.js";import{a as xee,c as ri,d as See,f as ii,h as ai,i as Cee,l as oi,m as si,n as ci,o as wee,p as li,r as ui,s as Tee,t as Eee,u as Dee}from"./sudoers-KgJRnN4b.js";import{a as di,i as fi,n as pi,o as mi,r as hi,s as gi}from"./skills-DxNa4Xoh.js";import{a as _i,c as vi,i as yi,l as bi,n as xi,o as Si,r as Ci,t as wi}from"./types-BfwydWt7.js";import{n as Ti,t as Ei}from"./boundary-Cp9c_bPu.js";import"./rest-paths-Dia19u9P.js";import{t as Di}from"./html-B_Hg2WOy.js";import{n as Oi,t as ki}from"./llm-session-id-BZyXP_j2.js";import{a as Ai,i as ji}from"./frozen-archive-format-CP0rleV0.js";import{n as Mi,r as Ni}from"./derive-TWFNEJkb.js";import{i as Pi,r as Fi}from"./browser-2rCVqcqy.js";import{n as Ii,t as Li}from"./safe-buffer-OLJ0qaLt.js";import"./global-db-DJXlpNui.js";import{S as Ri,_ as zi,a as Bi,b as Vi,c as Hi,d as Ui,f as Wi,g as Gi,h as Ki,i as qi,l as Ji,n as Yi,o as Xi,p as Zi,r as Qi,s as $i,t as ea,u as ta,v as U,x as na,y as ra}from"./state-CZURVOkM.js";import{a as ia,i as aa,r as oa,t as sa}from"./git-config-Bdgu8kD2.js";import{a as ca,c as la,i as ua,o as da,r as fa,s as pa,t as ma}from"./script-catalog-Bt94D0RP.js";import{t as ha}from"./process-manager-BkhAohXT.js";import{A as ga,C as _a,F as va,N as ya,P as ba,_ as xa,a as Sa,b as Ca,c as wa,d as Ta,f as Ea,g as Da,h as Oa,i as ka,j as Aa,l as ja,m as Ma,n as Na,o as Pa,p as Fa,r as Ia,s as La,t as Ra,u as za,v as Ba,x as Va,y as Ha}from"./shared-vu5AooI5.js";import{t as Ua}from"./realm-browser-fetch-V3uggGbM.js";import{n as Wa,t as Ga}from"./esbuild-wasm-L2Rk3D-4.js";import{n as Ka,t as qa}from"./wasm-compiler-Ct7QZURL.js";import{n as Ja,r as Ya,t as Xa}from"./just-bash-compat-_TMo8UnL.js";import{_ as Za,a as Qa,c as $a,f as eo,g as to,h as no,l as ro,m as io,n as ao,p as oo,r as so,u as co,v as lo,y as uo}from"./github-zip-Cn_DhUkt.js";import{a as fo,c as po,d as mo,f as ho,i as go,l as _o,n as vo,o as yo,p as bo,r as xo,s as So,u as Co}from"./github-install-WakGuTn3.js";import{n as Oee,t as kee}from"./magick-wasm-IdXcHdTy.js";import{i as Aee,n as wo,r as jee,t as To}from"./pdf-raster-BWk6ezTX.js";import{a as Mee,c as Nee,d as Pee,f as Fee,i as Iee,l as Lee,n as Ree,o as zee,p as Bee,r as Eo,s as Vee,t as Hee,u as Uee}from"./installer-DK4dNFOa.js";import{n as Do,r as Oo,t as Wee}from"./extension-media-capture-I_fwSF5G.js";import{t as Gee}from"./local-llm-DOoj67px.js";import{t as Kee}from"./client-C6Cmi9c4.js";import{t as qee}from"./redirect-uri-BKkf61lT.js";let ko=null;function Jee(e){ko=e!==null&&Number.isFinite(e)&&e>0?e:null}function Yee(){if(ko!==null)return ko;let e=globalThis.performance?.timeOrigin;return typeof e==`number`&&Number.isFinite(e)&&e>0?e:Date.now()}const Xee=[`/workspace`,`/shared`,`/scoops`,`/home`];var Ao=class{pending=new Map;issue(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{this.pending.delete(e),i(Error(n))},t);this.pending.set(e,{resolve:r,reject:i,timer:a})})}has(e){return this.pending.has(e)}resolve(e,t){this.take(e)?.resolve(t)}reject(e,t){this.take(e)?.reject(t)}rejectAll(e){for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}get size(){return this.pending.size}take(e){let t=this.pending.get(e);if(t)return this.pending.delete(e),clearTimeout(t.timer),t}};function jo(e,t,n,r){return new Promise((i,a)=>{if(r?.signal?.aborted){a(r.error());return}let o=null,s=!1,c,l=()=>{s=!0,clearTimeout(u),c&&r?.signal?.removeEventListener(`abort`,c),o?.()},u=setTimeout(()=>{l(),a(Error(n))},t);r?.signal&&(c=()=>{l(),a(r.error())},r.signal.addEventListener(`abort`,c,{once:!0})),o=e(e=>{l(),i(e)}),s&&o()})}const Mo=r(`cdp`);function Zee(e){return e===4001?`CDP connection superseded by another SLICC tab/window on this instance`:e===4002?`CDP connection reset by proxy (upstream Chrome connection was re-established)`:`CDP connection closed`}var Qee=class{ws=null;nextId=1;_superseded=!1;pending=new Ao;listeners=new Map;_state=`disconnected`;stateListeners=new Set;lastNotifiedState=`disconnected`;lastNotifiedReason;get state(){return this._state}onStateChange(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}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,Mo.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Mo.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(),Mo.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};t&&(a.params=t),n&&(a.sessionId=n),Mo.debug(`Send`,{method:e,id:i,sessionId:n});let o=this.pending.issue(i,r,`CDP command timed out after ${r}ms: ${e}`);return this.ws.send(JSON.stringify(a)),o}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 jo(t=>(this.on(e,t),()=>this.off(e,t)),t,`Timed out waiting for event: ${e}`)}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Mo.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Mo.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;Mo.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){e===4001?(this._superseded=!0,Mo.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?Mo.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):Mo.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(Zee(e))}cleanup(e=`CDP client disconnected`){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(e),this.notifyState(`disconnected`,e)}notifyState(e,t){if(e!==this.lastNotifiedState||t!==this.lastNotifiedReason){this.lastNotifiedState=e,this.lastNotifiedReason=t;for(let n of this.stateListeners)try{n(e,t)}catch{}}}},No=class extends Error{step;name=`CommandAbortedError`;constructor(e){super(`Browser command aborted while ${e}. A CDP round trip already in flight cannot be cancelled, so it may still have been applied to the page; nothing after it was started.`),this.step=e}};function Po(e,t){if(e?.aborted)throw new No(t)}function $ee(e,t){return e?{signal:e,error:()=>new No(t)}:void 0}function ete(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new No(n));return}let a=()=>{clearTimeout(o),i(new No(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function tte(e,t,n){return t?t.aborted?Promise.reject(new No(n)):new Promise((r,i)=>{let a=()=>i(new No(n));t.addEventListener(`abort`,a,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})}):e}const Fo=r(`har-recorder`);var nte=class{recordings=new Map;client;fs;eventCleanup=new Map;constructor(e,t){this.client=e,this.fs=t}async startRecording(e,t,n,r){let i=`rec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;Po(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Po(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Po(r,`about to read the URL of tab ${e}`);let a=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,o={id:i,targetId:e,sessionId:t,filterCode:n,pendingRequests:new Map,entries:[],startTime:Date.now(),currentUrl:a,snapshotCount:0};return this.recordings.set(i,o),this.setupEventListeners(o),await this.ensureDir(`/recordings/${i}`),Fo.debug(`Started recording`,{recordingId:i,targetId:e,currentUrl:a}),i}setupEventListeners(e){let{sessionId:t,id:n}=e,r=n=>{let r=n;r.sessionId===t&&this.handleRequestWillBeSent(e,r)},i=n=>{let r=n;r.sessionId===t&&this.handleResponseReceived(e,r)},a=r=>{let i=r;i.sessionId===t&&this.handleLoadingFinished(e,i).catch(e=>{Fo.error(`Failed to process loadingFinished event`,{recordingId:n,requestId:i.requestId,error:e instanceof Error?e.message:String(e)})})},o=n=>{let r=n;r.sessionId===t&&this.handleLoadingFailed(e,r)},s=r=>{let i=r;if(i.sessionId!==t)return;let a=i.frame;if(!a?.parentId&&a?.url){let t=[...e.entries],r=e.currentUrl;e.currentUrl=a.url,e.entries=[],e.pendingRequests.clear(),this.saveSnapshotWithEntries(e,`navigation`,t,r).catch(e=>{Fo.error(`Failed to save navigation snapshot`,{recordingId:n,error:e instanceof Error?e.message:String(e)})})}};this.client.on(`Network.requestWillBeSent`,r),this.client.on(`Network.responseReceived`,i),this.client.on(`Network.loadingFinished`,a),this.client.on(`Network.loadingFailed`,o),this.client.on(`Page.frameNavigated`,s),this.eventCleanup.set(n,()=>{this.client.off(`Network.requestWillBeSent`,r),this.client.off(`Network.responseReceived`,i),this.client.off(`Network.loadingFinished`,a),this.client.off(`Network.loadingFailed`,o),this.client.off(`Page.frameNavigated`,s)})}handleRequestWillBeSent(e,t){let{requestId:n,request:r,timestamp:i}=t;!n||!r||i==null||e.pendingRequests.set(n,{requestId:n,startTime:i*1e3,request:{method:r.method,url:r.url,headers:r.headers,postData:r.postData}})}handleResponseReceived(e,t){let{requestId:n,response:r}=t;if(!n||!r)return;let i=e.pendingRequests.get(n);i&&(i.response={status:r.status,statusText:r.statusText,headers:r.headers,mimeType:r.mimeType},i.timing=r.timing)}async handleLoadingFinished(e,t){let{requestId:n,timestamp:r}=t;if(!n||r==null)return;let i=e.pendingRequests.get(n);if(!i)return;i.endTime=r*1e3;try{let t=await this.client.send(`Network.getResponseBody`,{requestId:n},e.sessionId);i.responseBody=t.body,i.responseBodyBase64=t.base64Encoded===!0}catch{}let a=this.buildHarEntry(i);a&&e.entries.push(a),e.pendingRequests.delete(n)}handleLoadingFailed(e,t){let{requestId:n}=t;n&&e.pendingRequests.delete(n)}buildHarEntry(e){if(!e.response)return null;let{request:t,response:n,timing:r,startTime:i,endTime:a,responseBody:o,responseBodyBase64:s}=e,c=a?a-i:0,l=[];try{let e=new URL(t.url);l=Array.from(e.searchParams.entries()).map(([e,t])=>({name:e,value:t}))}catch{}let u=r?(()=>{let e=(e,t)=>{if(e==null||t==null||e<0||t<0)return-1;let n=t-e;return n>=0?n:-1},t=r.dnsStart>=0?r.dnsStart:r.connectStart>=0?r.connectStart:0;return{blocked:t>0?t:-1,dns:e(r.dnsStart,r.dnsEnd),connect:e(r.connectStart,r.connectEnd),ssl:e(r.sslStart,r.sslEnd),send:e(r.sendStart,r.sendEnd),wait:e(r.sendEnd,r.receiveHeadersStart),receive:e(r.receiveHeadersStart,r.receiveHeadersEnd)}})():{blocked:-1,dns:-1,connect:-1,ssl:-1,send:0,wait:c,receive:0},d={size:o?.length??0,mimeType:n.mimeType??`application/octet-stream`};o&&(d.text=o,s&&(d.encoding=`base64`));let f;return t.postData&&(f={mimeType:t.headers[`content-type`]??t.headers[`Content-Type`]??`text/plain`,text:t.postData}),{startedDateTime:new Date(i).toISOString(),time:c,request:{method:t.method,url:t.url,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(t.headers).map(([e,t])=>({name:e,value:t})),queryString:l,postData:f,headersSize:-1,bodySize:t.postData?.length??0},response:{status:n.status,statusText:n.statusText,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(n.headers).map(([e,t])=>({name:e,value:t})),content:d,redirectURL:n.headers.location??n.headers.Location??``,headersSize:-1,bodySize:d.size},cache:{},timings:u}}async saveSnapshot(e,t){return this.saveSnapshotWithEntries(e,t,e.entries,e.currentUrl)}async applyFilter(e,t){return rte(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Fo.debug(`No entries to save`,{recordingId:e.id,trigger:t}),null;let i=e.filterCode?await this.applyFilter(n,e.filterCode):n;if(i.length===0)return Fo.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=new Date().toISOString().replace(/[:.]/g,`-`),o=this.urlToSlug(r),s=`${e.snapshotCount.toString().padStart(3,`0`)}-${a}-${t}-${o}.har`,c=`/recordings/${e.id}/${s}`,l={log:{version:`1.2`,creator:{name:`SLICC HAR Recorder`,version:`1.0.0`},entries:i}};return await this.fs.writeFile(c,JSON.stringify(l,null,2)),Fo.debug(`Saved HAR snapshot`,{recordingId:e.id,path:c,entryCount:i.length}),c}urlToSlug(e){try{let t=new URL(e);return`${t.hostname}${t.pathname}`.replace(/[^a-zA-Z0-9]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).slice(0,50)||`page`}catch{return`page`}}async stopRecording(e){let t=this.recordings.get(e);if(!t)throw Error(`Recording not found: ${e}`);await this.saveSnapshot(t,`close`);let n=this.eventCleanup.get(e);n&&(n(),this.eventCleanup.delete(e));try{await this.client.send(`Network.disable`,{},t.sessionId)}catch{}this.recordings.delete(e);let r=`/recordings/${e}`;return Fo.debug(`Stopped recording`,{recordingId:e,snapshotCount:t.snapshotCount}),r}getRecording(e){return this.recordings.get(e)}getRecordingByTarget(e){for(let[t,n]of this.recordings)if(n.targetId===e)return t}async ensureDir(e){await this.fs.mkdir(e,{recursive:!0})}};function rte(e,t){try{let n=Function(`entry`,`return (${t})(entry);`),r=[];for(let t of e)try{let e=n(t);if(e===!1)continue;typeof e==`object`&&e?r.push(e):r.push(t)}catch(e){Fo.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Fo.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const Io=`(function() {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
// ===== DOM Utilities =====
|
|
@@ -1644,7 +1644,7 @@ except BaseException:
|
|
|
1644
1644
|
`)}}function eH(e,t,n){let r=!!e.env?.NO_COLOR,i=!1,a=0,o=e=>{i=!0,a=e},s=nH(e.stdin??``,o),c=WV(e.argv),l={write:t,end:()=>void 0,isTTY:!r},u={write:n,end:()=>void 0,isTTY:!r};return{processShim:{argv:c,env:e.env,versions:{node:va},version:`v${va}`,platform:`linux`,arch:`x64`,cwd:()=>e.cwd,exit:e=>{let t=Number.isFinite(e)?Number(e):0;throw o(t),new ZV(t)},stdin:s,stdout:l,stderr:u},getDidCallProcessExit:()=>i,getExitCode:()=>a,recordExit:o}}var tH=class extends $I.Stream{isTTY=!1;consumed=!1;flowScheduled=!1;paused=!1;buffer;onExit;constructor(e,t){super(),this.buffer=e,this.onExit=t}read(){return this.consumed?null:(this.consumed=!0,this.buffer.length>0?this.buffer:null)}toString(){return this.buffer}setEncoding(e){return this}pause(){return this.paused=!0,this}resume(){return this.paused=!1,this.scheduleFlow(),this}on(e,t){return super.on(e,t),e===`data`&&this.scheduleFlow(),this}addListener(e,t){return this.on(e,t)}once(e,t){return super.once(e,t),e===`data`&&this.scheduleFlow(),this}scheduleFlow(){this.flowScheduled||(this.flowScheduled=!0,queueMicrotask(()=>this.flush()))}flush(){if(this.paused){this.flowScheduled=!1;return}try{this.consumed||(this.consumed=!0,this.buffer.length>0&&this.emit(`data`,this.buffer)),this.readable=!1,this.emit(`end`),this.emit(`close`)}catch(e){if(e instanceof ZV){this.onExit(e.code);return}throw e}}[Symbol.asyncIterator](){return{next:async()=>this.consumed?{value:void 0,done:!0}:(this.consumed=!0,{value:this.buffer,done:!1})}}};function nH(e,t){return new tH(e,t)}function rH(e){if(e===``)return[];let t=e.split(`
|
|
1645
1645
|
`);return t[t.length-1]===``&&t.pop(),t.map(e=>e.endsWith(`\r`)?e.slice(0,-1):e)}function iH(e){if(typeof e==`string`)return e;if(e&&typeof e.read==`function`){let t=e.read();return typeof t==`string`?t:``}return``}function aH(e){return new TextDecoder(`utf-8`).decode(nI(e))}function oH(e){if(e&&typeof e.write==`function`)return e}var sH=class extends qI{terminal=!1;lines;cursor=0;closed=!1;flushScheduled=!1;output;onExit;constructor(e,t,n){super(),this.lines=rH(aH(iH(e))),this.output=t??n.output,this.onExit=n.onExit}on(e,t){return super.on(e,t),e===`line`&&this.scheduleFlush(),this}once(e,t){return super.once(e,t),e===`line`&&this.scheduleFlush(),this}pause(){return this}resume(){return this}close(){this.closed||(this.closed=!0,this.emit(`close`))}question(e,t,n){let r=typeof t==`function`?t:typeof n==`function`?n:void 0;this.output?.write(String(e));let i=this.cursor<this.lines.length?this.lines[this.cursor++]:``;if(r){queueMicrotask(()=>this.runHandler(()=>r(i)));return}return Promise.resolve(i)}[Symbol.asyncIterator](){return{next:async()=>!this.closed&&this.cursor<this.lines.length?{value:this.lines[this.cursor++],done:!1}:(this.close(),{value:void 0,done:!0})}}scheduleFlush(){this.flushScheduled||this.closed||(this.flushScheduled=!0,queueMicrotask(()=>this.flush()))}flush(){this.flushScheduled=!1,this.runHandler(()=>{for(;!this.closed&&this.cursor<this.lines.length;)this.emit(`line`,this.lines[this.cursor++]);this.close()})}runHandler(e){try{e()}catch(e){if(e instanceof ZV&&this.onExit){this.closed=!0,this.onExit(e.code);return}throw e}}};function cH(e){let t=(t,n)=>{let r,i;if(t&&typeof t==`object`&&`input`in t){let e=t;r=e.input,i=oH(e.output)}else r=t,i=oH(n);if(r==null)throw TypeError(`readline.createInterface: an 'input' stream is required`);return new sH(r,i,e)},n=(...e)=>{let t=e[e.length-1];return typeof t==`function`&&queueMicrotask(()=>t()),!0},r={createInterface:t,Interface:sH,emitKeypressEvents:()=>void 0,cursorTo:n,moveCursor:n,clearLine:n,clearScreenDown:n};return{...r,promises:r}}var lH=class extends Error{status;statusText;url;body;constructor(e,t,n,r){let i=typeof r==`string`&&r?`: ${r.slice(0,200)}`:r&&typeof r==`object`?`: ${uH(r).slice(0,200)}`:``;super(`HTTP ${e} ${t} ${n}${i}`),this.status=e,this.statusText=t,this.url=n,this.body=r,this.name=`HttpError`}};function uH(e){try{return JSON.stringify(e)}catch{return String(e)}}function dH(e){return new Promise(t=>setTimeout(t,e))}function fH(e,t){let n=[];for(let[e,r]of Object.entries(t))if(r!=null){if(Array.isArray(r))for(let t of r)t!=null&&n.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`);else n.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(r))}`)}return n.length===0?e:e+(e.includes(`?`)?`&`:`?`)+n.join(`&`)}function pH(e,t,n){let r;return r=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:e?`${e.endsWith(`/`)?e.slice(0,-1):e}${t.startsWith(`/`)?t:`/${t}`}`:t,n?fH(r,n):r}function mH(e,t){let n={};if(e)for(let[t,r]of Object.entries(e))n[t]=r;if(t)for(let[e,r]of Object.entries(t))n[e]=r;return n}function hH(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`application/json`)||/[+/]json(;|$|\s)/.test(t)}function gH(e){if(!e)return null;let t=e.trim();if(!t)return null;if(/^\d+(\.\d+)?$/.test(t)){let e=Number(t);if(Number.isFinite(e)&&e>=0)return Math.round(e*1e3)}let n=Date.parse(t);if(Number.isFinite(n)){let e=n-Date.now();return e>0?e:0}return null}async function _H(e){if(hH(e.headers.get(`content-type`))){let t=await e.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}return e.text()}function vH(e,t){if(e!=null)return typeof e==`string`||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob||typeof FormData<`u`&&e instanceof FormData||typeof URLSearchParams<`u`&&e instanceof URLSearchParams||typeof ReadableStream<`u`&&e instanceof ReadableStream?e:typeof e==`object`?(Object.keys(t).some(e=>e.toLowerCase()===`content-type`)||(t[`Content-Type`]=`application/json`),JSON.stringify(e)):String(e)}function yH(e,t){return Object.keys(e).some(e=>e.toLowerCase()===t.toLowerCase())}async function bH(e,t,n){let r=await t(n);r&&!yH(e,`authorization`)&&(e.Authorization=`Bearer ${r}`)}function xH(e,t){if(!t)return{signal:e,clearTimeout:null};let n=new AbortController,r=setTimeout(()=>n.abort(Error(`timeout`)),t),i=()=>clearTimeout(r);return e?{signal:AbortSignal.any([e,n.signal]),clearTimeout:i}:{signal:n.signal,clearTimeout:i}}function SH(e,t){return{body:t,headers:Object.fromEntries(e.headers.entries()),status:e.status}}async function CH(e,t){let n=await _H(e);return t?SH(e,n):n}async function wH(e,t){let n=await _H(e).catch(()=>null);throw new lH(e.status,e.statusText,t,n)}function TH(e,t){let n=gH(e.headers.get(`retry-after`));return n===null?500*2**t:n}async function EH(e,t,n,r){let i=null;for(let a=0;a<e.maxAttempts;a++){let{signal:o,clearTimeout:s}=xH(r.signal,e.timeoutMs),c=o?{...n,signal:o}:n,l;try{l=await e.fetch(t,c)}finally{s?.()}if(i=l,l.ok)return CH(l,r.raw);if(!(a+1<e.maxAttempts&&e.retryOn.has(l.status)))return wH(l,t);await e.sleep(TH(l,a))}if(i)return wH(i,t);throw Error(`http: no attempts made for ${n.method??`GET`} ${t}`)}function DH(e){let t=e.sleep??dH;function n(n){let r=new Set(n.retry?.on??[]),i=Math.max(1,Math.trunc(n.retry?.maxAttempts??1));async function a(a,o,s={}){let c=pH(n.baseUrl,o,s.params),l=mH(n.headers,s.headers);n.token&&await bH(l,n.token,{method:a,path:o,url:c});let u=vH(s.body,l),d={method:a,headers:l};return u!==void 0&&(d.body=u),EH({fetch:e.fetch,sleep:t,maxAttempts:i,retryOn:r,timeoutMs:n.timeoutMs},c,d,s)}return Object.freeze({get:((e,t)=>a(`GET`,e,t)),post:((e,t)=>a(`POST`,e,t)),put:((e,t)=>a(`PUT`,e,t)),patch:((e,t)=>a(`PATCH`,e,t)),delete:((e,t)=>a(`DELETE`,e,t))})}return Object.freeze({client:n})}function OH(e){let t=new TextEncoder().encode(e),n=``;for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return btoa(n)}function kH(e,t,n){let r=[];t.model&&r.push(`--model`,String(t.model)),t.thinking&&r.push(`--thinking`,String(t.thinking)),t.schema&&r.push(`--schema-b64`,OH(JSON.stringify(t.schema))),t.readOnly!==void 0&&r.push(`--read-only`,Array.isArray(t.readOnly)?t.readOnly.join(`,`):String(t.readOnly));let i=t.cwd===void 0?n||`.`:String(t.cwd),a=t.allowedCommands===void 0?`*`:String(t.allowedCommands);return[`agent`,...r,i,a,String(e)]}function AH(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(kH(t,i,n)),o=typeof a.exitCode==`number`?a.exitCode:0;return{finalText:String(a.stdout??``).replace(/\n+$/,``),exitCode:o,stderr:String(a.stderr??``).replace(/\n+$/,``)}},i=(async(e,t)=>{let n=t??{},i=await r(e,n);if(i.exitCode!==0)throw Error(`agent: exited with code ${i.exitCode}${i.stderr?`: ${i.stderr}`:``}`);if(n.schema)try{return JSON.parse(i.finalText)}catch{throw Error(`agent: schema response was not valid JSON (exit ${i.exitCode}): ${i.finalText.slice(0,200)}`)}return i.finalText});return i.spawn=r,i}function jH(e){if(typeof e==`string`)return e;if(e&&typeof e==`object`&&typeof e.targetId==`string`)return e.targetId;throw TypeError(`browser: expected a tab handle or targetId string`)}function MH(e){function t(t){return{...t,async update(n){let r={};return n.urlMatch!==void 0&&(r.urlMatch=n.urlMatch===null?null:n.urlMatch instanceof RegExp?n.urlMatch.source:n.urlMatch),n.filter!==void 0&&(r.filter=n.filter),e.call(`browser`,`wsUpdate`,[t.id,r])},async close(){return e.call(`browser`,`wsClose`,[t.id])}}}return{on(n,r={}){let i=jH(n),a=r.urlMatch===void 0?void 0:r.urlMatch instanceof RegExp?r.urlMatch.source:r.urlMatch,o,s={filter(e){if(typeof e==`function`||typeof e==`string`)throw TypeError(`browser.websocket: filter must be a declarative JSON object, not a function or string`);return o=e,s},async forward(n){return t(await e.call(`browser`,`wsObserve`,[{targetId:i,urlMatch:a,filter:o,forward:n}]))}};return s},async list(){return e.call(`browser`,`wsList`,[])}}}async function NH(e,t){if(!e&&!(t instanceof Request))return;let n=t instanceof Request?t:null,r=(e?.method??n?.method??`GET`).toUpperCase(),i={};if(e?.headers){if(e.headers instanceof Headers)e.headers.forEach((e,t)=>{i[t]=e});else if(Array.isArray(e.headers))for(let[t,n]of e.headers)i[t]=n;else Object.assign(i,e.headers)}else n&&n.headers.forEach((e,t)=>{i[t]=e});let a,o;if(r!==`GET`&&r!==`HEAD`&&e?.body!==void 0&&e?.body!==null&&e?.body!==``){let t=await PH(e.body);a=t.body,o=t.defaultContentType}return o&&!Object.keys(i).some(e=>e.toLowerCase()===`content-type`)&&(i[`Content-Type`]=o),{method:r,headers:i,body:a}}async function PH(e){if(typeof e==`string`)return{body:e};if(e instanceof URLSearchParams)return{body:e.toString(),defaultContentType:`application/x-www-form-urlencoded;charset=UTF-8`};if(e instanceof Blob)return{body:new Uint8Array(await e.arrayBuffer()),defaultContentType:e.type||`application/octet-stream`};if(e instanceof ArrayBuffer)return{body:new Uint8Array(e).slice(),defaultContentType:`application/octet-stream`};if(ArrayBuffer.isView(e))return{body:new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice(),defaultContentType:`application/octet-stream`};if(or(e)){let t=await fr(e);return{body:t.bytes,defaultContentType:t.contentType}}throw typeof ReadableStream<`u`&&e instanceof ReadableStream?Error(`node fetch shim: ReadableStream request bodies are not supported (collect into a Uint8Array or string before calling fetch)`):Error(`node fetch shim: unsupported request body type (${Object.prototype.toString.call(e)}); use a string, Uint8Array, ArrayBuffer, Blob, FormData, or URLSearchParams`)}function FH(e){return{findTab:t=>e.call(`browser`,`findTab`,[LH(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,RH(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[jH(t),IH(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[jH(t),IH(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[jH(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[jH(t),n]),fetch:(t,n,r={})=>Ua(n,r).then(n=>e.call(`browser`,`evalAsync`,[jH(t),n])),websocket:MH(e)}}function IH(e,t){if(typeof e==`function`)return`(${e.toString()})()`;if(typeof e==`string`)return e;throw TypeError(`browser.eval/evalAsync: source must be a function or string`)}function LH(e){let t={};return e.domain!==void 0&&(t.domain=e.domain),e.urlMatch!==void 0&&(t.urlMatch=e.urlMatch instanceof RegExp?e.urlMatch.source:e.urlMatch),t}function RH(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function zH(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function BH(e,t,n,r){let i=async()=>{if(!t?.wasUsed())return;let n=t.getMutations();if(n.created.length||n.modified.length||n.deleted.length)try{await e.call(`vfs`,`flushWrites`,[n])}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`[realm-exec] pre-exec sync-fs flush failed (will retry at exit): ${t}`);return}t.resetBaseline()},a=async(i=!1)=>{if(t?.wasUsed())try{let r=await e.call(`vfs`,`snapshot`,[n]);i?t.applySnapshotPreservingMutations(r):t.applySnapshot(r)}catch(e){let t=e instanceof Error?e.message:String(e);r?.(`[sync-fs] re-snapshot after exec failed: ${t}\n`)}},o=async t=>{await i();try{return await e.call(`exec`,`run`,[t])}finally{await a()}},s=async t=>{await i();try{return await e.call(`exec`,`spawn`,[t])}finally{await a()}},c=1,l=Object.assign(o,{spawn:s,start:(t,n)=>{let r=c++,o=[],s=!1,l=!1,u=!1,d,f,p=new Promise((e,t)=>{d=e,f=t}),m=()=>{if(s||u||l)return;l=!0;let c=o.length>0?o.join(``):n?.stdin,p={};c!==void 0&&(p.stdin=c),n?.stdinKind!==void 0&&(p.stdinKind=n.stdinKind),n?.args!==void 0&&(p.args=n.args),(async()=>{try{if(await i(),u){await a(!0);return}s=!0;let n=await e.call(`exec`,`start`,[r,t,p]);await a(!0),d(n)}catch(e){await a(!0),f(e)}})()};return{kill:t=>s?e.call(`exec`,`kill`,[r,t]):(u=!0,d({stdout:``,stderr:``,exitCode:zH(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}const VH=new Set([204,205,304]),HH=new Set([`content-encoding`,`transfer-encoding`,`content-length`]);function UH(e,t){let n=WH(e.body),r=GH(e.headers),i=VH.has(e.status)||n.byteLength===0,a=new Response(i?null:n,{status:e.status,statusText:e.statusText,headers:r});try{Object.defineProperty(a,"url",{value:e.url||t,writable:!1,configurable:!0,enumerable:!1})}catch{}return KH(a,n),a}function WH(e){return e.byteLength===0?new Uint8Array:e.slice()}function GH(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(!HH.has(n.toLowerCase()))try{t.set(n,r)}catch{}return t}function KH(e,t){let n=!1,r=()=>{if(n)throw TypeError(`Failed to read response body: body already used`);return n=!0,t},i=async()=>new TextDecoder().decode(r()),a=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);Object.defineProperties(e,{text:{value:i,configurable:!0},json:{value:async()=>JSON.parse(await i()),configurable:!0},arrayBuffer:{value:async()=>a(r()),configurable:!0},blob:{value:async()=>new Blob([a(r())]),configurable:!0}})}function qH(e){if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(e instanceof ArrayBuffer)return new Uint8Array(e);throw TypeError(`expected an ArrayBuffer or typed array`)}function JH(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function YH(e){return e==null?[]:Array.isArray(e)?e:[e]}function XH(e,t){let n=t.handle,r=new Set,i=new Set,a=!1,o=null,s=e=>{let t=e;if(!t||t.handle!==n)return;let i={reportId:t.reportId,data:JH(t.bytes)};for(let e of[...r])try{e(i)}catch{}},c=()=>{a||(a=!0,o=e.onEvent?e.onEvent(`hid-input-report`,s):null,e.call(`hid`,`subscribeInputReports`,[n]).catch(()=>{a=!1,o?.(),o=null}))},l=()=>{!a||r.size>0||(a=!1,o?.(),o=null,e.call(`hid`,`unsubscribeInputReports`,[n]).catch(()=>{}))};return{...t,open:()=>e.call(`hid`,`open`,[n]),close:()=>e.call(`hid`,`close`,[n]),sendReport:(t,r)=>e.call(`hid`,`sendReport`,[n,t,qH(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,qH(r)]),receiveFeatureReport:async t=>JH((await e.call(`hid`,`receiveFeatureReport`,[n,t])).bytes),addEventListener(e,t){if(e===`inputreport`)r.add(t),c();else if(e===`disconnect`)i.add(t);else throw TypeError(`hid device: unknown event type '${String(e)}'`)},removeEventListener(e,t){e===`inputreport`?(r.delete(t),l()):e===`disconnect`&&i.delete(t)},onInputReport(e){r.add(e),c()}}}function ZH(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>XH(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[YH(t)]))[0];if(!n)throw Error(`No device selected.`);return XH(e,n)}}}function QH(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var $H=class{rpc;targetId;selector;index;constructor(e,t,n,r){this.rpc=e,this.targetId=t,this.selector=n,this.index=r}evalOnElement(e){let t=`(() => { const els = document.querySelectorAll(${JSON.stringify(this.selector)}); const el = els[${this.index}]; ${e} })()`;return this.rpc.call(`browser`,`evalAsync`,[this.targetId,t])}async textContent(){return this.evalOnElement(`return el ? el.textContent : null;`)}async getAttribute(e){return this.evalOnElement(`return el ? el.getAttribute(${JSON.stringify(e)}) : null;`)}async isVisible(){return this.evalOnElement(`if (!el) return false; const s = getComputedStyle(el); if (s.display === 'none' || s.visibility === 'hidden' || s.opacity === '0') return false; const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0;`)}async boundingBox(){return this.evalOnElement(`if (!el) return null; const r = el.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height };`)}},eU=class{rpc;targetId;onClose;closed=!1;constructor(e,t,n){this.rpc=e,this.targetId=t,this.onClose=n}async goto(e,t){await this.rpc.call(`browser`,`navigateTab`,[this.targetId,e])}async waitForLoadState(e){await this.rpc.call(`browser`,`waitForLoadState`,[this.targetId,e??`load`])}async waitForTimeout(e){await new Promise(t=>setTimeout(t,e))}async evaluate(e,...t){let n=typeof e==`string`?e:`(${e.toString()}).apply(null, JSON.parse(${JSON.stringify(JSON.stringify(t))}))`;return this.rpc.call(`browser`,`evalAsync`,[this.targetId,n])}async screenshot(e){let t={};e?.fullPage!==void 0&&(t.fullPage=e.fullPage);let n=QH(await this.rpc.call(`browser`,`screenshotTab`,[this.targetId,t]));return e?.path&&await this.rpc.call(`vfs`,`writeFileBinary`,[e.path,n]),n}async $(e){return await this.rpc.call(`browser`,`evalAsync`,[this.targetId,`!!document.querySelector(${JSON.stringify(e)})`])?new $H(this.rpc,this.targetId,e,0):null}async $$(e){let t=await this.rpc.call(`browser`,`evalAsync`,[this.targetId,`document.querySelectorAll(${JSON.stringify(e)}).length`]),n=[];for(let r=0;r<t;r++)n.push(new $H(this.rpc,this.targetId,e,r));return n}async $$eval(e,t,...n){if(typeof t==`string`)return this.rpc.call(`browser`,`evalAsync`,[this.targetId,t]);let r=`(${t.toString()}).apply(null, [Array.from(document.querySelectorAll(${JSON.stringify(e)}))].concat(JSON.parse(${JSON.stringify(JSON.stringify(n))})))`;return this.rpc.call(`browser`,`evalAsync`,[this.targetId,r])}async content(){return this.rpc.call(`browser`,`evalAsync`,[this.targetId,`document.documentElement.outerHTML`])}async setViewportSize(e){await this.rpc.call(`browser`,`setViewport`,[this.targetId,e.width,e.height])}async close(){this.closed||(this.closed=!0,await this.rpc.call(`browser`,`closeTab`,[this.targetId]),this.onClose?.())}},tU=class{rpc;openPages=[];constructor(e){this.rpc=e}async newPage(e){let t=await this.rpc.call(`browser`,`createTab`,[`about:blank`]);e?.viewport&&await this.rpc.call(`browser`,`setViewport`,[t,e.viewport.width,e.viewport.height]);let n=new eU(this.rpc,t,()=>{let e=this.openPages.indexOf(n);e!==-1&&this.openPages.splice(e,1)});return this.openPages.push(n),n}pages(){return[...this.openPages]}async close(){let e=this.openPages.splice(0,this.openPages.length);for(let t of e)await t.close()}},nU=class{rpc;openPages=[];openContexts=[];constructor(e){this.rpc=e}async newPage(e){let t=await this.rpc.call(`browser`,`createTab`,[`about:blank`]);e?.viewport&&await this.rpc.call(`browser`,`setViewport`,[t,e.viewport.width,e.viewport.height]);let n=new eU(this.rpc,t,()=>{let e=this.openPages.indexOf(n);e!==-1&&this.openPages.splice(e,1)});return this.openPages.push(n),n}async newContext(e){let t=new tU(this.rpc);return this.openContexts.push(t),t}contexts(){return[...this.openContexts]}async close(){let e=this.openPages.splice(0,this.openPages.length);for(let t of e)await t.close();let t=this.openContexts.splice(0,this.openContexts.length);for(let e of t)await e.close()}};function rU(e){let t=async t=>new nU(e),n=async(t,n)=>new nU(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}const iU=new Set([`bcrypt`,`better-sqlite3`,`canvas`,`cpu-features`,`fsevents`,`leveldown`,`libxmljs`,`libxmljs2`,`node-gyp-build`,`node-sass`,`puppeteer`,`robotjs`,`sass-embedded`,`sharp`,`snappy`,`sqlite3`,`tree-sitter`,`usb`]),aU={sharp:` Use the built-in 'convert' shell command for image work.`,canvas:` Use the built-in 'convert' / OffscreenCanvas for image work.`,"better-sqlite3":` Use the built-in 'sqlite3' shell command (sql.js WASM).`,sqlite3:` Use the built-in 'sqlite3' shell command (sql.js WASM).`,bcrypt:` Use crypto.subtle.digest() with PBKDF2 / Argon2 in pure JS.`,puppeteer:` Use the built-in browser-automation shell commands.`};function oU(e,t){let n=aU[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function sU(e){return{...e,time:YV,fmt:NI,pool:GV}}function cU(e,t){return e?.startsWith(`/`)?XV(e):t}function lU(e){return e.includes(`require`)||e.includes(`import`)||/(?:^|[;\n}])\s*export\b/.test(e)}async function uU(e,t,n,r){return lU(t)?e.call(`module`,`buildGraph`,[t,cU(r,n),r]):{files:[],entryMap:{},edges:{},edgeErrors:{},errors:{}}}function dU(e){if(typeof e!=`object`||!e)return;let t=e;if(t.__esModule&&!Object.prototype.hasOwnProperty.call(t,`default`)&&Object.isExtensible(t))try{Object.defineProperty(t,"default",{value:t,enumerable:!1,configurable:!0})}catch{}}function fU(e){return{playwright:rU(e)}}function pU(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o,shimmedPackages:s={},nodeReadline:c,nodeOsModule:l=qL,nodeUtilModule:u=_L}=e,d=new Map(t.files.map(e=>[e.path,e.cjsSource])),f=new Map(t.files.map(e=>[e.path,e.kind])),p=new Map,m=e=>{if(typeof e==`string`&&e.startsWith(`sliccy:`))return{hit:!0,value:gU(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=mU(t,{fsBridge:n,processShim:r,childProcess:i,nodeOsModule:l,nodeUtilModule:u,nodeReadline:c});if(a.hit)return a;if(iU.has(t))throw oU(e,t);if(ba.has(t))throw vU(e,t);return t in s?{hit:!0,value:s[t]}:{hit:!1}},h=(e,n,r)=>{let i=m(n);if(i.hit)return i.value;let a=e?.[n];if(a)return g(a);let o=r===null?t.errors[n]:t.edgeErrors?.[r]?.[n];throw o?Error(o):hU(n)};function g(e){let n=p.get(e);if(n)return n.exports;let i=d.get(e);if(i===void 0)throw Error(`Cannot find module '${e}'`);let o={exports:{}};p.set(e,o);let s=n=>h(t.edges[e],n,e),c=XV(e);return Function(`module`,`exports`,`require`,`__dirname`,`__filename`,`process`,`console`,`Buffer`,`global`,i)(o,o.exports,s,c,e,r,a,globalThis.Buffer,globalThis),f.get(e)===`cjs`&&dU(o.exports),o.exports}return{require:e=>h(t.entryMap,e,null)}}function mU(e,t){let{fsBridge:n,processShim:r,childProcess:i,nodeOsModule:a,nodeUtilModule:o,nodeReadline:s}=t;return e===`fs`||e===`fs/promises`?{hit:!0,value:n}:e===`path`?{hit:!0,value:iR}:e===`crypto`?{hit:!0,value:HL}:e===`child_process`?{hit:!0,value:i}:e===`process`?{hit:!0,value:r}:e===`buffer`?{hit:!0,value:{Buffer:globalThis.Buffer}}:e===`assert`?{hit:!0,value:GI}:e===`assert/strict`?{hit:!0,value:WI}:e===`util`?{hit:!0,value:o}:e===`events`?{hit:!0,value:JI}:e===`os`?{hit:!0,value:a}:e===`tty`?{hit:!0,value:aR}:e===`stream`?{hit:!0,value:$I}:e===`url`?{hit:!0,value:cR}:e===`zlib`?{hit:!0,value:HV}:e===`readline`&&s?{hit:!0,value:s}:e===`readline/promises`&&s?{hit:!0,value:s.promises}:{hit:!1}}function hU(e){if(e.startsWith(`.`)||e.startsWith(`/`)||e.startsWith(`node:`))return Error(`Cannot find module '${e}'`);let t=e.startsWith(`@`)?e.split(`/`).slice(0,2).join(`/`):e.split(`/`)[0];return Error(`Cannot find module '${e}' (run: ipk install ${t})`)}function gU(e,t){let n=e.slice(7);if(n===``)throw Error(`require('sliccy:'): empty sliccy: module name`);if(!Object.prototype.hasOwnProperty.call(t,n))throw Error(`require('${e}'): unknown sliccy: module '${n}'. Known names: ${Object.keys(t).sort().join(`, `)}`);return t[n]}const _U={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function vU(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${_U[t]||``}`)}async function yU(e,t,n,r){let i=Object.keys(t),a=i.map(e=>t[e]),o=Object.getPrototypeOf(async function(){}).constructor,s=new o(...i,`${r?`"use strict";
|
|
1646
1646
|
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof ZV?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function bU(e,t){let n=t.handle;return{...t,open:t=>e.call(`serial`,`open`,[n,t]),close:()=>e.call(`serial`,`close`,[n]),read:(t={})=>e.call(`serial`,`read`,[n,{maxBytes:t.maxBytes??t.bytes,until:t.until?qH(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,qH(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function xU(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>bU(e,t)),request:async t=>bU(e,await e.call(`serial`,`request`,[YH(t)]))}}function SU(e=globalThis,t){let n=e.setTimeout,r=e.clearTimeout,i=e.setInterval,a=e.clearInterval,o=n.bind(e),s=r.bind(e),c=i.bind(e),l=a.bind(e),u=new Set,d=new Set,f=new Set,p=!1,m=()=>{if(f.size===0)return;let e=[...f];f.clear();for(let t of e)t()},h=e=>{if(e==null)return!1;let t=u.delete(e),n=d.delete(e);return t||n},g=(e,n)=>{try{e(...n)}catch(e){if(t?.onCallbackError?.(e),!t?.onCallbackError)throw e}finally{m()}};return{get pendingCount(){return u.size+d.size},install(){p||(p=!0,e.setTimeout=((e,t,...n)=>{if(typeof e!=`function`)return o(e,t,...n);let r=o(()=>{u.delete(r),g(e,n)},t);return u.add(r),r}),e.clearTimeout=(e=>{let t=h(e);s(e),t&&m()}),e.setInterval=((e,t,...n)=>{if(typeof e!=`function`)return c(e,t,...n);let r=c(()=>{g(e,n)},t);return d.add(r),r}),e.clearInterval=(e=>{let t=h(e);l(e),t&&m()}))},restore(){p&&(p=!1,e.setTimeout=n,e.clearTimeout=r,e.setInterval=i,e.clearInterval=a)},clearPending(){for(let e of u)s(e);u.clear();for(let e of d)l(e);d.clear(),m()},tick(){return new Promise(e=>{o(e,0)})},waitForProgress(){return u.size+d.size===0?Promise.resolve():new Promise(e=>{f.add(e)})}}}function CU(e,t){let n=t.handle,r=e=>({status:e.status,data:JH(e.bytes)});return{...t,open:()=>e.call(`usb`,`open`,[n]),close:()=>e.call(`usb`,`close`,[n]),reset:()=>e.call(`usb`,`reset`,[n]),clearHalt:(t,r)=>e.call(`usb`,`clearHalt`,[n,t,r]),selectConfiguration:t=>e.call(`usb`,`selectConfig`,[n,t]),claimInterface:t=>e.call(`usb`,`claim`,[n,t]),releaseInterface:t=>e.call(`usb`,`release`,[n,t]),controlTransferIn:async(t,i)=>r(await e.call(`usb`,`controlIn`,[n,t,i])),controlTransferOut:(t,r)=>e.call(`usb`,`controlOut`,[n,t,qH(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,qH(r)])}}function wU(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>CU(e,t)),request:async t=>CU(e,await e.call(`usb`,`request`,[YH(t)]))}}function TU(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function EU(e){if(!e)return e;let t=e.startsWith(`/`),n=e.split(`/`).filter(e=>e.length>0),r=n.indexOf(`scripts`);if(r<0)return e;let i=n.slice(0,r);return i.length===0?t?`/`:``:(t?`/`:``)+i.join(`/`)}function DU(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function OU(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function kU(e){let t=TU(e.argv[1]??``),n=EU(t),r=OU(n,`references`),i=OU(n,`assets`),a=OU(t,`.config`);async function o(){let t;try{t=await e.fs.exists(a)}catch{return null}if(!t)return null;let n;try{n=await e.fs.readFile(a)}catch{return null}let r=typeof n==`string`?n:String(n);if(!r.trim())return null;let i;try{i=JSON.parse(r)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`skill.config(): failed to parse ${a}: ${t}`)}if(i&&typeof i==`object`&&!Array.isArray(i))return i;throw Error(`skill.config(): ${a} must contain a JSON object`)}async function s(t){let n=await o();if(t===void 0)return n;if(typeof t!=`object`||!t||Array.isArray(t))throw TypeError(`skill.config(updates): updates must be a plain object`);let r={...n??{},...t};return await e.fs.writeFile(a,JSON.stringify(r,null,2)+`
|
|
1647
|
-
`),r}async function c(t){if(typeof t!=`string`||!t.trim())throw TypeError(`skill.token(providerId): providerId must be a non-empty string`);let n=`oauth-token ${DU(t)}`,{stdout:r,stderr:i,exitCode:a}=await e.exec(n);if(a!==0){let e=i.trim()||`oauth-token exited with code ${a}`;throw Error(`skill.token('${t}'): ${e}`)}return r.replace(/\r?\n+$/,``)}return Object.freeze({dir:t,root:n,refs:r,assets:i,config:s,token:c})}const AU=new Map,jU=new Map;function MU(e){let t=crypto.randomUUID();return AU.set(t,e),t}function NU(e){return AU.get(e)??null}function PU(e,t){if(!AU.has(e))return t.abort(),()=>{};let n=jU.get(e);return n||(n=new Set,jU.set(e,n)),n.add(t),()=>{let n=jU.get(e);n&&(n.delete(t),n.size===0&&jU.delete(e))}}function FU(e){AU.delete(e);let t=jU.get(e);if(t){jU.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function IU(e){let t=e instanceof Error?e.message:String(e),n=e?.code;return typeof n==`string`&&/^E[A-Z]+$/.test(n)?{ok:!1,errno:n,message:t}:{ok:!1,errno:`EIO`,message:t}}async function LU(e){let t=NU(e.token);if(!t)return{ok:!1,errno:`EACCES`,message:`sync-fs: unknown or revoked token`};let{fs:n,cwd:r}=t;try{let t=n.resolvePath(r,e.path);switch(e.op){case`read`:return{ok:!0,kind:`bytes`,bytes:await n.readFileBuffer(t)};case`write`:return await n.writeFile(t,e.body??new Uint8Array),{ok:!0,kind:`void`};case`exists`:return{ok:!0,kind:`json`,json:await n.exists(t)};case`stat`:{let e=await n.stat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,isSymbolicLink:e.isSymbolicLink,size:e.size}}}case`lstat`:{let e=await n.lstat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,isSymbolicLink:e.isSymbolicLink??!1,size:e.size}}}case`readdir`:return{ok:!0,kind:`json`,json:await n.readdir(t)};case`mkdir`:return await n.mkdir(t,{recursive:!0}),{ok:!0,kind:`void`};case`rm`:return await n.rm(t,{recursive:!0}),{ok:!0,kind:`void`};case`rename`:{let i=n.resolvePath(r,e.arg2??``),a=n;if(a.rename)await a.rename(t,i);else if(a.mv)await a.mv(t,i);else{let e=await n.readFileBuffer(t);await n.writeFile(i,e),await n.rm(t,{recursive:!0})}return{ok:!0,kind:`void`}}default:return{ok:!1,errno:`EINVAL`,message:`sync-fs: unknown op '${e.op}'`}}}catch(e){return IU(e)}}function RU(e){return`slicc-sync-fs-`+e}const zU=`sync-fs-ack`,BU=`sync-fs-res`,VU=6e5,HU=5e3,UU=`exec`;function WU(e){return e.channel===UU}function GU(e){let{command:t}=e;if(Array.isArray(t)){if(t.length===0||!t.every(e=>typeof e==`string`))return{errno:`EINVAL`,message:`sync-exec: argv must be a non-empty string[]`};let[e,...n]=t;return{cmd:e,args:n}}return typeof t!=`string`||t.length===0?{errno:`EINVAL`,message:`sync-exec: command must be a non-empty string`}:e.args===void 0?{cmd:t}:!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`)?{errno:`EINVAL`,message:`sync-exec: args must be a string[]`}:{cmd:t,args:e.args}}function KU(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,VU)}async function qU(e){let t=NU(e.token);if(!t)return{ok:!1,errno:`EACCES`,message:`sync-exec: unknown or revoked token`};if(!t.exec)return{ok:!1,errno:`ENOSYS`,message:`sync-exec: exec is not available`};let n=GU(e);if(`errno`in n)return{ok:!1,errno:n.errno,message:n.message};let r=new AbortController,i=!1,a=setTimeout(()=>{i=!0,r.abort()},KU(e.timeoutMs,VU)),o=PU(e.token,r);try{let i=await t.exec(n.cmd,{cwd:t.cwd,signal:r.signal,...n.args===void 0?{}:{args:n.args},...e.stdin===void 0?{}:{stdin:e.stdin}});return{ok:!0,kind:`json`,json:{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}catch(e){return i?{ok:!1,errno:`ETIMEDOUT`,message:`sync-exec: timed out — ${e instanceof Error?e.message:String(e)}`}:r.signal.aborted?{ok:!1,errno:`ECANCELED`,message:`sync-exec: realm disposed`}:IU(e)}finally{clearTimeout(a),o()}}function JU(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function YU(e){let t=ZU(e);if(QU(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw JU(`EIO`,e.label);$U(t,e.label)}function XU(e){let t=YU(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw JU(`EIO`,e.label)}}function ZU(e){let t=new XMLHttpRequest;try{t.open(e.method,e.url,!1),t.responseType=`arraybuffer`,t.timeout=e.timeoutMs,t.setRequestHeader(`x-slicc-fs-token`,e.token),e.body?t.send(new Uint8Array(e.body)):t.send()}catch{throw JU(`EIO`,e.label)}return t}function QU(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function $U(e,t){throw JU(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function eW(e){return(t,n,r)=>{let i=XU({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:UU})),timeoutMs:n+HU,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw JU(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function tW(e,t){let n=e.getMutations();for(let e of n.deleted)t.rm(e);for(let e of n.created)e.isDirectory?t.mkdir(e.path):t.writeFile(e.path,e.content);for(let e of n.modified)t.writeFile(e.path,e.content);e.resetBaseline()}function nW(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??eW(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&tW(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=KU(t.timeout,n),l={command:e,...t.args===void 0?{}:{args:t.args},...t.input===void 0?{}:{stdin:t.input},timeoutMs:c};try{return a(l,c,s)}finally{o&&r.invalidate()}}}}function rW(e,t){return JU(e,`sync-fs bridge, '${t}'`)}function iW(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function aW(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:iW(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return YU(r(`GET`,e))},writeFile(e,t){YU(r(`POST`,e,t))},stat(e){let t=XU(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw rW(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=XU(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw rW(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=XU(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw rW(`EIO`,e);return t},exists(e){let t=XU(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw rW(`EIO`,e);return t},mkdir(e){YU(r(`POST`,e,void 0,`mkdir`))},rm(e){YU(r(`POST`,e,void 0,`rm`))}}}const oW=new TextEncoder,sW=new TextDecoder;function cW(e){if(!e.ok)return{status:4,payload:oW.encode(JSON.stringify({errno:e.errno,message:e.message}))};switch(e.kind){case`bytes`:return{status:1,payload:e.bytes};case`json`:return{status:2,payload:oW.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function lW(e,t){switch(e){case 1:return{ok:!0,kind:`bytes`,bytes:t};case 3:return{ok:!0,kind:`void`};case 2:try{return{ok:!0,kind:`json`,json:JSON.parse(sW.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(sW.decode(t)),n=typeof e.errno==`string`&&/^E[A-Z]+$/.test(e.errno)?e.errno:`EIO`;return{ok:!1,errno:n,message:String(e.message??n)}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed errno payload`}}default:return{ok:!1,errno:`EIO`,message:`sync-sab: unknown status ${e}`}}}function uW(e){if(e.byteLength<4160)throw Error(`sync-sab: buffer too small (${e.byteLength} < 4160)`);return{header:new Int32Array(e,0,16),window:new Uint8Array(e,64)}}function dW(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function fW(e,t,n={}){let{header:r,window:i}=uW(e),a=n.wait??((e,t,n,r)=>Atomics.wait(e,t,n,r)),o=n.now??(()=>performance.now()),s=0;function c(e,t,n){for(;;){let i=t-o();if(i<=0)throw JU(`ETIMEDOUT`,n);if(a(r,0,1,i),Atomics.load(r,0)===2&&Atomics.load(r,1)===e)return;Atomics.load(r,0)===2&&Atomics.store(r,0,1)}}return{call(e,n,a){let l=++s,u=o()+n,d=null,f=0,p=0;try{for(;;){Atomics.store(r,0,1);let n=p===0?{type:`sync-sab-req`,id:l,req:e}:{type:`sync-sab-next`,id:l,offset:p};try{t.postMessage(n)}catch{throw JU(`EIO`,a)}c(l,u,a);let o=Atomics.load(r,3),s=Atomics.load(r,4);if(Atomics.load(r,5)!==p||s<0||o<0||p+s>o)throw JU(`EIO`,a);if(d===null&&(f=Atomics.load(r,2),d=new Uint8Array(o)),d.set(i.subarray(0,s),p),p+=s,p>=o)break;if(s===0)throw JU(`EIO`,a)}}finally{Atomics.store(r,0,0)}return lW(f,d)}}}function pW(e,t){return JU(e,`sync-sab bridge, '${t}'`)}function mW(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function hW(e,t={}){let n=t.timeoutMs??25e3;function r(t,r){let i=e.call(t,n,`sync-sab bridge, '${r}'`);if(!i.ok)throw pW(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw pW(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw pW(`EIO`,t)}return{readFile:e=>i({op:`read`,path:e},e),writeFile:(e,t)=>{r({op:`write`,path:e,body:t},e)},stat:e=>{let t=a({op:`stat`,path:e},e);if(!mW(t))throw pW(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!mW(t))throw pW(`EIO`,e);return t},readdir:e=>{let t=a({op:`readdir`,path:e},e);if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw pW(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw pW(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function gW(e){return(t,n,r)=>{let i=e.call({...t,channel:UU},n+HU,r);if(!i.ok)throw JU(i.errno,r);let a=i.kind===`json`?i.json:null;if(!a||typeof a.stdout!=`string`||typeof a.stderr!=`string`||typeof a.exitCode!=`number`)throw JU(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function _W(e,t,n){let r;try{r=await e.call(`vfs`,`snapshot`,[t])}catch(e){n?.(e instanceof Error?e.message:String(e)),r={entries:[]}}return new eI(r)}function vW(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function yW(e,t){return t?hW(t):e.syncFsToken?aW(e.syncFsToken):void 0}function bW(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return fW(e.syncSab,t)}function xW(e,t,n,r,i){let a=bW(e,t),o=yW(e,a);if(Object.assign(r,bI(n,e.cwd,o,i)),e.syncFsToken)return nW(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:gW(a)}:{}})}function SW(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:Yr().version,writable:!1,enumerable:!1,configurable:!1})}function CW(e,t,n){let r=CI({isTTY:!e,noColor:e});return{colorApi:r,cliApi:xI({writeStdout:t,writeStderr:n,exit:e=>{throw new ZV(e)},color:r})}}function wW(e,t,n){return{readStdinBytes:()=>nI(e.stdin??``),writeStdout:t,writeStderr:n}}function TW(e){return{usbBridge:wU(e),serialBridge:xU(e),hidBridge:ZH(e)}}async function EW(e,t){let n=[],r=[],i=e=>{n.push(typeof e==`string`?e:String(e))},a=e=>{r.push(typeof e==`string`?e:String(e))},o=$V(i,a),s=eH(e,i,a),{colorApi:c,cliApi:l}=CW(!!e.env?.NO_COLOR,i,a),u=new dF(t),d=wW(e,i,a),f=mI(u,C,d),p=await _W(u,e.cwd,vW(e,a)),m=xW(e,t,p,f,d),h=BH(u,p,e.cwd,a),g=AH(h,{cwd:e.cwd}),_=kU({argv:e.argv,fs:f,exec:h}),v=FH(u),{usbBridge:y,serialBridge:b,hidBridge:x}=TW(u),S=DH({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e);return UH(await u.call(`fetch`,`request`,[n,await NH(t,e)]),n)}let w=sU({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=XV(T),D=await uU(u,e.code,e.cwd,T),ee=pU({graph:D,fsBridge:f,processShim:s.processShim,childProcess:EL(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:fU(u),nodeReadline:cH({output:{write:i},onExit:s.recordExit}),nodeOsModule:KL(e.env),nodeUtilModule:gL(e=>a(`${e}\n`))}).require,te={exports:{},filename:e.filename},ne=D.entrySource!==void 0;await DW({entryCode:D.entrySource??e.code,isEsmEntry:ne,filename:T,dirname:E,proc:s,nodeConsole:o,requireShim:ee,moduleShim:te,realmFetch:C,writeStderr:a,rpc:u,syncFs:p,stdoutChunks:n,stderrChunks:r,port:t})}async function DW(e){let t=globalThis;SW(),t.__slicc_compileWasm=t=>e.rpc.call(`wasm`,`compile`,[t]);let n=SU(globalThis,{onCallbackError(e){if(!(e instanceof ZV))throw e}});n.install();try{let r=await OW({entryCode:e.entryCode,bridges:{process:e.proc.processShim,console:e.nodeConsole,require:e.requireShim,module:e.moduleShim,exports:e.moduleShim.exports,fetch:e.realmFetch,__dirname:e.dirname,__filename:e.filename},writeStderr:e.writeStderr,isEsmEntry:e.isEsmEntry,rpc:e.rpc,syncFs:e.syncFs,proc:e.proc,timers:n});delete t.__slicc_compileWasm,e.rpc.dispose(),e.port.postMessage({type:`realm-done`,stdout:e.stdoutChunks.join(``),stderr:e.stderrChunks.join(``),exitCode:r})}finally{n.clearPending(),n.restore()}}async function OW(e){let t=await yU(e.entryCode,e.bridges,e.writeStderr,e.isEsmEntry);return await kW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?(e.timers.clearPending(),e.proc.getExitCode()):(await AW(e.rpc,e.timers,e.proc),e.proc.getDidCallProcessExit()&&e.timers.clearPending(),await kW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?e.proc.getExitCode():t)}async function kW(e,t,n){let r=t.getMutations();if(r.created.length||r.modified.length||r.deleted.length)try{await e.call(`vfs`,`flushWrites`,[r]),t.resetBaseline()}catch(e){let t=e instanceof Error?e.message:String(e);n(`[sync-fs] ERROR: flush failed — ${r.created.length+r.modified.length} write(s) + ${r.deleted.length} delete(s) were NOT persisted: ${t}\n`)}}async function AW(e,t,n){for(await t.tick();!n.getDidCallProcessExit()&&(e.pendingCount>0||t.pendingCount>0);){let r=[];if(e.pendingCount>0&&r.push(e.waitForProgress()),t.pendingCount>0&&r.push(t.waitForProgress()),r.length===0)break;await Promise.race(r),n.getDidCallProcessExit()||await t.tick()}}function jW(){let e=new Set,t=new Set;return{realmSide:{postMessage:e=>{queueMicrotask(()=>{for(let n of[...t])n({data:e})})},addEventListener:(t,n)=>{e.add(n)},removeEventListener:(t,n)=>{e.delete(n)}},hostSide:{postMessage:t=>{queueMicrotask(()=>{for(let n of[...e])n({data:t})})},addEventListener:(e,n)=>{t.add(n)},removeEventListener:(e,n)=>{t.delete(n)}}}}function MW(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=jW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&EW(n,t).catch(e=>{let n={type:`realm-error`,message:e instanceof Error?e.message:String(e)};t.postMessage(n)})};return t.addEventListener(`message`,r),{controlPort:n,terminate(){t.removeEventListener(`message`,r)}}}}function NW(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=jW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&SF(n,t).catch(e=>{let n={type:`realm-error`,message:e instanceof Error?e.message:String(e)};t.postMessage(n)})};return t.addEventListener(`message`,r),{controlPort:n,terminate(){t.removeEventListener(`message`,r)}}}}const PW=MW(),FW=NW();function IW(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?RW():FW({kind:e,ctx:t}):typeof Worker<`u`?LW():PW({kind:e,ctx:t})}function LW(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return zW(new Worker(new URL(`/assets/js-realm-worker-DXyLExOV.js`,``+import.meta.url),{type:`module`}))}function RW(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return zW(new Worker(new URL(`/assets/py-realm-worker-BYQkpReo.js`,``+import.meta.url),{type:`module`}))}function zW(e){let t={postMessage:(t,n)=>n?e.postMessage(t,n):e.postMessage(t),addEventListener:(t,n)=>e.addEventListener(t,n),removeEventListener:(t,n)=>e.removeEventListener(t,n)},n=!1;return{controlPort:t,isolatedThread:!0,addEventListener:(t,n,r)=>e.addEventListener(t,n,r),removeEventListener:(t,n)=>e.removeEventListener(t,n),terminate(){if(!n){n=!0;try{e.terminate()}catch{}}}}}function BW(){if(Fa())return decodeURIComponent(Da(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function VW(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function HW(e){return e instanceof Error?e.message:String(e)}function UW(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function WW(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:UW(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function GW(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:UW(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const KW=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,qW=/\bimport\s*\.\s*meta\b/g;function JW(e,t){let n=JSON.stringify(t);return e.replace(KW,n).replace(qW,`({ url: ${n} })`)}async function YW(e,t,n,r){let i=await e();return i.transpileModule(JW(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function XW(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Wa(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Ta(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Ca(e))return e;let a=VW(t),o;try{return await WW(n,e,t,a)}catch(e){o=e}try{return await YW(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${HW(o)}; typescript fallback: ${HW(e)}`)}}}function ZW(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Wa(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Ta(t));return async({source:e,filename:t})=>{if(!Ca(e)&&!Ha(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?VW(t):void 0,o=i?t:`[eval].js`,s;try{return await GW(n,e,t,a)}catch(e){s=e}try{return await YW(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${HW(s)}; typescript fallback: ${HW(e)}`)}}}function QW(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
1647
|
+
`),r}async function c(t){if(typeof t!=`string`||!t.trim())throw TypeError(`skill.token(providerId): providerId must be a non-empty string`);let n=`oauth-token ${DU(t)}`,{stdout:r,stderr:i,exitCode:a}=await e.exec(n);if(a!==0){let e=i.trim()||`oauth-token exited with code ${a}`;throw Error(`skill.token('${t}'): ${e}`)}return r.replace(/\r?\n+$/,``)}return Object.freeze({dir:t,root:n,refs:r,assets:i,config:s,token:c})}const AU=new Map,jU=new Map;function MU(e){let t=crypto.randomUUID();return AU.set(t,e),t}function NU(e){return AU.get(e)??null}function PU(e,t){if(!AU.has(e))return t.abort(),()=>{};let n=jU.get(e);return n||(n=new Set,jU.set(e,n)),n.add(t),()=>{let n=jU.get(e);n&&(n.delete(t),n.size===0&&jU.delete(e))}}function FU(e){AU.delete(e);let t=jU.get(e);if(t){jU.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function IU(e){let t=e instanceof Error?e.message:String(e),n=e?.code;return typeof n==`string`&&/^E[A-Z]+$/.test(n)?{ok:!1,errno:n,message:t}:{ok:!1,errno:`EIO`,message:t}}async function LU(e){let t=NU(e.token);if(!t)return{ok:!1,errno:`EACCES`,message:`sync-fs: unknown or revoked token`};let{fs:n,cwd:r}=t;try{let t=n.resolvePath(r,e.path);switch(e.op){case`read`:return{ok:!0,kind:`bytes`,bytes:await n.readFileBuffer(t)};case`write`:return await n.writeFile(t,e.body??new Uint8Array),{ok:!0,kind:`void`};case`exists`:return{ok:!0,kind:`json`,json:await n.exists(t)};case`stat`:{let e=await n.stat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,isSymbolicLink:e.isSymbolicLink,size:e.size}}}case`lstat`:{let e=await n.lstat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,isSymbolicLink:e.isSymbolicLink??!1,size:e.size}}}case`readdir`:return{ok:!0,kind:`json`,json:await n.readdir(t)};case`mkdir`:return await n.mkdir(t,{recursive:!0}),{ok:!0,kind:`void`};case`rm`:return await n.rm(t,{recursive:!0}),{ok:!0,kind:`void`};case`rename`:{let i=n.resolvePath(r,e.arg2??``),a=n;if(a.rename)await a.rename(t,i);else if(a.mv)await a.mv(t,i);else{let e=await n.readFileBuffer(t);await n.writeFile(i,e),await n.rm(t,{recursive:!0})}return{ok:!0,kind:`void`}}default:return{ok:!1,errno:`EINVAL`,message:`sync-fs: unknown op '${e.op}'`}}}catch(e){return IU(e)}}function RU(e){return`slicc-sync-fs-`+e}const zU=`sync-fs-ack`,BU=`sync-fs-res`,VU=6e5,HU=5e3,UU=`exec`;function WU(e){return e.channel===UU}function GU(e){let{command:t}=e;if(Array.isArray(t)){if(t.length===0||!t.every(e=>typeof e==`string`))return{errno:`EINVAL`,message:`sync-exec: argv must be a non-empty string[]`};let[e,...n]=t;return{cmd:e,args:n}}return typeof t!=`string`||t.length===0?{errno:`EINVAL`,message:`sync-exec: command must be a non-empty string`}:e.args===void 0?{cmd:t}:!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`)?{errno:`EINVAL`,message:`sync-exec: args must be a string[]`}:{cmd:t,args:e.args}}function KU(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,VU)}async function qU(e){let t=NU(e.token);if(!t)return{ok:!1,errno:`EACCES`,message:`sync-exec: unknown or revoked token`};if(!t.exec)return{ok:!1,errno:`ENOSYS`,message:`sync-exec: exec is not available`};let n=GU(e);if(`errno`in n)return{ok:!1,errno:n.errno,message:n.message};let r=new AbortController,i=!1,a=setTimeout(()=>{i=!0,r.abort()},KU(e.timeoutMs,VU)),o=PU(e.token,r);try{let i=await t.exec(n.cmd,{cwd:t.cwd,signal:r.signal,...n.args===void 0?{}:{args:n.args},...e.stdin===void 0?{}:{stdin:e.stdin}});return{ok:!0,kind:`json`,json:{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}catch(e){return i?{ok:!1,errno:`ETIMEDOUT`,message:`sync-exec: timed out — ${e instanceof Error?e.message:String(e)}`}:r.signal.aborted?{ok:!1,errno:`ECANCELED`,message:`sync-exec: realm disposed`}:IU(e)}finally{clearTimeout(a),o()}}function JU(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function YU(e){let t=ZU(e);if(QU(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw JU(`EIO`,e.label);$U(t,e.label)}function XU(e){let t=YU(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw JU(`EIO`,e.label)}}function ZU(e){let t=new XMLHttpRequest;try{t.open(e.method,e.url,!1),t.responseType=`arraybuffer`,t.timeout=e.timeoutMs,t.setRequestHeader(`x-slicc-fs-token`,e.token),e.body?t.send(new Uint8Array(e.body)):t.send()}catch{throw JU(`EIO`,e.label)}return t}function QU(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function $U(e,t){throw JU(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function eW(e){return(t,n,r)=>{let i=XU({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:UU})),timeoutMs:n+HU,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw JU(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function tW(e,t){let n=e.getMutations();for(let e of n.deleted)t.rm(e);for(let e of n.created)e.isDirectory?t.mkdir(e.path):t.writeFile(e.path,e.content);for(let e of n.modified)t.writeFile(e.path,e.content);e.resetBaseline()}function nW(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??eW(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&tW(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=KU(t.timeout,n),l={command:e,...t.args===void 0?{}:{args:t.args},...t.input===void 0?{}:{stdin:t.input},timeoutMs:c};try{return a(l,c,s)}finally{o&&r.invalidate()}}}}function rW(e,t){return JU(e,`sync-fs bridge, '${t}'`)}function iW(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function aW(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:iW(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return YU(r(`GET`,e))},writeFile(e,t){YU(r(`POST`,e,t))},stat(e){let t=XU(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw rW(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=XU(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw rW(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=XU(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw rW(`EIO`,e);return t},exists(e){let t=XU(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw rW(`EIO`,e);return t},mkdir(e){YU(r(`POST`,e,void 0,`mkdir`))},rm(e){YU(r(`POST`,e,void 0,`rm`))}}}const oW=new TextEncoder,sW=new TextDecoder;function cW(e){if(!e.ok)return{status:4,payload:oW.encode(JSON.stringify({errno:e.errno,message:e.message}))};switch(e.kind){case`bytes`:return{status:1,payload:e.bytes};case`json`:return{status:2,payload:oW.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function lW(e,t){switch(e){case 1:return{ok:!0,kind:`bytes`,bytes:t};case 3:return{ok:!0,kind:`void`};case 2:try{return{ok:!0,kind:`json`,json:JSON.parse(sW.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(sW.decode(t)),n=typeof e.errno==`string`&&/^E[A-Z]+$/.test(e.errno)?e.errno:`EIO`;return{ok:!1,errno:n,message:String(e.message??n)}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed errno payload`}}default:return{ok:!1,errno:`EIO`,message:`sync-sab: unknown status ${e}`}}}function uW(e){if(e.byteLength<4160)throw Error(`sync-sab: buffer too small (${e.byteLength} < 4160)`);return{header:new Int32Array(e,0,16),window:new Uint8Array(e,64)}}function dW(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function fW(e,t,n={}){let{header:r,window:i}=uW(e),a=n.wait??((e,t,n,r)=>Atomics.wait(e,t,n,r)),o=n.now??(()=>performance.now()),s=0;function c(e,t,n){for(;;){let i=t-o();if(i<=0)throw JU(`ETIMEDOUT`,n);if(a(r,0,1,i),Atomics.load(r,0)===2&&Atomics.load(r,1)===e)return;Atomics.load(r,0)===2&&Atomics.store(r,0,1)}}return{call(e,n,a){let l=++s,u=o()+n,d=null,f=0,p=0;try{for(;;){Atomics.store(r,0,1);let n=p===0?{type:`sync-sab-req`,id:l,req:e}:{type:`sync-sab-next`,id:l,offset:p};try{t.postMessage(n)}catch{throw JU(`EIO`,a)}c(l,u,a);let o=Atomics.load(r,3),s=Atomics.load(r,4);if(Atomics.load(r,5)!==p||s<0||o<0||p+s>o)throw JU(`EIO`,a);if(d===null&&(f=Atomics.load(r,2),d=new Uint8Array(o)),d.set(i.subarray(0,s),p),p+=s,p>=o)break;if(s===0)throw JU(`EIO`,a)}}finally{Atomics.store(r,0,0)}return lW(f,d)}}}function pW(e,t){return JU(e,`sync-sab bridge, '${t}'`)}function mW(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function hW(e,t={}){let n=t.timeoutMs??25e3;function r(t,r){let i=e.call(t,n,`sync-sab bridge, '${r}'`);if(!i.ok)throw pW(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw pW(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw pW(`EIO`,t)}return{readFile:e=>i({op:`read`,path:e},e),writeFile:(e,t)=>{r({op:`write`,path:e,body:t},e)},stat:e=>{let t=a({op:`stat`,path:e},e);if(!mW(t))throw pW(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!mW(t))throw pW(`EIO`,e);return t},readdir:e=>{let t=a({op:`readdir`,path:e},e);if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw pW(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw pW(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function gW(e){return(t,n,r)=>{let i=e.call({...t,channel:UU},n+HU,r);if(!i.ok)throw JU(i.errno,r);let a=i.kind===`json`?i.json:null;if(!a||typeof a.stdout!=`string`||typeof a.stderr!=`string`||typeof a.exitCode!=`number`)throw JU(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function _W(e,t,n){let r;try{r=await e.call(`vfs`,`snapshot`,[t])}catch(e){n?.(e instanceof Error?e.message:String(e)),r={entries:[]}}return new eI(r)}function vW(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function yW(e,t){return t?hW(t):e.syncFsToken?aW(e.syncFsToken):void 0}function bW(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return fW(e.syncSab,t)}function xW(e,t,n,r,i){let a=bW(e,t),o=yW(e,a);if(Object.assign(r,bI(n,e.cwd,o,i)),e.syncFsToken)return nW(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:gW(a)}:{}})}function SW(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:Yr().version,writable:!1,enumerable:!1,configurable:!1})}function CW(e,t,n){let r=CI({isTTY:!e,noColor:e});return{colorApi:r,cliApi:xI({writeStdout:t,writeStderr:n,exit:e=>{throw new ZV(e)},color:r})}}function wW(e,t,n){return{readStdinBytes:()=>nI(e.stdin??``),writeStdout:t,writeStderr:n}}function TW(e){return{usbBridge:wU(e),serialBridge:xU(e),hidBridge:ZH(e)}}async function EW(e,t){let n=[],r=[],i=e=>{n.push(typeof e==`string`?e:String(e))},a=e=>{r.push(typeof e==`string`?e:String(e))},o=$V(i,a),s=eH(e,i,a),{colorApi:c,cliApi:l}=CW(!!e.env?.NO_COLOR,i,a),u=new dF(t),d=wW(e,i,a),f=mI(u,C,d),p=await _W(u,e.cwd,vW(e,a)),m=xW(e,t,p,f,d),h=BH(u,p,e.cwd,a),g=AH(h,{cwd:e.cwd}),_=kU({argv:e.argv,fs:f,exec:h}),v=FH(u),{usbBridge:y,serialBridge:b,hidBridge:x}=TW(u),S=DH({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e);return UH(await u.call(`fetch`,`request`,[n,await NH(t,e)]),n)}let w=sU({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=XV(T),D=await uU(u,e.code,e.cwd,T),ee=pU({graph:D,fsBridge:f,processShim:s.processShim,childProcess:EL(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:fU(u),nodeReadline:cH({output:{write:i},onExit:s.recordExit}),nodeOsModule:KL(e.env),nodeUtilModule:gL(e=>a(`${e}\n`))}).require,te={exports:{},filename:e.filename},ne=D.entrySource!==void 0;await DW({entryCode:D.entrySource??e.code,isEsmEntry:ne,filename:T,dirname:E,proc:s,nodeConsole:o,requireShim:ee,moduleShim:te,realmFetch:C,writeStderr:a,rpc:u,syncFs:p,stdoutChunks:n,stderrChunks:r,port:t})}async function DW(e){let t=globalThis;SW(),t.__slicc_compileWasm=t=>e.rpc.call(`wasm`,`compile`,[t]);let n=SU(globalThis,{onCallbackError(e){if(!(e instanceof ZV))throw e}});n.install();try{let r=await OW({entryCode:e.entryCode,bridges:{process:e.proc.processShim,console:e.nodeConsole,require:e.requireShim,module:e.moduleShim,exports:e.moduleShim.exports,fetch:e.realmFetch,__dirname:e.dirname,__filename:e.filename},writeStderr:e.writeStderr,isEsmEntry:e.isEsmEntry,rpc:e.rpc,syncFs:e.syncFs,proc:e.proc,timers:n});delete t.__slicc_compileWasm,e.rpc.dispose(),e.port.postMessage({type:`realm-done`,stdout:e.stdoutChunks.join(``),stderr:e.stderrChunks.join(``),exitCode:r})}finally{n.clearPending(),n.restore()}}async function OW(e){let t=await yU(e.entryCode,e.bridges,e.writeStderr,e.isEsmEntry);return await kW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?(e.timers.clearPending(),e.proc.getExitCode()):(await AW(e.rpc,e.timers,e.proc),e.proc.getDidCallProcessExit()&&e.timers.clearPending(),await kW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?e.proc.getExitCode():t)}async function kW(e,t,n){let r=t.getMutations();if(r.created.length||r.modified.length||r.deleted.length)try{await e.call(`vfs`,`flushWrites`,[r]),t.resetBaseline()}catch(e){let t=e instanceof Error?e.message:String(e);n(`[sync-fs] ERROR: flush failed — ${r.created.length+r.modified.length} write(s) + ${r.deleted.length} delete(s) were NOT persisted: ${t}\n`)}}async function AW(e,t,n){for(await t.tick();!n.getDidCallProcessExit()&&(e.pendingCount>0||t.pendingCount>0);){let r=[];if(e.pendingCount>0&&r.push(e.waitForProgress()),t.pendingCount>0&&r.push(t.waitForProgress()),r.length===0)break;await Promise.race(r),n.getDidCallProcessExit()||await t.tick()}}function jW(){let e=new Set,t=new Set;return{realmSide:{postMessage:e=>{queueMicrotask(()=>{for(let n of[...t])n({data:e})})},addEventListener:(t,n)=>{e.add(n)},removeEventListener:(t,n)=>{e.delete(n)}},hostSide:{postMessage:t=>{queueMicrotask(()=>{for(let n of[...e])n({data:t})})},addEventListener:(e,n)=>{t.add(n)},removeEventListener:(e,n)=>{t.delete(n)}}}}function MW(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=jW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&EW(n,t).catch(e=>{let n={type:`realm-error`,message:e instanceof Error?e.message:String(e)};t.postMessage(n)})};return t.addEventListener(`message`,r),{controlPort:n,terminate(){t.removeEventListener(`message`,r)}}}}function NW(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=jW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&SF(n,t).catch(e=>{let n={type:`realm-error`,message:e instanceof Error?e.message:String(e)};t.postMessage(n)})};return t.addEventListener(`message`,r),{controlPort:n,terminate(){t.removeEventListener(`message`,r)}}}}const PW=MW(),FW=NW();function IW(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?RW():FW({kind:e,ctx:t}):typeof Worker<`u`?LW():PW({kind:e,ctx:t})}function LW(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return zW(new Worker(new URL(`/assets/js-realm-worker-CoOVJsfl.js`,``+import.meta.url),{type:`module`}))}function RW(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return zW(new Worker(new URL(`/assets/py-realm-worker-BYQkpReo.js`,``+import.meta.url),{type:`module`}))}function zW(e){let t={postMessage:(t,n)=>n?e.postMessage(t,n):e.postMessage(t),addEventListener:(t,n)=>e.addEventListener(t,n),removeEventListener:(t,n)=>e.removeEventListener(t,n)},n=!1;return{controlPort:t,isolatedThread:!0,addEventListener:(t,n,r)=>e.addEventListener(t,n,r),removeEventListener:(t,n)=>e.removeEventListener(t,n),terminate(){if(!n){n=!0;try{e.terminate()}catch{}}}}}function BW(){if(Fa())return decodeURIComponent(Da(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function VW(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function HW(e){return e instanceof Error?e.message:String(e)}function UW(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function WW(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:UW(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function GW(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:UW(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const KW=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,qW=/\bimport\s*\.\s*meta\b/g;function JW(e,t){let n=JSON.stringify(t);return e.replace(KW,n).replace(qW,`({ url: ${n} })`)}async function YW(e,t,n,r){let i=await e();return i.transpileModule(JW(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function XW(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Wa(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Ta(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Ca(e))return e;let a=VW(t),o;try{return await WW(n,e,t,a)}catch(e){o=e}try{return await YW(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${HW(o)}; typescript fallback: ${HW(e)}`)}}}function ZW(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Wa(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Ta(t));return async({source:e,filename:t})=>{if(!Ca(e)&&!Ha(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?VW(t):void 0,o=i?t:`[eval].js`,s;try{return await GW(n,e,t,a)}catch(e){s=e}try{return await YW(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${HW(s)}; typescript fallback: ${HW(e)}`)}}}function QW(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
1648
1648
|
`);return t===-1?``:e.slice(t+1)}function $W(e){return cn(e).dir}const eG=[`node`,`require`,`default`],tG=[`node`,`import`,`default`],nG=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,rG=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,iG=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,aG=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,oG=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function sG(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function cG(e){let t=Va(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!sG(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(nG,`require`,`require`),r(rG,`import`,`import`),r(iG,`import`,`import`),r(aG,`import`,`export`),r(oG,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function lG(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=QW(e);if(n===`esm`){if(!r)throw Error(`Cannot load ESM module '${t}': no transpile hook configured (run: ${Ra} esbuild-wasm)`);return await r({source:i,path:t,kind:n})}return i}async function uG(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??eG,s=e.importConditions??tG,c=i??o,l=new Map,u=[],d={},f={};async function p(e,t){if(l.has(e))return;let n=await r.readFile(e),i=await lG(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=$W(e),m={},h={};for(let{specifier:e,kind:t}of cG(n)){let n;try{n=await _a(e,c,r,{conditions:t===`import`?s:o})}catch(t){h[e]=t instanceof Error?t.message:String(t);continue}n.type===`file`&&(m[e]=n.path,await p(n.path,n.moduleKind))}d[e]=m,Object.keys(h).length>0&&(f[e]=h),u.push(e)}let m={};for(let e of t){let t=await _a(e,n,r,{conditions:c});t.type===`file`&&(m[e]=t.path,await p(t.path,t.moduleKind))}return{files:u.map(e=>{let t=l.get(e);if(!t)throw Error(`module-loader: missing built module for '${e}'`);return t}),entryMap:m,edges:d,edgeErrors:f}}function dG(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||ya.has(e)||iU.has(e))}function fG(e,t){for(let[n,r]of Object.entries(t))e[n]={...e[n]??{},...r}}async function pG(e){let{entryCode:t,fromDir:n,entryFilename:r,reader:i,transpile:a,transpileEntry:o}=e,s=new Map,c=[],l={},u={},d={},f={};for(let{specifier:e,kind:r}of cG(t))if(dG(e))try{let t=await uG({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?tG:eG,requireConditions:eG,importConditions:tG});for(let e of t.files)s.has(e.path)||(s.set(e.path,e),c.push(e.path));Object.assign(l,t.entryMap),fG(u,t.edges),fG(d,t.edgeErrors)}catch(t){f[e]=t instanceof Error?t.message:String(t)}let p;o&&(Ca(t)||Ha(t))&&(p=await o({source:t,filename:r??`[eval]`,fromDir:n}));let m={files:c.map(e=>{let t=s.get(e);if(!t)throw Error(`module-loader: missing built module for '${e}'`);return{path:t.path,cjsSource:t.cjsSource,kind:t.kind}}),entryMap:l,edges:u,edgeErrors:d,errors:f};return p!==void 0&&(m.entrySource=p),m}function mG(){return globalThis.navigator?.hid??null}function hG(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function gG(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&hG(e)===hG(t)&&!!e.productName}var _G=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(gG(n,e))return this.byHandle.set(t,e),t;let t=`hid${++this.counter}`;return this.byHandle.set(t,e),t}get(e){return this.byHandle.get(e)}remove(e){return this.byHandle.delete(e)}list(){return[...this.byHandle].map(([e,t])=>({handle:e,device:t}))}};let vG=null;function yG(){return vG||=new _G,vG}const bG=4194304;function xG(e,t){let n=t.collections?.[0];return{handle:e,vendorId:t.vendorId,productId:t.productId,...t.productName?{productName:t.productName}:{},...n?.usagePage===void 0?{}:{usagePage:n.usagePage},...n?.usage===void 0?{}:{usage:n.usage},opened:t.opened}}function SG(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function CG(e){e.opened||await e.open()}function wG(e,t){if(e>4194304)throw Error(`${t} exceeds the ${bG}-byte (4 MiB) v1 limit`)}function TG(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function EG(e,t){return(await t.getDevices()).map(t=>xG(e.register(t),t))}async function DG(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>xG(e.register(t),t))}function OG(e,t){return xG(t,SG(e,t))}async function kG(e,t){await SG(e,t).open()}async function AG(e,t){await SG(e,t).close()}async function jG(e,t,n,r){wG(r.byteLength,`send report payload`);let i=SG(e,t);await CG(i),await i.sendReport(n,r)}async function MG(e,t,n,r){wG(r.byteLength,`send feature report payload`);let i=SG(e,t);await CG(i),await i.sendFeatureReport(n,r)}async function NG(e,t,n){let r=SG(e,t);return await CG(r),{reportId:n,bytes:TG(await r.receiveFeatureReport(n))}}async function PG(e,t,n){let r=SG(e,t);await CG(r);let i=e=>{n({reportId:e.reportId,bytes:TG(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const FG=6e4;function IG(){return uw()}function LG(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),FG);dw(`hid-device`,e??[],void 0,{timeoutMs:FG}).then(e=>{let t=e;t.cancelled?r({cancelled:!0}):typeof t.error==`string`?r({error:t.error}):t.granted&&t.info?r({granted:!0,info:t.info}):r({error:`hid picker returned an unexpected response`})}).catch(e=>{r({error:e instanceof Error?e.message:`Failed to open HID picker`})})})}function RG(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var zG=class{registry;constructor(e){this.registry=e}hid(){let e=mG();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return EG(this.registry,this.hid())}async request(e){if(IG()){let t=await LG(e);if(`cancelled`in t)throw Error(`user cancelled the HID picker`);if(`error`in t)throw Error(t.error);let n=await this.reacquireAll(t.info);if(n.length===0)throw Error(`granted device could not be re-acquired`);return n.map(e=>xG(this.registry.register(e),e))}return DG(this.registry,this.hid(),e)}async reacquireAll(e){return(await this.hid().getDevices()).filter(t=>t.vendorId===e.vendorId&&t.productId===e.productId)}info(e){return Promise.resolve(OG(this.registry,e))}open(e){return kG(this.registry,e)}close(e){return AG(this.registry,e)}sendReport(e,t,n){return jG(this.registry,e,t,RG(n))}sendFeatureReport(e,t,n){return MG(this.registry,e,t,RG(n))}async receiveFeatureReport(e,t){let n=await NG(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return PG(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},BG=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=3e5;async list(){return(await this.rpc.call(`hid-list`,void 0)).devices}async request(t){return(await this.rpc.call(`hid-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).devices}async info(e){return(await this.rpc.call(`hid-device-info`,{handle:e})).device}async open(e){await this.rpc.call(`hid-open`,{handle:e})}async close(e){await this.rpc.call(`hid-close`,{handle:e})}async sendReport(e,t,n){await this.rpc.call(`hid-send-report`,{handle:e,reportId:t,bytes:RG(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:RG(n)})}async receiveFeatureReport(e,t){let n=await this.rpc.call(`hid-receive-feature-report`,{handle:e,reportId:t});return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){let n=this.rpc.onEvent(`hid-input-report`,n=>{let r=n;!r||r.handle!==e||t({reportId:r.reportId,bytes:new Uint8Array(r.bytes)})});try{await this.rpc.call(`hid-subscribe-input-reports`,{handle:e})}catch(e){throw n(),e}return async()=>{n();try{await this.rpc.call(`hid-unsubscribe-input-reports`,{handle:e})}catch{}}}};function VG(e,t){return e&&mG()?new zG(yG()):t?new BG(t):null}function HG(e){return async function(t,n){let r=t instanceof Request?t:null,i=UG(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=GG(r?.headers,n?.headers),s=await JG(n,r,a,o);s.defaultContentType&&!KG(o,`content-type`)&&(o[`Content-Type`]=s.defaultContentType);let c=await e(i,{method:a,headers:o,body:s.body}),l=new Headers;for(let[e,t]of Object.entries(c.headers))try{l.set(e,t)}catch{}let u=c.status===204||c.status===205||c.status===304||!c.body||c.body.byteLength===0?null:c.body,d=new Response(u,{status:c.status,statusText:c.statusText,headers:l});try{Object.defineProperty(d,"url",{value:c.url||i,writable:!1,configurable:!0,enumerable:!1})}catch{}return d}}function UG(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function WG(e){if(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}if(Array.isArray(e)){let t={};for(let[n,r]of e)t[n]=r;return t}return{...e}}}function GG(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=WG(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function KG(e,t){return qG(e,t)!==void 0}function qG(e,t){let n=t.toLowerCase(),r;for(let[t,i]of Object.entries(e))t.toLowerCase()===n&&(r=i);return r}async function JG(e,t,n,r){if(e&&`body`in e&&e.body!==void 0)return YG(e.body,n);if(t&&n!==`GET`&&n!==`HEAD`){let e=t.body!==null,n=new Uint8Array(await t.arrayBuffer()),i=qG(r,`content-type`)??``,a=e&&(!i||!v(i));return{body:n.byteLength===0?void 0:a?ye(n):new TextDecoder(`utf-8`).decode(n),defaultContentType:a?`application/octet-stream`:void 0}}return{}}async function YG(e,t){if(or(e)){if(t===`GET`||t===`HEAD`)return{};let n=await fr(e);return{body:n.bytes,defaultContentType:n.contentType}}return{body:await XG(e,t),defaultContentType:QG(e,t)}}async function XG(e,t){if(e!=null&&t!==`GET`&&t!==`HEAD`){if(typeof e==`string`)return e;if(e instanceof URLSearchParams)return e.toString();if(e instanceof Uint8Array)return ye(e);if(e instanceof ArrayBuffer)return new Uint8Array(e).slice();if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice()}if(typeof Blob<`u`&&e instanceof Blob)return new Uint8Array(await e.arrayBuffer());throw typeof ReadableStream<`u`&&e instanceof ReadableStream?Error(`node fetch shim: ReadableStream request bodies are not supported (collect into a Uint8Array or string before calling fetch)`):Error(`node fetch shim: unsupported request body type (${Object.prototype.toString.call(e)}); use a string, Uint8Array, ArrayBuffer, Blob, FormData, or URLSearchParams`)}}function ZG(e){return e instanceof Uint8Array||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob}function QG(e,t){if(e instanceof URLSearchParams)return`application/x-www-form-urlencoded;charset=UTF-8`;if(!(t===`GET`||t===`HEAD`||!ZG(e)))return typeof Blob<`u`&&e instanceof Blob&&e.type?e.type:`application/octet-stream`}function $G(){return globalThis.navigator?.serial??null}var eK=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(n.port===e)return t;let t=`serial${++this.counter}`;return this.byHandle.set(t,{port:e,opened:!1}),t}get(e){return this.byHandle.get(e)}remove(e){return this.byHandle.delete(e)}list(){return[...this.byHandle].map(([e,t])=>({handle:e,entry:t}))}retainOnly(e){let t=[];for(let[n,r]of[...this.byHandle])e.includes(r.port)||(this.byHandle.delete(n),t.push({handle:n,entry:r}));return t}};let tK=null;function nK(){return tK||=new eK,tK}const rK=4194304;function iK(e,t){let n=t.port.getInfo();return{handle:e,...n.usbVendorId===void 0?{}:{usbVendorId:n.usbVendorId},...n.usbProductId===void 0?{}:{usbProductId:n.usbProductId},opened:t.opened}}function aK(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function oK(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function sK(e,t,n){if(t.length===0)return-1;outer:for(let r=Math.max(0,n);r+t.length<=e.length;r++){for(let n=0;n<t.length;n++)if(e[r+n]!==t[n])continue outer;return r}return-1}async function cK(e){if(e.reader){try{await e.reader.cancel()}catch{}try{e.reader.releaseLock()}catch{}e.reader=void 0}if(e.pendingRead=void 0,e.leftover=void 0,e.writer){try{e.writer.releaseLock()}catch{}e.writer=void 0}}async function lK(e){if(await cK(e),e.opened){try{await e.port.close()}catch{}e.opened=!1}}async function uK(e,t){let n=await t.getPorts();for(let{entry:t}of e.retainOnly(n))await lK(t);return n.map(t=>{let n=e.register(t);return iK(n,e.get(n))})}async function dK(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return iK(i,e.get(i))}function fK(e,t){return iK(t,aK(e,t))}async function pK(e,t,n){let r=aK(e,t);try{await r.port.open(n)}catch(e){throw Error(`${e instanceof Error?e.message:String(e)} (handle '${t}' may be stale after a device reset — re-run 'serial list' to pick up the current handle)`)}r.opened=!0}async function mK(e,t){let n=aK(e,t);await cK(n);try{await n.port.close()}catch(e){if(!hK(e))throw e}n.opened=!1}function hK(e){let t=e instanceof Error?e.message:String(e);return/already closed|not open/i.test(t)}function gK(e){if(!e.reader){if(!e.port.readable)throw Error(`serial port is not readable (is it open?)`);e.reader=e.port.readable.getReader()}return e.reader}function _K(e){if(!e.writer){if(!e.port.writable)throw Error(`serial port is not writable (is it open?)`);e.writer=e.port.writable.getWriter()}return e.writer}async function vK(e,t,n){let r=aK(e,t),i=Math.min(n.maxBytes??4194304,rK),a=n.until?.length?n.until:void 0,o=n.timeoutMs??1e3,s=Date.now()+Math.max(0,o),c=r.leftover??new Uint8Array;r.leftover=void 0;let l=0,u=()=>{if(a){let e=sK(c,a,Math.max(0,l-(a.length-1)));if(e>=0){let t=e+a.length;return r.leftover=c.slice(t),c.slice(0,t)}}return c.length>=i?(r.leftover=c.slice(i),c.slice(0,i)):null},d=u();if(d)return d;let f=gK(r);for(;Date.now()<s;){let e=s-Date.now(),t=r.pendingRead??f.read();r.pendingRead=t;let n,i=new Promise(t=>{n=setTimeout(()=>t(`__timeout`),e)}),a;try{a=await Promise.race([t,i])}finally{n&&clearTimeout(n)}if(a===`__timeout`)break;if(r.pendingRead=void 0,a.done){r.reader=void 0;break}if(a.value?.length){l=c.length,c=oK(c,a.value);let e=u();if(e)return e}}return c}async function yK(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${rK}-byte (4 MiB) v1 limit`);return await _K(aK(e,t)).write(n),n.length}async function bK(e,t){return aK(e,t).port.getSignals()}async function xK(e,t,n){await aK(e,t).port.setSignals(n)}const SK=6e4;function CK(){return uw()}function wK(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),SK);dw(`serial-port`,e??[],void 0,{timeoutMs:SK}).then(e=>{let t=e;t.cancelled?r({cancelled:!0}):typeof t.error==`string`?r({error:t.error}):t.granted&&t.info?r({granted:!0,info:t.info}):r({error:`serial picker returned an unexpected response`})}).catch(e=>{r({error:e instanceof Error?e.message:`Failed to open serial picker`})})})}function TK(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var EK=class{registry;constructor(e){this.registry=e}serial(){let e=$G();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return uK(this.registry,this.serial())}async request(e){if(CK()){let t=await wK(e);if(`cancelled`in t)throw Error(`user cancelled the serial picker`);if(`error`in t)throw Error(t.error);let n=await this.reacquire(t.info);if(!n)throw Error(`granted port could not be re-acquired`);let r=this.registry.register(n);return iK(r,this.registry.get(r))}return dK(this.registry,this.serial(),e)}async reacquire(e){let t=await this.serial().getPorts(),n=t.filter(t=>{let n=t.getInfo();return!(e.usbVendorId!==void 0&&n.usbVendorId!==e.usbVendorId||e.usbProductId!==void 0&&n.usbProductId!==e.usbProductId)}),r=n.length?n:t,i=this.registry.list().map(e=>e.entry.port);return r.find(e=>!i.includes(e))??r[0]??null}info(e){return Promise.resolve(fK(this.registry,e))}open(e,t){return pK(this.registry,e,t)}close(e){return mK(this.registry,e)}read(e,t){return vK(this.registry,e,t)}write(e,t){return yK(this.registry,e,t)}getSignals(e){return bK(this.registry,e)}setSignals(e,t){return xK(this.registry,e,t)}},DK=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=3e5;static READ_MARGIN_MS=3e4;async list(){return(await this.rpc.call(`serial-list`,void 0)).devices}async request(t){return(await this.rpc.call(`serial-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).device}async info(e){return(await this.rpc.call(`serial-device-info`,{handle:e})).device}async open(e,t){await this.rpc.call(`serial-open`,{handle:e,options:t})}async close(e){await this.rpc.call(`serial-close`,{handle:e})}async read(t,n){let r=(n.timeoutMs??1e3)+e.READ_MARGIN_MS,i=await this.rpc.call(`serial-read`,{handle:t,maxBytes:n.maxBytes,until:n.until?TK(n.until):void 0,timeoutMs:n.timeoutMs},{timeoutMs:r});return new Uint8Array(i.bytes)}async write(e,t){return(await this.rpc.call(`serial-write`,{handle:e,bytes:TK(t)})).bytesWritten}async getSignals(e){return(await this.rpc.call(`serial-get-signals`,{handle:e})).signals}async setSignals(e,t){await this.rpc.call(`serial-set-signals`,{handle:e,signals:t})}};function OK(e,t){return e&&$G()?new EK(nK()):t?new DK(t):null}function kK(){return globalThis.navigator?.usb??null}function AK(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var jK=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(AK(n,e))return this.byHandle.set(t,e),t;let t=`usb${++this.counter}`;return this.byHandle.set(t,e),t}get(e){return this.byHandle.get(e)}remove(e){return this.byHandle.delete(e)}list(){return[...this.byHandle].map(([e,t])=>({handle:e,device:t}))}};let MK=null;function NK(){return MK||=new jK,MK}const PK=4194304,FK=new Set([`in`,`out`]),IK=new Set([`bulk`,`interrupt`,`isochronous`]);function LK(e){return e.map(e=>({configurationValue:e.configurationValue,...e.configurationName?{configurationName:e.configurationName}:{},interfaces:(e.interfaces??[]).map(e=>({interfaceNumber:e.interfaceNumber,claimed:!!e.claimed,alternates:(e.alternates??[]).map(e=>({alternateSetting:e.alternateSetting,interfaceClass:e.interfaceClass,interfaceSubclass:e.interfaceSubclass,interfaceProtocol:e.interfaceProtocol,...e.interfaceName?{interfaceName:e.interfaceName}:{},endpoints:(e.endpoints??[]).filter(e=>FK.has(e.direction)&&IK.has(e.type)).map(e=>({endpointNumber:e.endpointNumber,direction:e.direction,type:e.type,packetSize:e.packetSize}))}))}))}))}function RK(e,t){return{handle:e,vendorId:t.vendorId,productId:t.productId,...t.productName?{productName:t.productName}:{},...t.manufacturerName?{manufacturerName:t.manufacturerName}:{},...t.serialNumber?{serialNumber:t.serialNumber}:{},opened:t.opened,...t.configurations?{configurations:LK(t.configurations)}:{}}}function zK(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function BK(e,t){if(e>4194304)throw Error(`${t} exceeds the ${PK}-byte (4 MiB) v1 limit`)}function VK(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function HK(e,t){return(await t.getDevices()).map(t=>RK(e.register(t),t))}async function UK(e,t,n){let r=await t.requestDevice({filters:n});return RK(e.register(r),r)}function WK(e,t){return RK(t,zK(e,t))}async function GK(e,t){await zK(e,t).open()}async function KK(e,t){await zK(e,t).close()}async function qK(e,t,n){await zK(e,t).selectConfiguration(n)}async function JK(e,t,n){await zK(e,t).claimInterface(n)}async function YK(e,t,n){await zK(e,t).releaseInterface(n)}async function XK(e,t,n,r){BK(r,`control-in length`);let i=await zK(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?VK(i.data):new ArrayBuffer(0)}}async function ZK(e,t,n,r){BK(r.byteLength,`control-out payload`);let i=await zK(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function QK(e,t,n,r){BK(r,`transfer-in length`);let i=await zK(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?VK(i.data):new ArrayBuffer(0)}}async function $K(e,t,n,r){BK(r.byteLength,`transfer-out payload`);let i=await zK(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function eq(e,t){await zK(e,t).reset()}async function tq(e,t,n,r){await zK(e,t).clearHalt(n,r)}const nq=6e4;function rq(){return uw()}function iq(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),nq);dw(`usb-device`,e??[],void 0,{timeoutMs:nq}).then(e=>{let t=e;t.cancelled?r({cancelled:!0}):typeof t.error==`string`?r({error:t.error}):t.granted&&t.info?r({granted:!0,info:t.info}):r({error:`usb picker returned an unexpected response`})}).catch(e=>{r({error:e instanceof Error?e.message:`Failed to open USB picker`})})})}function aq(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var oq=class{registry;constructor(e){this.registry=e}usb(){let e=kK();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return HK(this.registry,this.usb())}async request(e){if(rq()){let t=await iq(e);if(`cancelled`in t)throw Error(`user cancelled the USB picker`);if(`error`in t)throw Error(t.error);let n=await this.reacquire(t.info);if(!n)throw Error(`granted device could not be re-acquired`);return RK(this.registry.register(n),n)}return UK(this.registry,this.usb(),e)}async reacquire(e){return(await this.usb().getDevices()).find(t=>t.vendorId===e.vendorId&&t.productId===e.productId&&(!e.serialNumber||t.serialNumber===e.serialNumber))??null}info(e){return Promise.resolve(WK(this.registry,e))}open(e){return GK(this.registry,e)}close(e){return KK(this.registry,e)}selectConfig(e,t){return qK(this.registry,e,t)}claim(e,t){return JK(this.registry,e,t)}release(e,t){return YK(this.registry,e,t)}async controlIn(e,t,n){let r=await XK(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return ZK(this.registry,e,t,aq(n))}async transferIn(e,t,n){let r=await QK(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return $K(this.registry,e,t,aq(n))}clearHalt(e,t,n){return tq(this.registry,e,t,n)}reset(e){return eq(this.registry,e)}},sq=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=3e5;async list(){return(await this.rpc.call(`usb-list`,void 0)).devices}async request(t){return(await this.rpc.call(`usb-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).device}async info(e){return(await this.rpc.call(`usb-device-info`,{handle:e})).device}async open(e){await this.rpc.call(`usb-open`,{handle:e})}async close(e){await this.rpc.call(`usb-close`,{handle:e})}async selectConfig(e,t){await this.rpc.call(`usb-select-configuration`,{handle:e,configurationValue:t})}async claim(e,t){await this.rpc.call(`usb-claim-interface`,{handle:e,interfaceNumber:t})}async release(e,t){await this.rpc.call(`usb-release-interface`,{handle:e,interfaceNumber:t})}async controlIn(e,t,n){let r=await this.rpc.call(`usb-control-transfer-in`,{handle:e,setup:t,length:n});return{status:r.status,bytes:new Uint8Array(r.bytes)}}async controlOut(e,t,n){return this.rpc.call(`usb-control-transfer-out`,{handle:e,setup:t,bytes:aq(n)})}async transferIn(e,t,n){let r=await this.rpc.call(`usb-transfer-in`,{handle:e,endpointNumber:t,length:n});return{status:r.status,bytes:new Uint8Array(r.bytes)}}async transferOut(e,t,n){return this.rpc.call(`usb-transfer-out`,{handle:e,endpointNumber:t,bytes:aq(n)})}async clearHalt(e,t,n){await this.rpc.call(`usb-clear-halt`,{handle:e,direction:t,endpointNumber:n})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function cq(e,t){return e&&kK()?new oq(NK()):t?new sq(t):null}function lq(e,t,n,r={}){let{header:i,window:a}=uW(t),o=new Map,s=!1,c=r.dispatch??(e=>WU(e)?qU(e):LU(e));function l(e){let t=o.get(e);t&&(clearTimeout(t.timer),o.delete(e))}function u(e,t,n){let r=Math.min(a.byteLength,t.payload.byteLength-n);r>0&&a.set(t.payload.subarray(n,n+r)),Atomics.store(i,2,t.status),Atomics.store(i,3,t.payload.byteLength),Atomics.store(i,4,r),Atomics.store(i,5,n),Atomics.store(i,1,e),Atomics.store(i,0,2),Atomics.notify(i,0),n+r>=t.payload.byteLength&&l(e)}function d(e,t){if(s)return;let{status:n,payload:r}=cW(t);l(e);let i={status:n,payload:r,timer:setTimeout(()=>l(e),605e3)};o.set(e,i),u(e,i,0)}let f=e=>{let t=e.data;if(!t||typeof t.id!=`number`)return;if(t.type===`sync-sab-next`){let e=o.get(t.id),n=t.offset;if(!e||typeof n!=`number`||!Number.isInteger(n)||n<0||n>e.payload.byteLength){d(t.id,{ok:!1,errno:`EIO`,message:`sync-sab: bad continuation`});return}u(t.id,e,n);return}if(t.type!==`sync-sab-req`||!t.req||typeof t.req!=`object`)return;let r=t.id,i={...t.req,token:n},a;try{a=c(i)}catch(e){d(r,{ok:!1,errno:`EIO`,message:e instanceof Error?e.message:String(e)});return}a.then(e=>d(r,e),e=>d(r,{ok:!1,errno:`EIO`,message:e instanceof Error?e.message:String(e)}))};return e.addEventListener(`message`,f),{dispose:()=>{if(!s){s=!0,e.removeEventListener(`message`,f);for(let e of[...o.keys()])l(e)}}}}const uq=r(`realm-host`);function dq(e,t,n={}){let r=new Map,i=n.syncFsBridgeEnabled?MU({fs:t.fs,...t.exec?{exec:t.exec}:{},cwd:t.cwd}):void 0,a=!1,o={subscriptions:r,pushEvent:(t,n=[])=>{if(!a)try{e.postMessage(t,n)}catch{}}},s=new Map,c={spawns:s,opts:n},l=r=>{if(r.data?.type!==`realm-rpc-req`)return;let i=r.data;fq(e,i,t,n,o,c)};e.addEventListener(`message`,l);let u=i&&n.syncSab?lq(e,n.syncSab,i):void 0;return e.start?.(),{syncFsToken:i,dispose:()=>{if(!a){a=!0,u?.dispose(),i&&FU(i),e.removeEventListener(`message`,l);for(let{controller:e}of s.values())try{e.signal.aborted||e.abort()}catch{}s.clear();for(let e of r.values())try{Promise.resolve(e()).catch(()=>{})}catch{}r.clear()}}}}async function fq(e,t,n,r,i,a){try{let o=await pq(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=nJ(o);e.postMessage(s,c)}catch(n){let r=n instanceof Error?n.message:String(n),i={type:`realm-rpc-res`,id:t.id,error:r};e.postMessage(i)}}async function pq(e,t,n,r,i){switch(e.channel){case`vfs`:return yq(e.op,e.args,t);case`exec`:return Mq(e.op,e.args,t,i);case`fetch`:return Iq(e.op,e.args,t);case`browser`:return Bq(e.op,e.args,mq(n),n);case`usb`:return $q(e.op,e.args,gq(n));case`serial`:return eJ(e.op,e.args,_q(n));case`hid`:return tJ(e.op,e.args,vq(n),r);case`module`:return Rq(e.op,e.args,t);case`wasm`:return zq(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function mq(e){if(e.browser)return e.browser;let t=globalThis;if(t.__slicc_browser)return t.__slicc_browser;throw Error(`browser is not available in this runtime`)}function hq(e){if(e.wsSubscribers)return e.wsSubscribers;let t=globalThis;if(t.__slicc_wsSubscribers)return t.__slicc_wsSubscribers;throw Error(`browser.websocket is not available in this runtime`)}function gq(e){if(e.usbBackend)return e.usbBackend;let t=cq(d(),u());if(!t)throw Error(`usb is not available in this runtime`);return t}function _q(e){if(e.serialBackend)return e.serialBackend;let t=OK(d(),u());if(!t)throw Error(`serial is not available in this runtime`);return t}function vq(e){if(e.hidBackend)return e.hidBackend;let t=VG(d(),u());if(!t)throw Error(`hid is not available in this runtime`);return t}async function yq(e,t,n){let r=typeof t[0]==`string`?t[0]:null,i=r===null?null:n.fs.resolvePath(n.cwd,r);switch(e){case`readFile`:return n.fs.readFile(i);case`readFileBinary`:return n.fs.readFileBuffer(i);case`writeFile`:return await n.fs.writeFile(i,t[1]),!0;case`writeFileBinary`:return await n.fs.writeFile(i,t[1]),!0;case`readDir`:return n.fs.readdir(i);case`exists`:return n.fs.exists(i);case`stat`:{let e=await n.fs.stat(i);return{isDirectory:e.isDirectory,isFile:e.isFile,size:e.size}}case`mkdir`:return await n.fs.mkdir(i,{recursive:!0}),!0;case`rm`:return await n.fs.rm(i,{recursive:!0}),!0;case`rename`:{let e=n.fs.resolvePath(n.cwd,t[1]),r=n.fs;if(r.rename)await r.rename(i,e);else{let t=await n.fs.readFileBuffer(i);await n.fs.writeFile(e,t),await n.fs.rm(i,{recursive:!0})}return!0}case`resolvePath`:return n.fs.resolvePath(n.cwd,t[0]);case`invalidatePaths`:{let e=t[0],r=n.fs;return r.invalidatePaths&&r.invalidatePaths(e),!0}case`snapshot`:return Oq(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await kq(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const bq=10485760;function xq(e){return e.fileCount>=500||e.totalBytes>=bq}function Sq(e){return e.entries.length>=2e4}async function Cq(e,t,n,r){r.entries.push({path:t,content:new Uint8Array,isDirectory:!0});let i;try{i=await e.fs.readdir(t)}catch{return}for(let e of i)e!==`node_modules`&&n.push(t===`/`?`/${e}`:`${t}/${e}`)}async function wq(e,t,n,r){let i=``;try{i=await e.fs.readlink(t)}catch{return}r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,isSymbolicLink:!0,symlinkTarget:i,size:n})}async function Tq(e,t,n,r,i){if(n>1048576||xq(r)||r.totalBytes+n>bq){r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:n});return}let a;try{a=await e.fs.readFileBuffer(t)}catch{await Eq(e,t,i,r);return}r.entries.push({path:t,content:a,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=a.byteLength}async function Eq(e,t,n,r){let i;try{i=await e.fs.stat(t)}catch{return}if(i.isDirectory){await Cq(e,t,n,r);return}r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:i.size})}async function Dq(e,t,n){if(Sq(n))return;let r=[t];for(;r.length>0;){if(Sq(n))return;let t=r.pop(),i;try{i=await e.fs.lstat(t)}catch{}if(i?.isSymbolicLink){await wq(e,t,i.size,n);continue}let a;try{a=await e.fs.stat(t)}catch{continue}a.isDirectory?await Cq(e,t,r,n):a.isFile&&await Tq(e,t,a.size,n,r)}}async function Oq(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await Dq(e,t,n),t!==`/tmp`&&await Dq(e,`/tmp`,n),{entries:n.entries}}async function kq(e,t){let n=[],r=async(e,t)=>{try{await t()}catch(t){n.push(`${e}: ${t instanceof Error?t.message:String(t)}`)}};for(let n of t.deleted)await r(n,()=>e.fs.rm(n,{recursive:!0}));for(let n of t.created)n.isSymbolicLink?await r(n.path,()=>e.fs.symlink(n.symlinkTarget??``,n.path)):n.isDirectory?await r(n.path,()=>e.fs.mkdir(n.path,{recursive:!0})):await r(n.path,()=>e.fs.writeFile(n.path,n.content));for(let n of t.modified)await r(n.path,()=>e.fs.writeFile(n.path,n.content));if(n.length>0)throw Error(`sync-fs flush failed for ${n.length} path(s): ${n.join(`; `)}`)}const Aq=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),jq=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function Mq(e,t,n,r){if(!n.exec)throw Error(`exec is not available in this runtime`);if(e===`run`){let e=t[0],r=await n.exec(e,{cwd:n.cwd});return{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode}}if(e===`spawn`){let e=t[0];if(!Array.isArray(e)||e.length===0||!e.every(e=>typeof e==`string`))throw Error(`exec.spawn: argv must be a non-empty string[]`);let[r,...i]=e,a=await n.exec(r,{cwd:n.cwd,args:i});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}if(e===`start`)return Pq(t,n,r);if(e===`kill`)return Fq(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function Nq(e){if(e.stdin!==void 0&&typeof e.stdin!=`string`)throw Error(`exec.start: stdin must be a string`);if(e.stdinKind!==void 0&&e.stdinKind!==`text`&&e.stdinKind!==`bytes`)throw Error(`exec.start: stdinKind must be 'text' or 'bytes'`);if(e.args!==void 0&&(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`)))throw Error(`exec.start: args must be a string[]`)}async function Pq(e,t,n){let[r,i,a]=e;if(typeof r!=`number`)throw Error(`exec.start: spawnId must be a number`);if(n.spawns.has(r))throw Error(`exec.start: spawnId ${r} is already in use`);let o,s,c;if(Array.isArray(i)){if(i.length===0||!i.every(e=>typeof e==`string`))throw Error(`exec.start: argv must be a non-empty string[]`);[o,...s]=i,c=i.slice()}else if(typeof i==`string`)o=i,c=[i];else throw Error(`exec.start: command must be a string or a non-empty string[]`);let l=a??{};Nq(l);let u=new AbortController,{pm:d,owner:f}=n.opts,p=0;d&&f&&(p=d.spawn({kind:`shell`,argv:c,cwd:t.cwd,owner:f,...n.opts.ppid===void 0?{}:{ppid:n.opts.ppid},adoptAbort:u}).pid),n.spawns.set(r,{controller:u,pid:p});let m;try{let e={cwd:t.cwd,signal:u.signal};return l.stdin!==void 0&&(e.stdin=l.stdin),l.stdinKind!==void 0&&(e.stdinKind=l.stdinKind),s===void 0?l.args!==void 0&&(e.args=l.args):e.args=s,m=await t.exec(o,e),{stdout:m.stdout,stderr:m.stderr,exitCode:m.exitCode}}finally{if(n.spawns.delete(r),d&&p){let e=d.get(p);d.exit(p,e?.terminatedBy?null:m?.exitCode??1)}}}function Fq(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&Aq.has(r)?r:`SIGTERM`;jq.has(a)&&!i.controller.signal.aborted&&i.controller.abort();let{pm:o}=t.opts;return o&&i.pid?o.signal(i.pid,a):!0}async function Iq(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?HG(n.fetch):globalThis.fetch.bind(globalThis))(r,i),o={};a.headers.forEach((e,t)=>{o[t]=e});let s=new Uint8Array(await a.arrayBuffer());return{status:a.status,statusText:a.statusText,headers:o,body:s,url:a.url}}function Lq(e){let t=t=>e.fs.resolvePath(e.cwd,t);return{exists:n=>e.fs.exists(t(n)),isDirectory:async n=>{try{return(await e.fs.stat(t(n))).isDirectory}catch{return!1}},readFile:async n=>{let r=await e.fs.readFile(t(n));return typeof r==`string`?r:new TextDecoder().decode(r)}}}async function Rq(e,t,n){if(e!==`buildGraph`)throw Error(`realm-host: unknown module op '${e}'`);let r=typeof t[0]==`string`?t[0]:``,i=typeof t[1]==`string`&&t[1]?t[1]:n.cwd,a=typeof t[2]==`string`?t[2]:``,o=Lq(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return pG({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:XW({ipk:s}),transpileEntry:ZW({ipk:s})})}async function zq(e,t,n){if(e!==`compile`)throw Error(`realm-host: unknown wasm op '${e}'`);let r=typeof t[0]==`string`?t[0]:null;if(r===null)throw Error(`realm-host: wasm.compile requires a path argument`);let i=n.fs.resolvePath(n.cwd,r);return qa(e=>n.fs.readFileBuffer(e),i)}async function Bq(e,t,n,r){switch(e){case`findTab`:return Uq(n,t[0]??{});case`ensureTab`:{let e=t[0];return Wq(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return Gq(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return Gq(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return Yq(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return Xq(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await hq(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return hq(r).update(e,n)}case`wsClose`:{let e=t[0];return hq(r).close(e)}case`wsList`:return hq(r).list();case`createTab`:{let e=t[0];return n.createPage(e)}case`closeTab`:{let e=t[0];return n.closePage(e)}case`setViewport`:{let e=t[0],r=t[1],i=t[2];return n.withTab(e,e=>e.setViewportOverride(r,i))}case`navigateTab`:{let e=t[0],r=t[1];return n.withTab(e,e=>e.navigate(r))}case`screenshotTab`:{let e=t[0],r=t[1];return n.withTab(e,async e=>(await e.bringToFront(),e.screenshot(r)))}case`waitForLoadState`:{let e=t[0],r=t[1];return Jq(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function Vq(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function Hq(e){if(typeof e.listAllTargets!=`function`)return(await e.listPages()).map(e=>({targetId:e.targetId,url:e.url,title:e.title}));let t=(await e.listAllTargets()).map(e=>({targetId:e.targetId,url:e.url,title:e.title})),n=Vq()?u():null;if(n)try{let{targets:e}=await n.call(`list-remote-targets`,void 0,{timeoutMs:3e3}),r=new Set(t.map(e=>e.targetId));for(let n of e)r.has(n.targetId)||(r.add(n.targetId),t.push({targetId:n.targetId,url:n.url,title:n.title}))}catch(e){uq.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function Uq(e,t){let n=await Hq(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=Zq(t.url);if(n&&n.toLowerCase()===e)return t}return null}if(t.urlMatch){let e;try{e=new RegExp(t.urlMatch)}catch(e){throw Error(`browser.findTab: invalid urlMatch regex: ${e instanceof Error?e.message:String(e)}`)}for(let t of n)if(e.test(t.url))return t;return null}throw Error("browser.findTab: query requires `domain` or `urlMatch`")}async function Wq(e,t,n){let r=await Hq(e);if(n.matchUrl){let e;try{e=new RegExp(n.matchUrl)}catch(e){throw Error(`browser.ensureTab: invalid matchUrl regex: ${e instanceof Error?e.message:String(e)}`)}let t=r.find(t=>e.test(t.url));if(t)return t}else{let e=Qq(t);if(e){let t=r.find(t=>Qq(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function Gq(e,t,n,r){return e.withTab(t,async e=>Kq(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function Kq(e){if(typeof e!=`string`)return e;let t=qq(e);if(t===void 0)return e;if(typeof t==`object`&&t)return t;if(typeof t==`string`){let e=t.trim();if(e.length>0&&(e[0]===`{`||e[0]===`[`)){let e=qq(t);if(typeof e==`object`&&e)return e}return t}return e}function qq(e){let t=e.trim();if(t.length===0)return;let n=t[0];if(n===`{`||n===`[`||n===`"`||n===`-`||n>=`0`&&n<=`9`||t===`true`||t===`false`||t===`null`)try{return JSON.parse(t)}catch{return}}async function Jq(e,t,n){if(n===`networkidle`)return e.withTab(t,async e=>{for(let t=0;t<20;t++)if(await new Promise(e=>setTimeout(e,250)),await e.evaluate(`(function(){
|
|
1649
1649
|
try {
|
|
1650
1650
|
var entries = performance.getEntriesByType('resource');
|
|
@@ -1661,7 +1661,7 @@ except BaseException:
|
|
|
1661
1661
|
})()`,{returnByValue:!0}))return})}async function Yq(e,t,n){return e.withTab(t,async e=>{let t=((await e.send(`Network.getCookies`)).cookies??[]).find(e=>e.name===n);return t&&typeof t.value==`string`?t.value:null})}async function Xq(e,t,n){return e.withTab(t,async e=>{let t=await e.evaluate(`(function(){try{var v=window.localStorage.getItem(${JSON.stringify(n)});return v===null?null:String(v);}catch(e){return null;}})()`,{returnByValue:!0});return t==null?null:typeof t==`string`?t:String(t)})}function Zq(e){try{return new URL(e).hostname}catch{return null}}function Qq(e){try{return new URL(e).origin}catch{return null}}async function $q(e,t,n){switch(e){case`list`:return n.list();case`request`:return n.request(t[0]??[]);case`info`:return n.info(t[0]);case`open`:return n.open(t[0]);case`close`:return n.close(t[0]);case`reset`:return n.reset(t[0]);case`clearHalt`:return n.clearHalt(t[0],t[1],t[2]);case`selectConfig`:return n.selectConfig(t[0],t[1]);case`claim`:return n.claim(t[0],t[1]);case`release`:return n.release(t[0],t[1]);case`controlIn`:return n.controlIn(t[0],t[1],t[2]);case`controlOut`:return n.controlOut(t[0],t[1],t[2]);case`transferIn`:return n.transferIn(t[0],t[1],t[2]);case`transferOut`:return n.transferOut(t[0],t[1],t[2]);default:throw Error(`realm-host: unknown usb op '${e}'`)}}async function eJ(e,t,n){switch(e){case`list`:return n.list();case`request`:return n.request(t[0]??[]);case`info`:return n.info(t[0]);case`open`:return n.open(t[0],t[1]);case`close`:return n.close(t[0]);case`read`:{let e=t[1]??{};return n.read(t[0],e)}case`write`:return n.write(t[0],t[1]);case`getSignals`:return n.getSignals(t[0]);case`setSignals`:return n.setSignals(t[0],t[1]);default:throw Error(`realm-host: unknown serial op '${e}'`)}}async function tJ(e,t,n,r){switch(e){case`list`:return n.list();case`request`:return n.request(t[0]??[]);case`info`:return n.info(t[0]);case`open`:return n.open(t[0]);case`close`:return n.close(t[0]);case`sendReport`:return n.sendReport(t[0],t[1],t[2]);case`sendFeatureReport`:return n.sendFeatureReport(t[0],t[1],t[2]);case`receiveFeatureReport`:return n.receiveFeatureReport(t[0],t[1]);case`subscribeInputReports`:{let e=t[0];if(r.subscriptions.has(e))return!0;let i=await n.subscribeInputReports(e,t=>{let n=t.bytes instanceof Uint8Array?t.bytes:new Uint8Array(t.bytes),i={type:`realm-event`,channel:`hid-input-report`,payload:{handle:e,reportId:t.reportId,bytes:n}};r.pushEvent(i,[n.buffer])});return r.subscriptions.set(e,i),!0}case`unsubscribeInputReports`:{let e=t[0],n=r.subscriptions.get(e);return!n||(r.subscriptions.delete(e),await n(),!0)}default:throw Error(`realm-host: unknown hid op '${e}'`)}}function nJ(e){if(e instanceof Uint8Array)return[e.buffer];if(e&&typeof e==`object`){let t=e;if(t.body instanceof Uint8Array)return[t.body.buffer];if(t.bytes instanceof Uint8Array)return[t.bytes.buffer]}return[]}async function rJ(e){let t=e.procKind??`jsh`,n=e.pm.spawn({kind:t,argv:e.argv,cwd:e.cwd,env:e.env,owner:e.owner,ppid:e.ppid}),r;try{r=await e.realmFactory({kind:e.kind,ctx:e.ctx})}catch(t){let r=t instanceof Error?t.message:String(t);return e.pm.exit(n.pid,1),{stdout:``,stderr:`realm-runner: ${r}\n`,exitCode:1}}let i=r.isolatedThread?iJ(e.syncSabBytes):void 0,a=dq(r.controlPort,e.ctx,{...e.owner.scoopJid===void 0?{}:{scoopJid:e.owner.scoopJid},pm:e.pm,owner:e.owner,ppid:n.pid,syncFsBridgeEnabled:!!e.syncFsBridgeEnabled||i!==void 0,...i?{syncSab:i}:{}});return new Promise(t=>{let o=!1,s=null,c=null,l=null,u=null,d=()=>{c&&r.controlPort.removeEventListener(`message`,c),r.removeEventListener&&(l&&r.removeEventListener(`error`,l),u&&r.removeEventListener(`messageerror`,u)),s?.(),a.dispose()},f=(i,a)=>{if(!o){o=!0,d();try{r.terminate()}catch{}e.pm.exit(n.pid,a),t(i)}};c=e=>{let t=e.data;if(t?.type===`realm-done`){let t=e.data;f({stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode},t.exitCode)}else if(t?.type===`realm-error`){let t=e.data;f({stdout:``,stderr:t.message+`
|
|
1662
1662
|
`,exitCode:1},1)}},l=e=>{let t=e.message??`realm error`;f({stdout:``,stderr:t+`
|
|
1663
1663
|
`,exitCode:1},1)},u=()=>{f({stdout:``,stderr:`realm-runner: worker message could not be deserialized
|
|
1664
|
-
`,exitCode:1},1)},s=e.pm.onSignal((e,t)=>{e.pid===n.pid&&(t===`SIGKILL`?f({stdout:``,stderr:``,exitCode:137},137):t===`SIGINT`?f({stdout:``,stderr:``,exitCode:130},130):t===`SIGTERM`&&f({stdout:``,stderr:``,exitCode:143},143))}),r.controlPort.addEventListener(`message`,c),r.addEventListener&&(r.addEventListener(`error`,l),r.addEventListener(`messageerror`,u));let p={type:`realm-init`,kind:e.kind,code:e.code,argv:e.realmArgv??e.argv,env:e.env,cwd:e.cwd,filename:e.filename,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,opfsMountDbName:e.opfsMountDbName,mountPoints:e.mountPoints,...a.syncFsToken===void 0?{}:{syncFsToken:a.syncFsToken},...i?{syncSab:i}:{}};r.controlPort.postMessage(p)})}function iJ(e){if(dW())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let aJ=!1;function oJ(e){aJ=e}function sJ(){return aJ}const cJ=Object.freeze({anthropic:`ANTHROPIC_API_KEY`,"ant-ling":`ANT_LING_API_KEY`,"qwen-token-plan":`QWEN_TOKEN_PLAN_API_KEY`,"qwen-token-plan-cn":`QWEN_TOKEN_PLAN_CN_API_KEY`,"qwen-token-plan-individual":`QWEN_TOKEN_PLAN_API_KEY`,openai:`OPENAI_API_KEY`,"azure-openai-responses":`AZURE_OPENAI_API_KEY`,nvidia:`NVIDIA_API_KEY`,deepseek:`DEEPSEEK_API_KEY`,google:`GEMINI_API_KEY`,"google-vertex":`GOOGLE_CLOUD_API_KEY`,groq:`GROQ_API_KEY`,cerebras:`CEREBRAS_API_KEY`,xai:`XAI_API_KEY`,radius:`RADIUS_API_KEY`,openrouter:`OPENROUTER_API_KEY`,"vercel-ai-gateway":`AI_GATEWAY_API_KEY`,zai:`ZAI_API_KEY`,"zai-coding-cn":`ZAI_CODING_CN_API_KEY`,mistral:`MISTRAL_API_KEY`,minimax:`MINIMAX_API_KEY`,"minimax-cn":`MINIMAX_CN_API_KEY`,moonshotai:`MOONSHOT_API_KEY`,"moonshotai-cn":`MOONSHOT_API_KEY`,huggingface:`HF_TOKEN`,fireworks:`FIREWORKS_API_KEY`,together:`TOGETHER_API_KEY`,baseten:`BASETEN_API_KEY`,opencode:`OPENCODE_API_KEY`,"opencode-go":`OPENCODE_API_KEY`,"kimi-coding":`KIMI_API_KEY`,"cloudflare-workers-ai":`CLOUDFLARE_API_KEY`,"cloudflare-ai-gateway":`CLOUDFLARE_API_KEY`,xiaomi:`XIAOMI_API_KEY`,"xiaomi-token-plan-cn":`XIAOMI_TOKEN_PLAN_CN_API_KEY`,"xiaomi-token-plan-ams":`XIAOMI_TOKEN_PLAN_AMS_API_KEY`,"xiaomi-token-plan-sgp":`XIAOMI_TOKEN_PLAN_SGP_API_KEY`});function lJ(e){return cJ[e]??null}function uJ(e,t){let n=lJ(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let dJ=null;function fJ(e){let t=dJ;return dJ=e,t}async function pJ(){if(!dJ)return{};try{return await dJ()??{}}catch{return{}}}function mJ(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-
|
|
1664
|
+
`,exitCode:1},1)},s=e.pm.onSignal((e,t)=>{e.pid===n.pid&&(t===`SIGKILL`?f({stdout:``,stderr:``,exitCode:137},137):t===`SIGINT`?f({stdout:``,stderr:``,exitCode:130},130):t===`SIGTERM`&&f({stdout:``,stderr:``,exitCode:143},143))}),r.controlPort.addEventListener(`message`,c),r.addEventListener&&(r.addEventListener(`error`,l),r.addEventListener(`messageerror`,u));let p={type:`realm-init`,kind:e.kind,code:e.code,argv:e.realmArgv??e.argv,env:e.env,cwd:e.cwd,filename:e.filename,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,opfsMountDbName:e.opfsMountDbName,mountPoints:e.mountPoints,...a.syncFsToken===void 0?{}:{syncFsToken:a.syncFsToken},...i?{syncSab:i}:{}};r.controlPort.postMessage(p)})}function iJ(e){if(dW())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let aJ=!1;function oJ(e){aJ=e}function sJ(){return aJ}const cJ=Object.freeze({anthropic:`ANTHROPIC_API_KEY`,"ant-ling":`ANT_LING_API_KEY`,"qwen-token-plan":`QWEN_TOKEN_PLAN_API_KEY`,"qwen-token-plan-cn":`QWEN_TOKEN_PLAN_CN_API_KEY`,"qwen-token-plan-individual":`QWEN_TOKEN_PLAN_API_KEY`,openai:`OPENAI_API_KEY`,"azure-openai-responses":`AZURE_OPENAI_API_KEY`,nvidia:`NVIDIA_API_KEY`,deepseek:`DEEPSEEK_API_KEY`,google:`GEMINI_API_KEY`,"google-vertex":`GOOGLE_CLOUD_API_KEY`,groq:`GROQ_API_KEY`,cerebras:`CEREBRAS_API_KEY`,xai:`XAI_API_KEY`,radius:`RADIUS_API_KEY`,openrouter:`OPENROUTER_API_KEY`,"vercel-ai-gateway":`AI_GATEWAY_API_KEY`,zai:`ZAI_API_KEY`,"zai-coding-cn":`ZAI_CODING_CN_API_KEY`,mistral:`MISTRAL_API_KEY`,minimax:`MINIMAX_API_KEY`,"minimax-cn":`MINIMAX_CN_API_KEY`,moonshotai:`MOONSHOT_API_KEY`,"moonshotai-cn":`MOONSHOT_API_KEY`,huggingface:`HF_TOKEN`,fireworks:`FIREWORKS_API_KEY`,together:`TOGETHER_API_KEY`,baseten:`BASETEN_API_KEY`,opencode:`OPENCODE_API_KEY`,"opencode-go":`OPENCODE_API_KEY`,"kimi-coding":`KIMI_API_KEY`,"cloudflare-workers-ai":`CLOUDFLARE_API_KEY`,"cloudflare-ai-gateway":`CLOUDFLARE_API_KEY`,xiaomi:`XIAOMI_API_KEY`,"xiaomi-token-plan-cn":`XIAOMI_TOKEN_PLAN_CN_API_KEY`,"xiaomi-token-plan-ams":`XIAOMI_TOKEN_PLAN_AMS_API_KEY`,"xiaomi-token-plan-sgp":`XIAOMI_TOKEN_PLAN_SGP_API_KEY`});function lJ(e){return cJ[e]??null}function uJ(e,t){let n=lJ(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let dJ=null;function fJ(e){let t=dJ;return dJ=e,t}async function pJ(){if(!dJ)return{};try{return await dJ()??{}}catch{return{}}}function mJ(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-BOfP1pcJ.js`).then(e=>e.t);return uJ(t(),e())}}async function hJ(e,t,n,r,i={}){return await n.fs.exists(e)?gJ(await n.fs.readFile(e),[`node`,e,...t],n,r,{...i,filename:e}):{stdout:``,stderr:`jsh: cannot find script '${e}'\n`,exitCode:127}}async function gJ(e,t,n,r,i={}){let a=i.realmFactory??_J(),o=r?.processManager??bJ()??yJ(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await rJ({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:{...s.kind===`scoop`?{}:await pJ(),...Object.fromEntries(n.env.entries())},cwd:n.cwd,filename:c,stdin:Ja(n.stdin),ctx:n,ppid:r?.getParentPid?.(),syncFsBridgeEnabled:sJ()})}function _J(){return typeof Worker<`u`||typeof document<`u`?IW():MW()}let vJ=null;function yJ(){return vJ||=new ha,vJ}function bJ(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function xJ(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`){for(r++;r<e.length&&e[r]!==`"`;)n+=e[r],r++;r++}else if(i===`'`){for(r++;r<e.length&&e[r]!==`'`;)n+=e[r],r++;r++}else i===`\\`&&r+1<e.length&&e[r+1]===` `?(n+=` `,r+=2):/\s/.test(i)?(n.length>0&&(t.push(n),n=``),r++):(n+=i,r++)}return n.length>0&&t.push(n),t}var SJ=class{aggregator=null;now;explicitSink;scrubLabel;ids=new Map;seq=0;constructor(e={}){this.now=e.now??Date.now,this.explicitSink=e.sink,this.scrubLabel=e.scrubLabel}allocateId(e=`p`){return this.seq+=1,`${e}-${this.seq}`}hasSink(){return this.resolveSink()!==null}setAggregator(e){this.aggregator=e}emit(e){let t=this.aggregator;if(t&&e.id!==t.id)return t.onChild(e),!0;let n=this.resolveSink();if(!n)return e.phase===`end`&&this.ids.delete(e.id),!1;let r=this.ids.get(e.id);if(e.phase===`update`){if(!r)return!1;let t=this.now();return t-r.lastUpdateAt<250?!1:(r.lastUpdateAt=t,this.deliver(r,n,e),!0)}if(e.phase===`start`){let t={lastUpdateAt:-1/0,rawLabel:e.label,label:this.scrubbed(e.label),tail:Promise.resolve()};return this.ids.set(e.id,t),this.deliver(t,n,e),!0}return r?(this.ids.delete(e.id),this.deliver(r,n,e),!0):!1}resolveSink(){if(this.explicitSink)return this.explicitSink;let e=Ft();if(!e)return null;let t=e.onUpdate;return e=>{t({content:[{type:`progress`,progress:e}]})}}scrubbed(e){return this.scrubLabel?CJ(this.scrubLabel,e):e}deliver(e,t,n){n.label!==e.rawLabel&&(e.rawLabel=n.label,e.label=this.scrubbed(n.label));let{label:r}=e;if(typeof r==`string`){let e=wJ(r);t(e===n.label?n:{...n,label:e});return}e.tail=e.tail.then(async()=>{let i=await r;e.label=i,t({...n,label:wJ(i)})})}};async function CJ(e,t){if(!t)return t;try{return await e(t)}catch{return`[label withheld: secret scrub unavailable]`}}function wJ(e,t=80){return e.length>t?`${e.slice(0,t-1)}…`:e}function TJ(e,t){return t.length?`${e} ${t.join(` `)}`:e}function EJ(e){try{let t=new URL(e);return`↓ ${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return`↓ ${e}`}}function DJ(e,t=Date.now){let n=new Map,r=e=>n.get(e)?.[0];return{start(r,i){if(!e.hasSink())return;let a={id:e.allocateId(`net`),label:EJ(r),startedAt:t()},o=n.get(r);o?o.push(a):n.set(r,[a]),e.emit({id:a.id,label:a.label,fraction:i===void 0?void 0:0,done:0,total:i,unit:`bytes`,phase:`start`})},chunk(n,i,a){let o=r(n);if(!o)return;let s,c;if(a!==void 0&&a>0){s=Math.min(1,i/a);let e=t()-o.startedAt;i>0&&(c=Math.max(0,e/i*(a-i)))}e.emit({id:o.id,label:o.label,fraction:s,etaMs:c,done:i,total:a,unit:`bytes`,phase:`update`})},end(t){let r=n.get(t),i=r?.shift();r&&r.length===0&&n.delete(t),i&&e.emit({id:i.id,label:i.label,fraction:1,etaMs:0,unit:`bytes`,phase:`end`})}}}const OJ={timeout:e=>{let t=0;for(;t<e.length&&e[t].startsWith(`-`)&&e[t]!==`--`;)[`-k`,`--kill-after`,`-s`,`--signal`].includes(e[t])&&(t+=1),t+=1;return e[t]===`--`&&(t+=1),t+1},env:e=>{let t=0;for(;t<e.length&&(e[t].startsWith(`-`)||e[t].includes(`=`));)t+=1;return t},nohup:()=>0,nice:e=>{let t=0;for(;t<e.length&&e[t].startsWith(`-`);)t+=1;return t}},kJ=new Set([`xargs`,`watch`,`parallel`,`bash`,`sh`,`eval`,`source`,`.`]);function AJ(e){let t=``;for(let n of e.parts)switch(n.type){case`Literal`:case`SingleQuoted`:case`Escaped`:t+=n.value;break;case`DoubleQuoted`:for(let e of n.parts){if(e.type!==`Literal`&&e.type!==`Escaped`)return null;t+=e.value}break;default:return null}return t}function jJ(e,t){switch(e.type){case`CommandSubstitution`:return HJ(e.body,t);case`DoubleQuoted`:{let n=0;for(let r of e.parts){let e=jJ(r,t);if(e===null)return null;n+=e}return n}case`ProcessSubstitution`:return null;default:return 0}}function MJ(e,t){let n=0;for(let r of e.parts){let e=jJ(r,t);if(e===null)return null;n+=e}return n}function NJ(e,t){let n=0;for(let r of e.assignments){if(!r.value)continue;let e=MJ(r.value,t);if(e===null)return null;n+=e}for(let r of e.args){let e=MJ(r,t);if(e===null)return null;n+=e}if(!e.name)return n;let r=AJ(e.name);if(r===null||kJ.has(r))return null;if(!t.has(r))return n;n+=1;let i=OJ[r];if(i){let r=e.args.map(AJ);if(r.some(e=>e===null))return null;let a=r[i(r)];if(a===void 0)return n;if(kJ.has(a))return null;t.has(a)&&(n+=1)}return n}function PJ(e){let t=typeof e.start==`number`?e.start:Number(e.start),n=typeof e.end==`number`?e.end:Number(e.end);if(!Number.isFinite(t)||!Number.isFinite(n)){let t=String(e.start),n=String(e.end);return t.length!==1||n.length!==1?null:Math.abs(n.charCodeAt(0)-t.charCodeAt(0))+1}let r=Math.abs(e.step??1)||1;return Math.floor(Math.abs(n-t)/r)+1}function FJ(e){if(e.parts.length!==1||e.parts[0].type!==`CommandSubstitution`)return null;let t=e.parts[0].body;if(t.statements.length!==1)return null;let n=t.statements[0];if(n.pipelines.length!==1||n.pipelines[0].commands.length!==1)return null;let r=n.pipelines[0].commands[0];if(r.type!==`SimpleCommand`||!r.name||AJ(r.name)!==`seq`)return null;let i=r.args.map(e=>{let t=AJ(e);return t===null?NaN:Number(t)});if(i.some(e=>!Number.isFinite(e)))return null;let a=1,o=1,s;if(i.length===1)[s]=i;else if(i.length===2)[a,s]=i;else if(i.length===3)[a,o,s]=i;else return null;if(o===0)return null;let c=Math.floor((s-a)/o)+1;return c>0?c:0}function IJ(e){let t=0;for(let n of e){let e=n.type===`Word`?LJ(n.word):PJ(n);if(e===null)return null;t+=e}return t}function LJ(e){let t=FJ(e);if(t!==null)return t;let n=1;for(let t of e.parts)switch(t.type){case`Literal`:case`SingleQuoted`:case`Escaped`:break;case`DoubleQuoted`:if(t.parts.some(e=>e.type!==`Literal`&&e.type!==`Escaped`))return null;break;case`BraceExpansion`:{let e=IJ(t.items);if(e===null)return null;n*=e;break}default:return null}return n}function RJ(e){let t=0;for(let n of e){let e=LJ(n);if(e===null)return null;t+=e}return t}function zJ(e,t){let n=0;for(let r of e){let e=VJ(r,t);if(e===null)return null;n+=e}return n}function BJ(e,t){switch(e.type){case`SimpleCommand`:return NJ(e,t);case`For`:{if(!e.words)return null;let n=RJ(e.words),r=zJ(e.body,t);return n===null||r===null?null:e.words.filter(e=>FJ(e)!==null&&t.has(`seq`)).length+n*r}case`Subshell`:case`Group`:return zJ(e.body,t);case`FunctionDef`:return 0;default:return null}}function VJ(e,t){let n=0;for(let r of e.pipelines)for(let e of r.commands){let r=BJ(e,t);if(r===null)return null;n+=r}return n}function HJ(e,t){return zJ(e.statements,t)}function UJ(e,t){let n=HJ(e,t);return{totalSteps:n!==null&&n>0?n:null}}function WJ(e){return e.split(`
|
|
1665
1665
|
`).map(e=>e.trim()).find(e=>e.length>0&&!e.startsWith(`#`))||`bash`}var GJ=class{plan;emitter;label;now;id;steps=0;startedAt;finished=!1;children=new Map;constructor(e,t,n,r=Date.now){this.plan=e,this.emitter=t,this.label=n,this.now=r,this.id=t.allocateId(`script`),this.startedAt=r(),this.emitter.setAggregator(this),this.publish(`start`)}stepDone(){this.finished||(this.steps+=1,this.publish(`update`))}onChild(e){if(!this.finished){if(e.phase===`end`){this.children.delete(e.id);return}this.children.set(e.id,{fraction:e.fraction,label:e.label}),(e.fraction!==void 0||e.phase===`start`)&&this.publish(`update`)}}end(){this.finished||(this.finished=!0,this.emitter.setAggregator(null),this.emitter.emit({id:this.id,label:this.label,fraction:1,etaMs:0,done:this.steps,total:this.plan.totalSteps??void 0,unit:`iterations`,phase:`end`}))}fraction(){let e=[...this.children.values()].at(-1)?.fraction,t=this.plan.totalSteps;if(t===null)return e;let n=e??0;return Math.min(1,(this.steps+n)/t)}publish(e){let t=this.fraction(),n=this.now()-this.startedAt,r=t!==void 0&&t>0&&t<1?Math.max(0,n/t*(1-t)):t===1?0:void 0,i=[...this.children.values()].at(-1);this.emitter.emit({id:this.id,label:i?`${this.label} · ${i.label}`:this.label,fraction:t,etaMs:r,done:this.steps,total:this.plan.totalSteps??void 0,unit:`iterations`,phase:e})}};const KJ=globalThis.setTimeout.bind(globalThis);function qJ(e){let t=e/1e3;return`sleep ${Number.isInteger(t)?t:t.toFixed(1)}`}function JJ(e,t={}){let n=t.now??Date.now,r=t.setTimeout??KJ,i=t.isAborted??(()=>!1),a=t.label??qJ,o=e=>new Promise(t=>r(t,e));return async t=>{let r=Math.max(0,t),s=e.allocateId(`sleep`),c=a(r),l=n();e.emit({id:s,label:c,fraction:0,etaMs:r,done:0,total:r,unit:`ms`,phase:`start`});try{let t=0;for(;t<r;){if(i())return;if(await o(Math.min(250,r-t)),t=n()-l,t<r){let n=Math.min(1,t/r);e.emit({id:s,label:c,fraction:n,etaMs:Math.max(0,r-t),done:Math.min(t,r),total:r,unit:`ms`,phase:`update`})}}}finally{e.emit({id:s,label:c,fraction:1,etaMs:0,done:r,total:r,unit:`ms`,phase:`end`})}}}const YJ=globalThis.setTimeout.bind(globalThis);function XJ(e){let t=/^(\d+(?:\.\d+)?|\.\d+)([smhd]?)$/.exec(e.trim());return t?Number(t[1])*({"":1e3,s:1e3,m:6e4,h:36e5,d:864e5}[t[2]]??1e3):null}function ZJ(e){let t=0;for(;t<e.length;){let n=e[t];if(n===`--`)return t+1<e.length?t+1:-1;if(!n.startsWith(`-`))return t;[`-k`,`--kill-after`,`-s`,`--signal`].includes(n)&&(t+=1),t+=1}return-1}function QJ(e,t,n={}){let r=n.now??Date.now,i=n.setTimeout??YJ;return{...e,async execute(n,a){let o=ZJ(n),s=o>=0?XJ(n[o]):null;if(!t.hasSink()||s===null||s<=0)return e.execute(n,a);let c=t.allocateId(`timeout`),l=TJ(e.name,n),u=r(),d=!0,f=()=>{if(!d)return;let e=r()-u,n=Math.min(1,e/s);t.emit({id:c,label:l,fraction:n,etaMs:Math.max(0,s-e),done:Math.min(e,s),total:s,unit:`ms`,phase:`update`}),e<s&&i(f,250)};t.emit({id:c,label:l,fraction:0,etaMs:s,done:0,total:s,unit:`ms`,phase:`start`}),i(f,250);try{return await e.execute(n,a)}finally{d=!1,t.emit({id:c,label:l,fraction:1,etaMs:0,done:s,total:s,unit:`ms`,phase:`end`})}}}}const $J=new Set(`sleep,echo,printf,true,false,test,[,cd,pwd,export,unset,set,shift,local,return,break,continue,exit,:,read,let,declare,typeset,readonly,eval,exec,source,.,alias,unalias,type,command,builtin,wait,trap,basename,dirname,seq,expr`.split(`,`));function eY(e,t,n={}){if((n.skip??$J).has(e.name))return e;let r=e.name;return{...e,async execute(n,i){if(!t.hasSink())return e.execute(n,i);let a=t.allocateId(`cmd`),o=TJ(r,n);t.emit({id:a,label:o,phase:`start`});try{return await e.execute(n,i)}finally{t.emit({id:a,label:o,phase:`end`})}}}}function tY(e){return di(`sudo`,e)}async function nY(e,t){let n=e.trim();if(!n||Cee(oi(t.policy,n),t.defaultDisposition??`allow`)!==`require-approval`)return{allowed:!0};let r=await t.broker.requestApproval({kind:`command`,detail:n});if(r.decision===`deny`)return{allowed:!1,message:tY(r)};if(r.decision===`always`){let e=r.pattern?.trim()||n;await t.persistGrant(e)}return{allowed:!0}}const rY={directory:{title:`Mount local directory`,approve:`Select directory`},"usb-device":{title:`Connect USB device`,approve:`Select USB device`},"serial-port":{title:`Connect serial port`,approve:`Select serial port`},"hid-device":{title:`Connect HID device`,approve:`Select HID device`}};function iY(e,t=[],n){let r=rY[e],i=t.length?` data-action-data='${JSON.stringify({filters:t}).replace(/'/g,`'`)}'`:``,a=e===`directory`&&n?`<div class="sprinkle-action-card__meta">Target: ${Di(n)}</div>`:``;return`
|
|
1666
1666
|
<div class="sprinkle-action-card">
|
|
1667
1667
|
<div class="sprinkle-action-card__header">
|
|
@@ -1779,7 +1779,7 @@ Examples:
|
|
|
1779
1779
|
skill list
|
|
1780
1780
|
skill info bluebubbles
|
|
1781
1781
|
skill read bluebubbles
|
|
1782
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
1782
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-DxNa4Xoh.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${HY()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:WY(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
1783
1783
|
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:GY(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
|
|
1784
1784
|
`,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+`
|
|
1785
1785
|
`,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}}})}const JY=[{names:[`--branch`,`-b`],validate:e=>!e.startsWith(`-`)&&T(e),error:`upskill: --branch must be a git ref of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", trailing "/" or ".lock", or shell metacharacters`,apply:(e,t)=>{e.branch=t}},{names:[`--from`],validate:e=>go(e)!==null,error:`upskill: --from requires a GitHub source (owner/repo, owner/repo@branch, or a github.com URL)`,apply:(e,t)=>{e.from=t}},{names:[`--path`,`-p`],validate:e=>b(e),error:`upskill: --path must be a repo-relative sub-path of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", or shell metacharacters`,apply:(e,t)=>{e.path=t}}];function YY(e){let t={skills:[],dryRun:!1,json:!1};for(let n=0;n<e.length;n++){let r=e[n],i=JY.find(e=>e.names.includes(r));if(i){let r=e[++n];if(!r||!i.validate(r))return t.error=i.error,t;i.apply(t,r)}else if(r===`--dry-run`||r===`-n`)t.dryRun=!0;else if(r===`--json`)t.json=!0;else if(r.startsWith(`-`))return t.error=`upskill: unknown option "${r}" for update`,t;else t.skills.push(r)}return t}function XY(e,t){return!e||!t||e.byteLength!==t.byteLength?!1:e.every((e,n)=>e===t[n])}async function ZY(e,t){try{let n=await e.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(String(n))}catch{return}}async function QY(e,t,n,r){let i=await ZY(e,t);return oo(n)?i?{status:`kept-local`,write:!1}:{status:`added`,write:!0}:i?XY(i,r)?{status:`unchanged`,write:!1}:{status:`updated`,write:!0}:{status:`added`,write:!0}}async function $Y(e,t,n,r){let i={changes:[],writes:[],removals:[]};for(let[r,a]of n){let n=`${t}/${r}`,{status:o,write:s}=await QY(e,n,r,a);i.changes.push({path:r,status:o}),s&&i.writes.push({path:n,content:a})}let a=new Set(r.files??[]);for(let r of await io(e,t)){if(n.has(r))continue;let e=a.has(r);i.changes.push({path:r,status:e?`removed`:`kept-local`}),e&&i.removals.push(`${t}/${r}`)}return i.changes.sort((e,t)=>e.path.localeCompare(t.path)),i}async function eX(e,t,n,r,i,a){let o={skill:n,source:`${r.kind}:${r.source}`,ref:i??r.ref,from:r.sha,outcome:`current`,changes:[]},[s,c]=r.source.split(`/`);if(!s||!c)return{...o,outcome:`error`,error:`unusable source "${r.source}"`};let l=(r.path??``).replace(/^\/|\/$/g,``),u=await ro(t),d=await mo(s,c,o.ref,u,!0);if(d&&r.sha===d&&await tX(e,n,r))return{...o,to:d,outcome:`current`,changes:[]};let f=await nX(s,c,l,n,o.ref,t,u);if(`error`in f)return{...o,outcome:`error`,error:f.error};let p=f.files,m=f.path;if(p.size===0)return{...o,outcome:`error`,error:`no files at ${s}/${c}${m?`/${m}`:``} — the skill may have moved or been removed upstream`};let{changes:h,writes:g,removals:_}=await $Y(e,`${to}/${n}`,p,r),v=g.length>0||_.length>0;if(a)return{...o,outcome:v?`updated`:`current`,changes:h};let y=d??r.sha;return v&&await sX(e,{changes:h,writes:g,removals:_}),await bo(e,n,{...r,ref:o.ref,path:m,sha:y,files:[...p.keys()].sort()}),{...o,to:y,outcome:v?`updated`:`current`,changes:h}}async function tX(e,t,n){if(!n.files?.length)return!1;for(let r of n.files)if(!await e.exists(`/workspace/skills/${t}/${r}`))return!1;return!0}async function nX(e,t,n,r,i,a,o){let s=await so(e,t,a,i??`main`);if(s.status===`ok`){let i=Qa(s.files),a=n||rX(i,r);return a===null?{error:`could not find "${r}/SKILL.md" in ${e}/${t} — pass --path <dir> to say where the skill lives`}:{files:oX(i,a),path:a}}try{return{files:aX(iX(await ao(e,t,n,i,o))),path:n}}catch(e){let t=e instanceof Error?e.message:String(e);return{error:`${s.message}; Contents API fallback failed: ${t}`}}}function rX(e,t){let n=[];for(let r of Object.keys(e))r===`SKILL.md`?n.push(``):(r.endsWith(`/${t}/SKILL.md`)||r===`${t}/SKILL.md`)&&n.push(r.slice(0,-9));return n.length===0?null:(n.sort((e,t)=>e.split(`/`).length-t.split(`/`).length||e.localeCompare(t)),n[0])}function iX(e){return new Map([...e].filter(([e])=>$a(e)))}function aX(e){return new Map([...e].sort(([e],[t])=>e.localeCompare(t)))}function oX(e,t){let n=t?`${t}/`:``,r=new Map;for(let[t,i]of Object.entries(e)){if(!t.startsWith(n)||t.endsWith(`/`))continue;let e=t.slice(n.length);$a(e)&&r.set(e,i)}return aX(r)}async function sX(e,t){for(let n of t.writes){let t=n.path.slice(0,n.path.lastIndexOf(`/`));await e.mkdir(t,{recursive:!0}),await e.writeFile(n.path,n.content)}for(let n of t.removals)await e.rm(n).catch(()=>{})}async function cX(e,t,n,r,i){let a={skill:n,source:`${r.kind}:${r.source}`,outcome:`current`,changes:[]},[o,s]=r.source.split(`/`);if(!o||!s)return{...a,outcome:`error`,error:`unusable source "${r.source}"`};let c=await BY(o,s,t);if(!c.ok)return{...a,outcome:`error`,error:c.error};let l=`${to}/${n}/SKILL.md`,u=await ZY(e,l),d=new TextEncoder().encode(c.content),f=u!==void 0&&RY(new TextDecoder().decode(u))===RY(c.content);if(XY(u,d)||f)return{...a,changes:[{path:`SKILL.md`,status:`unchanged`}]};let p=u?`updated`:`added`;return i||(await e.mkdir(`${to}/${n}`,{recursive:!0}),await e.writeFile(l,d),await bo(e,n,{...r,files:[`SKILL.md`]})),{...a,outcome:`updated`,changes:[{path:`SKILL.md`,status:p}]}}function lX(e,t){if(e.outcome===`error`)return` ${e.skill}: failed — ${e.error}\n`;let n=new Map;for(let t of e.changes)n.set(t.status,(n.get(t.status)??0)+1);let r=e.to&&e.to!==e.from?` → ${e.to.slice(0,7)}`:``;if(e.outcome===`current`)return` ${e.skill}: already current (${e.source}${r})\n`;let i=t?`would update`:`updated`,a=` ${e.skill}: ${i} from ${e.source}${r}\n`;for(let t of e.changes)t.status!==`unchanged`&&(a+=` ${t.status.padEnd(10)} ${t.path}\n`);let o=n.get(`kept-local`)??0;return o>0&&(a+=` (${o} kept-local — dotfiles and local additions are never touched)\n`),a}function uX(e,t,n,r){let i=go(t);return i?{version:1,kind:`github`,source:`${i.owner}/${i.repo}`,skill:e,ref:r??i.branch,path:n??i.path,installed:new Date().toISOString()}:null}async function dX(e,t,n){if(t.length===0){let t=await ho(e);return{targets:t.provenanced,missing:[],skipped:t.unattributed}}let r=[],i=[];for(let a of t){let t=await Co(e,a);if(t){r.push({name:a,provenance:t});continue}if(!await e.exists(`/workspace/skills/${a}`)){i.push({name:a,reason:`not-installed`});continue}let o=n.from?uX(a,n.from,n.path,n.branch):null;o?r.push({name:a,provenance:o}):i.push({name:a,reason:`no-provenance`})}return{targets:r,missing:i,skipped:[]}}function fX(e){return e.reason===`not-installed`?`upskill: no skill named "${e.name}" is installed — check \`upskill list\`
|
|
@@ -1812,7 +1812,7 @@ Examples:
|
|
|
1812
1812
|
`,{stdout:s,stderr:``,exitCode:0}}function OX(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
1813
1813
|
`,exitCode:1}:T(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
|
|
1814
1814
|
`,exitCode:1}}function kX(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`||!b(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
|
|
1815
|
-
`,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=OX(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 AX(e){let t=await(await import(`./skills-
|
|
1815
|
+
`,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=OX(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 AX(e){let t=await(await import(`./skills-DxNa4Xoh.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${HY()}`,stderr:``,exitCode:0}:{stdout:WY(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function jX(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-DxNa4Xoh.js`).then(e=>e.t);if(e===`info`){let e=await r.getSkillInfo(n,t);if(!e)return{stdout:``,stderr:`upskill: skill "${t}" not found\n`,exitCode:1};let i=await Co(n,t),a=i?_o(i):"Installed from: (no provenance recorded — reinstall to enable `upskill update`)\n";return{stdout:GY(e)+a,stderr:``,exitCode:0}}let i=await r.readSkillInstructions(n,t);return i===null?{stdout:``,stderr:`upskill: no SKILL.md found for "${t}"\n`,exitCode:1}:{stdout:i+`
|
|
1816
1816
|
`,stderr:``,exitCode:0}}async function MX(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 yo(p.path,p.name,r,i,a,s?{...s,path:p.path}:void 0),h=f+1,g=((Date.now()-o)/1e3).toFixed(1),_=(Date.now()-o)/h,v=h<d?` (~${Math.round((d-h)*_/1e3)}s remaining)`:``;m.ok?(c+=`[${h}/${d}] Installed "${p.name}" from ${t}/${n} (${g}s)${v}\n`,u++):(c+=`[${h}/${d}] Failed "${p.name}": ${m.error}${v}\n`,l+=`upskill: ${m.error}\n`)}return{output:c,errors:l,successCount:u}}async function NX(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 vo(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 PX(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await vo(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 FX(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 IX(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await ro(r),l=await xo(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:FX(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:FX(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 so(i,a,r,o);if(e.status===`ok`){let r=await mo(i,a,o,c),s=await MX(u,i,a,Qa(e.files),n,t.force,f,{kind:`github`,source:`${i}/${a}`,ref:o,sha:r});({output:p,errors:m,successCount:h}=s)}else{let e=await NX(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await PX(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 po()),{stdout:p,stderr:m,exitCode:+!!m}}async function LX(e,t,n,r){switch(e[0]){case`tabs`:return EX(t,n,r,e.includes(`--json`));case`recommendations`:return DX(t,n,e.includes(`--install`));case`update`:case`upgrade`:return gX(e.slice(1),t,n);case`list`:return AX(t);case`info`:case`read`:return jX(e[0],e[1],t);case`search`:return zX(e,n);default:return null}}function RX(e,t,n){return V(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return KY();let a=await LX(r,e,t,n);if(a)return a;let o=kX(r);if(o.earlyReturn)return o.earlyReturn;if(!o.sourceRef)return KY();if(o.sourceRef.startsWith(`tessl:`))return BX(o.sourceRef,o.force,e,t);let s=FY(o.sourceRef);if(s)return VY(s.hostname,s.task,e,t,o.force);let c=go(o.sourceRef);return c?IX(c,o,e,t):{stdout:``,stderr:`upskill: unrecognized source "${o.sourceRef}"\n\nExpected: owner/repo, tessl:<name>, or browse:<hostname>/<task>\n`,exitCode:1}})}async function zX(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?xX(a,t,i):KY()}async function BX(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
1817
1817
|
`,exitCode:1};let a=await vX(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await ro(r);return vo(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function VX(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
1818
1818
|
|
|
@@ -2233,7 +2233,7 @@ Examples:
|
|
|
2233
2233
|
`;for(let n of e)t+=` ${n.id} ${n.name.padEnd(20)} ${n.cron.padEnd(15)}`,n.scoop&&(t+=` -> ${n.scoop}`),n.filter&&(t+=` [filtered]`),t+=` (${n.status})`,n.nextRun&&(t+=` next: ${new Date(n.nextRun).toLocaleString()}`),t+=`
|
|
2234
2234
|
`;return t}async function x1(e,t){let n=H(e.slice(1),{});if(`error`in n)return v1(n.error);if(!t()){let e=await d1();if(!e)return m1(`list`);let t=await e.listCronTasks();return t.length===0?{stdout:`No active cron tasks
|
|
2235
2235
|
`,stderr:``,exitCode:0}:{stdout:b1(t),stderr:``,exitCode:0}}let{ok:r,data:i}=await g1(`GET`,``);if(!r)return{stdout:``,stderr:`crontask: failed to list: ${i.error??`unknown error`}\n`,exitCode:1};let a=i;return a.length===0?{stdout:`No active cron tasks
|
|
2236
|
-
`,stderr:``,exitCode:0}:{stdout:b1(a),stderr:``,exitCode:0}}async function S1(e,t){let n=e[0],r=H(e.slice(1),{});if(`error`in r)return v1(r.error);let i=r.positionals[0];if(!i)return{stdout:``,stderr:`crontask: ${n} requires an ID\n`,exitCode:1};if(!t()){let e=await d1();return e?await e.deleteCronTask(i)?{stdout:`Deleted cron task "${i}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`crontask: task "${i}" not found\n`,exitCode:1}:m1(`delete`)}let{ok:a,status:o,data:s}=await g1(`DELETE`,`/${i}`);return a?{stdout:`Deleted cron task "${i}"\n`,stderr:``,exitCode:0}:o===404?{stdout:``,stderr:`crontask: task "${i}" not found\n`,exitCode:1}:{stdout:``,stderr:`crontask: failed to delete: ${s.error??`unknown error`}\n`,exitCode:1}}function C1(e={}){let t=e.hasLocalNodeServer??(()=>!1);return V(`crontask`,async(e,n)=>{let r=e[0];if(!r||ni(e,{valueFlags:_1}))return h1();try{switch(r){case`create`:return await y1(e,n.env,t);case`list`:return await x1(e,t);case`delete`:case`kill`:return await S1(e,t);default:return{stdout:``,stderr:`crontask: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`crontask: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function w1(e){return V(`curlwright`,async(t,n)=>{let{runCurlwright:r}=await import(`./run-
|
|
2236
|
+
`,stderr:``,exitCode:0}:{stdout:b1(a),stderr:``,exitCode:0}}async function S1(e,t){let n=e[0],r=H(e.slice(1),{});if(`error`in r)return v1(r.error);let i=r.positionals[0];if(!i)return{stdout:``,stderr:`crontask: ${n} requires an ID\n`,exitCode:1};if(!t()){let e=await d1();return e?await e.deleteCronTask(i)?{stdout:`Deleted cron task "${i}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`crontask: task "${i}" not found\n`,exitCode:1}:m1(`delete`)}let{ok:a,status:o,data:s}=await g1(`DELETE`,`/${i}`);return a?{stdout:`Deleted cron task "${i}"\n`,stderr:``,exitCode:0}:o===404?{stdout:``,stderr:`crontask: task "${i}" not found\n`,exitCode:1}:{stdout:``,stderr:`crontask: failed to delete: ${s.error??`unknown error`}\n`,exitCode:1}}function C1(e={}){let t=e.hasLocalNodeServer??(()=>!1);return V(`crontask`,async(e,n)=>{let r=e[0];if(!r||ni(e,{valueFlags:_1}))return h1();try{switch(r){case`create`:return await y1(e,n.env,t);case`list`:return await x1(e,t);case`delete`:case`kill`:return await S1(e,t);default:return{stdout:``,stderr:`crontask: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`crontask: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function w1(e){return V(`curlwright`,async(t,n)=>{let{runCurlwright:r}=await import(`./run-cPelajgY.js`);return r(e,t,n)})}const T1=`slicc-fs`;async function E1(){try{let e=globalThis.indexedDB;if(!e)return!1;let t=e.databases;return typeof t!=`function`||(await t.call(e)).some(e=>e.name===T1)}catch{return!0}}async function D1(){let e=globalThis.indexedDB;return e?new Promise(t=>{let n;try{n=e.deleteDatabase(T1)}catch{t(`error`);return}n.onsuccess=()=>t(`deleted`),n.onerror=()=>t(`error`),n.onblocked=()=>t(`blocked`)}):`error`}async function O1(){if(!await E1())return{kind:`absent`,message:`legacy slicc-fs IDB not present — nothing to clean`};let e=await D1();return e===`deleted`?{kind:`deleted`,message:`legacy slicc-fs IDB deleted`}:e===`blocked`?{kind:`blocked`,message:`legacy slicc-fs IDB delete blocked by another connection — close other tabs and retry`}:{kind:`error`,message:`legacy slicc-fs IDB delete failed`}}function k1(){return`slicc-fs-cleanup — delete the legacy slicc-fs IndexedDB
|
|
2237
2237
|
|
|
2238
2238
|
Usage:
|
|
2239
2239
|
slicc-fs-cleanup Delete the legacy slicc-fs IDB.
|
|
@@ -2725,7 +2725,7 @@ Options:
|
|
|
2725
2725
|
`,stderr:``,exitCode:0}}let a=e.routes.get(r.targetId)??[],o=a.length,s=a.filter(e=>e.pattern!==i);if(e.routes.set(r.targetId,s),s.length===0){let t=e.routeCleanup.get(r.targetId);t&&(t(),e.routeCleanup.delete(r.targetId))}return{stdout:`Removed ${o-s.length} route(s) matching "${i}"\n`,stderr:``,exitCode:0}};async function L4(e,t){if(!t.sessionDirsCreated){for(let t of[`/.playwright`,`/.playwright/snapshots`,`/.playwright/screenshots`])try{await e.mkdir(t,{recursive:!0})}catch(e){if(!Wi(e))throw e}t.sessionDirsCreated=!0}}async function Ule(e,t,n,r){try{return await e.withTab(n,async e=>{let{url:i,title:a,text:o,refToSelector:s,refToBackendNodeId:c,refToFrameId:u}=await l(e),d={url:i,title:a,refToSelector:s,refToBackendNodeId:c,refToFrameId:u,content:o,timestamp:Date.now()};r.snapshots.set(n,d);let f=[`Page URL: ${i}`,`Page Title: ${a}`,``,o].join(`
|
|
2726
2726
|
`),p=`/.playwright/snapshots/page-${Hi(new Date)}.yml`;return await t.writeFile(p,f),p})}catch{return null}}async function Wle(e,t,n){await L4(e,t);let r=new Date().toISOString(),i=`playwright-cli ${n.command}${n.args.length?` `+n.args.join(` `):``}`,a=n.result.exitCode===0?n.result.stdout.trim()||`OK`:`Error: ${n.result.stderr.trim()}`,o=[`### ${i}`,`- **Time**: ${r}`];if(n.tabUrl||n.targetId){let e=n.tabUrl?`${n.tabUrl}${n.targetId?` (targetId: ${n.targetId})`:``}`:`targetId: ${n.targetId}`;o.push(`- **Tab**: ${e}`)}o.push(`- **Result**: ${a}`),n.snapshotPath&&o.push(``,`[Snapshot](${n.snapshotPath})`),o.push(`---`,``);let s=o.join(`
|
|
2727
2727
|
`)+`
|
|
2728
|
-
`,c=`/.playwright/session.md`,l=``;try{let t=await e.readFile(c);l=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await e.writeFile(c,l+s)}function R4(){return import(`./snapshot-features-
|
|
2728
|
+
`,c=`/.playwright/session.md`,l=``;try{let t=await e.readFile(c);l=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await e.writeFile(c,l+s)}function R4(){return import(`./snapshot-features-DqQzJ2V2.js`)}async function Gle(e,t,n,r){let i=await e.getAccessibilityTreeForFrame(r.frameId),a=new Map,o=new Map,s=new Map,l=c(i,a,o,{value:0},``,`f1`);for(let e of a.keys())s.set(e,r.frameId);let u=l.join(`
|
|
2729
2729
|
`);return t.snapshots.set(n,{url:r.url,title:r.name,refToSelector:a,refToBackendNodeId:o,refToFrameId:s,content:u,timestamp:Date.now()}),u}async function Kle(e,t){await e.send(`DOM.enable`),await e.send(`Runtime.enable`);let n=(await e.send(`DOM.resolveNode`,{backendNodeId:t})).object;if(n?.objectId)return(await e.send(`Runtime.callFunctionOn`,{objectId:n.objectId,functionDeclaration:`function() {
|
|
2730
2730
|
this.scrollIntoView({ block: 'center' });
|
|
2731
2731
|
const r = this.getBoundingClientRect();
|
|
@@ -2803,7 +2803,7 @@ Options:
|
|
|
2803
2803
|
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
2804
2804
|
return el.files.length;
|
|
2805
2805
|
})()`,r=await t.send(`Runtime.evaluate`,{expression:n,returnByValue:!0,awaitPromise:!1},e);if(r.exceptionDetails){let e=r.exceptionDetails.exception?.description??r.exceptionDetails.text??`File upload failed`;throw Error(e)}});let f=u.map(e=>e.split(`/`).pop()??e).join(`, `);return{stdout:`Uploaded ${u.length} file(s): ${f}\n`,stderr:``,exitCode:0}}],[`state-save`,tue],[`state-load`,nue],[`console`,_ce],[`requests`,Ole],[`request`,kle],[`request-headers`,Ale],[`request-body`,jle],[`response-headers`,Mle],[`response-body`,Nle],[`mousemove`,$ce],[`mousedown`,ele],[`mouseup`,tle],[`mousewheel`,nle],[`drop`,rle],[`route`,Ble],[`route-list`,Vle],[`unroute`,Hle],[`generate-locator`,Tce],[`highlight`,Ece]]);function _ue(){let e=(qi.string??[]).map(e=>`--${e}`),t=new Set(qi.boolean??[]);for(let[e,n]of Object.entries(qi.alias??{})){let r=[e,...Array.isArray(n)?n:[n]];if(r.some(e=>t.has(e)))for(let e of r)t.add(e)}return{value:e,bool:[...[...t].map(e=>`--${e}`),`--help`,`-h`,`--no-iframes`]}}function vue(e){return e.map(e=>e===`--no-iframes`||e.startsWith(`--no-iframes=`)?e.replace(`--no-iframes`,`--_noiframes`):e)}function yue(e){return{...e,bool:[...e.bool??[],`--_noiframes`],value:[...e.value??[],`--_noiframes`]}}const Y4=2e3;function bue(e,t){if(typeof e.getTabLockStats!=`function`)return;let n=e.getTabLockStats();return t?{totalWaitMs:n.totalWaitMs,tabWaitMs:e.getTabLockStats(t).tabWaitMs}:{totalWaitMs:n.totalWaitMs}}function xue(e,t,n,r){if(!t||typeof e.getTabLockStats!=`function`)return r;let i=e.getTabLockStats(),a=i.totalWaitMs-t.totalWaitMs;if(a<Y4)return r;let o=(a/1e3).toFixed(1),s=n&&t.tabWaitMs!==void 0?e.getTabLockStats(n).tabWaitMs-t.tabWaitMs:0,c=`note: browser bridge contended — lock waits totaled ${o}s while this command ran, ${s>=Y4?`${(s/1e3).toFixed(1)}s of it waiting on this tab (--tab=${n})`:`all of it waiting on the bridge, not on this tab`} (queue depth ${i.queueDepth}). Commands on the same tab serialize; commands on different tabs run in parallel — stagger callers on THIS tab, or give each caller its own tab.
|
|
2806
|
-
`;return{...r,stderr:r.stderr+c}}async function Sue(e,t,n){let r=n instanceof Error?n.message:String(n);return{stdout:``,stderr:`Error: ${(t.tab?await Ji(e,t.tab,n):null)??r}\n`,exitCode:1}}function X4(e,t,n){return{stdout:``,stderr:`${e} ${t}: ${n===void 0?`aborted: the caller stopped waiting for it`:n instanceof Error?n.message:String(n)}\n`,exitCode:130}}async function Cue(e,t,n){let r=gue.get(t);if(!r)return{stdout:``,stderr:`Unknown command: ${t}\nRun "playwright-cli help" for usage.\n`,exitCode:1};let{signal:i}=n;try{let a=await r(n);return i?.aborted?X4(e,t,void 0):a}catch(r){return i?.aborted?X4(e,t,r):await Sue(n.browser,n.flags,r)}}async function wue(e,t,n,r){let i=H(vue(n),yue(r));if(`error`in i)return{answer:{stdout:``,stderr:`${e} ${t}: ${i.error}\n`,exitCode:1}};let a;try{({flags:a}=Ki(n))}catch(n){return{answer:{stdout:``,stderr:`${e} ${t}: ${n instanceof Error?n.message:String(n)}\n`,exitCode:1}}}if(a.help===`true`||a.h===`true`){let{formatSubcommandHelp:n}=await import(`./help-
|
|
2806
|
+
`;return{...r,stderr:r.stderr+c}}async function Sue(e,t,n){let r=n instanceof Error?n.message:String(n);return{stdout:``,stderr:`Error: ${(t.tab?await Ji(e,t.tab,n):null)??r}\n`,exitCode:1}}function X4(e,t,n){return{stdout:``,stderr:`${e} ${t}: ${n===void 0?`aborted: the caller stopped waiting for it`:n instanceof Error?n.message:String(n)}\n`,exitCode:130}}async function Cue(e,t,n){let r=gue.get(t);if(!r)return{stdout:``,stderr:`Unknown command: ${t}\nRun "playwright-cli help" for usage.\n`,exitCode:1};let{signal:i}=n;try{let a=await r(n);return i?.aborted?X4(e,t,void 0):a}catch(r){return i?.aborted?X4(e,t,r):await Sue(n.browser,n.flags,r)}}async function wue(e,t,n,r){let i=H(vue(n),yue(r));if(`error`in i)return{answer:{stdout:``,stderr:`${e} ${t}: ${i.error}\n`,exitCode:1}};let a;try{({flags:a}=Ki(n))}catch(n){return{answer:{stdout:``,stderr:`${e} ${t}: ${n instanceof Error?n.message:String(n)}\n`,exitCode:1}}}if(a.help===`true`||a.h===`true`){let{formatSubcommandHelp:n}=await import(`./help-CDxwLbqk.js`);return{answer:{stdout:n(e,t),stderr:``,exitCode:0}}}let o=null;try{let{validateSubcommandArgs:r}=await import(`./validate-args-BcxRh84E.js`);o=r(e,t,n,i.positionals)}catch{o=null}return o?{answer:{stdout:``,stderr:o,exitCode:1}}:{positional:i.positionals,flags:a}}function Tue(e,t,n){let r=t?Ui(t,n):null,i=_ue();return V(e,async(a,o)=>{if(a.length===0||a[0]===`help`||a[0]===`--help`||a[0]===`-h`){let{formatHelp:t}=await import(`./help-CDxwLbqk.js`);return{stdout:t(e)+`
|
|
2807
2807
|
`,stderr:``,exitCode:0}}let s=a[0],c=a.slice(1),l=await wue(e,s,c,i);if(`answer`in l)return l.answer;let{positional:u,flags:d}=l;if(!t||!r)return{stdout:``,stderr:`${e}: browser APIs are unavailable in this environment\n`,exitCode:1};let f=d.tab??null,p=bue(t,f),m=await Cue(e,s,{browser:t,fs:n,state:r,positional:u,flags:d,scratchDir:WL(o.env),onTab:(e,n)=>t.withTab(e,n,{signal:o.signal}),signal:o.signal}),h=d.tab??null,g=null;ea.has(s)&&m.exitCode===0&&h&&(g=await Ule(t,n,h,r));try{await Wle(n,r,{command:s,args:c,result:m,snapshotPath:g,targetId:h})}catch{}return xue(t,p,f,m)})}const Eue=new Map([[`File operations`,[`ls`,`cat`,`head`,`tail`,`wc`,`touch`,`mkdir`,`rm`,`cp`,`mv`,`ln`,`chmod`,`stat`,`readlink`,`file`,`rmdir`,`rsync`]],[`Text processing`,[`grep`,`sed`,`awk`,`sort`,`uniq`,`cut`,`tr`,`tee`,`diff`,`patch`,`column`,`comm`,`egrep`,`fgrep`,`expand`,`unexpand`,`fold`,`join`,`nl`,`od`,`paste`,`rev`,`split`,`strings`,`tac`]],[`Search`,[`find`,`rg`]],[`Navigation & paths`,[`pwd`,`basename`,`dirname`,`tree`,`du`,`cd`]],[`Archives`,[`zip`,`unzip`,`pdftk`,`pdf`,`gunzip`,`gzip`,`zcat`]],[`Media`,[`convert`,`magick`,`pdftoppm`,`pdftocairo`,`pdftotext`,`ffmpeg`,`ffprobe`,`screencapture`]],[`Audio`,[`say`,`afplay`,`chime`]],[`Environment & shell`,`echo.printf.env.printenv.export.alias.unalias.history.clear.true.false.bash.sh.commands.which.uname.man.host.oauth-token.secret.nuke.models.local-llm.cost.hostname.whoami.id.help.sleep.time.timeout.oauth-domain`.split(`.`)],[`Data processing`,[`xargs`,`jq`,`base64`,`date`,`expr`,`seq`]],[`Hashes`,[`md5sum`,`sha1sum`,`sha256sum`]],[`Network`,[`curl`,`curlwright`,`wget`,`dig`,`websocat`,`html-to-markdown`]],[`Version control`,[`git`]],[`Languages`,[`node`,`python`,`python3`,`sqlite3`]],[`Virtualization`,[`v86`]],[`Build tools`,[`tsc`,`test`,`esbuild`,`biome`]],[`Packages`,[`ipk`,`hf`,`npm`,`i`,`ipx`,`npx`]],[`Skills`,[`skill`,`upskill`]],[`Browser & UI`,[`serve`,`open`,`imgcat`,...Qi,`sprinkle`]],[`Clipboard`,[`pbcopy`,`pbpaste`,`xclip`,`xsel`]],[`Filesystem`,[`mount`,`umount`,`fswatch`]],[`Scoops & agents`,[`agent`,`mcp`,`webhook`,`crontask`]],[`Process`,[`ps`,`kill`,`meminfo`,`uptime`]],[`Shell builtins (limited)`,[...EZ]]]);function Due(e,t=[],n=[]){let r=[],i=new Set(e);for(let e of t)i.delete(e);for(let e of n)i.delete(e);r.push(`Available commands:
|
|
2808
2808
|
`);let a=[];for(let[e,t]of Eue){let n=t.filter(e=>i.has(e));if(n.length>0){r.push(` ${e}:`),r.push(` ${n.join(`, `)}\n`);for(let e of n)i.delete(e)}}for(let e of i)a.push(e);return a.length>0&&(r.push(` Other:`),r.push(` ${a.sort().join(`, `)}\n`)),t.length>0&&(r.push(` User scripts (.jsh):`),r.push(` ${t.sort().join(`, `)}\n`)),n.length>0&&(r.push(` Workflows:`),r.push(` ${n.sort().join(`, `)}\n`)),r.push(`Use '<command> --help' for details on a specific command.`),r.join(`
|
|
2809
2809
|
`)+`
|
|
@@ -3061,7 +3061,7 @@ Common base URLs:
|
|
|
3061
3061
|
`)+`
|
|
3062
3062
|
`,stderr:``,exitCode:0}}function Afe(e,t){let n=t.models.length;return{stdout:[`✓ ${e} (${c6(t.runtime,!1)})`,` Saved ${n} model${n===1?``:`s`} to Settings:`,...l6(t.models)].join(`
|
|
3063
3063
|
`)+`
|
|
3064
|
-
`,stderr:``,exitCode:0}}function jfe(){return V(s6,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Dfe(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./account-store-
|
|
3064
|
+
`,stderr:``,exitCode:0}}function jfe(){return V(s6,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Dfe(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./account-store-BOfP1pcJ.js`).then(e=>e.t),{verifyConnection:a}=await import(`./local-llm-DOoj67px.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(s6);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
3065
3065
|
`,exitCode:1};let c=await a(s,t(s6)??void 0);if(!c.ok)return Ofe(s,c);if(o===`discover`){let e=n(s6)??``;return i(s6,e,s,c.models.join(`, `)),Afe(s,c)}return kfe(s,c)})}function Mfe(){return{stdout:`usage: man <topic>
|
|
3066
3066
|
|
|
3067
3067
|
Fetches documentation for a given topic from sliccy.com.
|
|
@@ -3099,20 +3099,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
3099
3099
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
3100
3100
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
3101
3101
|
short name resolves on the PATH.
|
|
3102
|
-
`);let n=H(e,{});if(`error`in n)return m6(n.error);if(n.positionals.length<2)return p6(`mcp add: expected <url> <name>`);let[r,i]=n.positionals;if(!/^https?:\/\//i.test(r))return p6(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return p6(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
3102
|
+
`);let n=H(e,{});if(`error`in n)return m6(n.error);if(n.positionals.length<2)return p6(`mcp add: expected <url> <name>`);let[r,i]=n.positionals;if(!/^https?:\/\//i.test(r))return p6(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return p6(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-QKk0BB_L.js`).then(e=>e.r);if(await a(i,t.fs))return p6(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-C6Cmi9c4.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 zfe(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>y6(i)}),await l.initialize()}let d=await l.toolsList(),f=await l.appsList(),p=new Date().toISOString();await o(i,{url:r,protocolVersion:l.getNegotiatedProtocolVersion(),tools:d,apps:f,addedAt:p,lastRefreshedAt:p,...u?{auth:u}:{}},t.fs),await ipe(i,t);let m=await S6(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-CSn_GER4.js`);e({name:i,serverUrl:r,auth:u})}return f6([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${d6}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
3103
3103
|
`)+`
|
|
3104
|
-
`)}async function zfe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-
|
|
3105
|
-
`);let n=H(e,{});if(`error`in n)return m6(n.error);let{ensureAllMcpProvidersRegistered:r}=await import(`./provider-
|
|
3104
|
+
`)}async function zfe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-BOfP1pcJ.js`).then(e=>e.t),c=await npe(r.oauthFetchImpl),l=r.oauthLauncher??await b6(),u=await i(e,n,c);u6.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await qee(Rt()),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,scopes:m.scope}),{providerId:h,authorizationServer:u.issuer,clientId:f.clientId,redirectUri:d,scope:m.scope??p,registrationClientUri:f.registrationClientUri}}async function Bfe(e,t){if(ni(e))return f6(`usage: mcp list
|
|
3105
|
+
`);let n=H(e,{});if(`error`in n)return m6(n.error);let{ensureAllMcpProvidersRegistered:r}=await import(`./provider-CSn_GER4.js`);await r();let{listServers:i}=await import(`./store-QKk0BB_L.js`).then(e=>e.r),a=await i(t.fs),o=Object.keys(a).sort();if(o.length===0)return f6("No MCP servers configured. Use `mcp add <url> <name>`.\n");let s=[[`NAME`,`URL`,`AUTH`,`TOOLS`,`APPS`,`ADDED`]];for(let e of o){let t=a[e];s.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 f6(h6(s))}function h6(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(`
|
|
3106
3106
|
`)+`
|
|
3107
3107
|
`}async function Vfe(e,t){if(ni(e))return f6(`usage: mcp search <query>
|
|
3108
3108
|
|
|
3109
3109
|
Case-insensitive substring search across the cached tools of every
|
|
3110
3110
|
registered MCP server. Matches tool name OR description and prints a
|
|
3111
3111
|
table of (server, tool, description, match-field) rows.
|
|
3112
|
-
`);let n=H(e,{});if(`error`in n)return m6(n.error);if(n.positionals.length===0)return p6(`mcp search: expected <query>`);let r=n.positionals[0],i=r.toLowerCase(),{ensureAllMcpProvidersRegistered:a}=await import(`./provider-
|
|
3113
|
-
`);let n=H(e,{});if(`error`in n)return m6(n.error);let r=n.positionals[0];if(!r)return p6(`mcp delete: expected <name>`);let{ensureMcpProviderRegistered:i,removeMcpProvider:a}=await import(`./provider-
|
|
3112
|
+
`);let n=H(e,{});if(`error`in n)return m6(n.error);if(n.positionals.length===0)return p6(`mcp search: expected <query>`);let r=n.positionals[0],i=r.toLowerCase(),{ensureAllMcpProvidersRegistered:a}=await import(`./provider-CSn_GER4.js`);await a();let{listServers:o}=await import(`./store-QKk0BB_L.js`).then(e=>e.r),s=await o(t.fs),c=Object.keys(s).sort();if(c.length===0)return f6("No MCP servers configured. Use `mcp add <url> <name>`.\n");let l=[];for(let e of c){let t=s[e].tools??[];for(let n of t){let t=n.description??``,r=n.name.toLowerCase().includes(i),a=t.toLowerCase().includes(i);if(!r&&!a)continue;let o=r&&a?`name+description`:r?`name`:`description`;l.push({server:e,tool:n.name,description:t,match:o})}}if(l.length===0)return f6(`No tools matched "${r}".\n`);l.sort((e,t)=>e.server===t.server?e.tool.localeCompare(t.tool):e.server.localeCompare(t.server));let u=[[`SERVER`,`TOOL`,`DESCRIPTION`,`MATCH`]];for(let e of l)u.push([e.server,e.tool,Hfe(e.description),e.match]);return f6(h6(u))}function Hfe(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function Ufe(e,t){if(e.length===0||ni(e))return e.length===0?p6(`mcp delete: expected <name>`):f6(`usage: mcp delete <name>
|
|
3113
|
+
`);let n=H(e,{});if(`error`in n)return m6(n.error);let r=n.positionals[0];if(!r)return p6(`mcp delete: expected <name>`);let{ensureMcpProviderRegistered:i,removeMcpProvider:a}=await import(`./provider-CSn_GER4.js`);await i(r);let{deleteServer:o}=await import(`./store-QKk0BB_L.js`).then(e=>e.r),s=await o(r,t.fs);await ape(r,t),await ope(r,t);let c=`mcp:${r}`,l=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./account-store-BOfP1pcJ.js`).then(e=>e.t);t().some(e=>e.providerId===c)&&(await e(c),l=!0)}catch(e){u6.warn(`mcp delete: OAuth removal failed`,{providerId:c,error:e instanceof Error?e.message:String(e)})}let u=a(r);return!s&&!l&&!u?p6(`mcp delete: no server, alias, or account found for "${r}"`):f6([`Removed MCP server "${r}"`,` servers.json: ${s?`removed`:`not present`}`,` alias: cleaned`,` sprinkles: cleaned`,` oauth: ${l?`removed`:`not present`}`,` provider: ${u?`unregistered`:`not registered`}`].join(`
|
|
3114
3114
|
`)+`
|
|
3115
|
-
`)}async function Wfe(e,t){if(e.length===0)return p6(`mcp invoke: expected <name>`);if(ni(e.slice(0,1)))return f6(Kfe());let n=H([e[0]],{});if(`error`in n)return m6(n.error);let r=n.positionals[0];if(!r)return p6(`mcp invoke: expected <name>`);let i=e.slice(1),{ensureMcpProviderRegistered:a}=await import(`./provider-
|
|
3115
|
+
`)}async function Wfe(e,t){if(e.length===0)return p6(`mcp invoke: expected <name>`);if(ni(e.slice(0,1)))return f6(Kfe());let n=H([e[0]],{});if(`error`in n)return m6(n.error);let r=n.positionals[0];if(!r)return p6(`mcp invoke: expected <name>`);let i=e.slice(1),{ensureMcpProviderRegistered:a}=await import(`./provider-CSn_GER4.js`);await a(r);let{getServer:o}=await import(`./store-QKk0BB_L.js`).then(e=>e.r),s=await o(r,t.fs);if(!s)return p6(`mcp invoke: unknown server "${r}" (run \`mcp add <url> ${r}\` first)`);let c=s.tools??[];if(i.length===0||ni(i.slice(0,1)))return f6(qfe(r,s,c));let l=H([i[0]],{});if(`error`in l)return m6(l.error);let u=l.positionals[0];if(!u)return p6(`mcp invoke: expected <tool>`);let d=c.find(e=>e.name===u);if(!d)return p6(`mcp invoke: unknown tool "${u}" on "${r}" (run \`${r}\` to list tools)`);let{timeoutMs:f,remaining:p,warnings:m}=Gfe(i.slice(1));if(ni(p))return f6(Jfe(r,d));let h=Yfe(p,d.inputSchema);if(!h.ok)return p6(`mcp invoke: ${h.error}`);let{McpClient:g}=await import(`./client-C6Cmi9c4.js`).then(e=>e.n),_=new g({url:s.url,fetchImpl:t.fetchImpl,headers:s.headers,getAuthHeader:s.auth?()=>y6(r):void 0,...f===void 0?{}:{timeoutMs:f}});await _.initialize();let v=$fe(await _.toolsCall(u,h.value));return m.length>0&&(v.stderr=m.map(e=>`${e}\n`).join(``)+v.stderr),v}function Gfe(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=g6(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=g6(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 g6(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 Kfe(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
3116
3116
|
|
|
3117
3117
|
mcp invoke <name> List tools on <name>.
|
|
3118
3118
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -3142,7 +3142,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
3142
3142
|
|
|
3143
3143
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
3144
3144
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
3145
|
-
`);let n=H(e,{});if(`error`in n)return m6(n.error);let r=n.positionals[0];if(!r)return p6(`mcp refresh: expected <name>`);let{ensureMcpProviderRegistered:i}=await import(`./provider-
|
|
3145
|
+
`);let n=H(e,{});if(`error`in n)return m6(n.error);let r=n.positionals[0];if(!r)return p6(`mcp refresh: expected <name>`);let{ensureMcpProviderRegistered:i}=await import(`./provider-CSn_GER4.js`);await i(r);let{getServer:a,setServer:o}=await import(`./store-QKk0BB_L.js`).then(e=>e.r),s=await a(r,t.fs);if(!s)return p6(`mcp refresh: unknown server "${r}"`);let{McpClient:c,McpAuthRequiredError:l}=await import(`./client-C6Cmi9c4.js`).then(e=>e.n),u=new c({url:s.url,fetchImpl:t.fetchImpl,headers:s.headers,getAuthHeader:s.auth?()=>y6(r):void 0});try{await u.initialize()}catch(e){if(e instanceof l)return p6(`mcp refresh: server "${r}" returned 401 — token may have expired. Run \`mcp auth ${r}\` to re-authenticate.`);throw e}let d=await u.toolsList(),f=await u.appsList();await o(r,{...s,protocolVersion:u.getNegotiatedProtocolVersion(),tools:d,apps:f,lastRefreshedAt:new Date().toISOString()},t.fs);let p=await S6(r,f,t);return f6(`Refreshed "${r}" — tools: ${d.length}, apps: ${f.length} (${p} sprinkle${p===1?``:`s`})\n`)}async function tpe(e,t){if(ni(e))return f6(`usage: mcp auth <name> [--silent | --interactive]
|
|
3146
3146
|
|
|
3147
3147
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
3148
3148
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -3154,7 +3154,7 @@ Options:
|
|
|
3154
3154
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
3155
3155
|
directly. Use after revoking a refresh token or
|
|
3156
3156
|
when the AS no longer accepts the cached one.
|
|
3157
|
-
`);let n=H(e,{bool:Ffe});if(`error`in n)return m6(n.error);let r=n.positionals[0];if(!r)return p6(`mcp auth: expected <name>`);let i=n.bools.has(`--silent`)||n.bools.has(`-s`),a=n.bools.has(`--interactive`)||n.bools.has(`-i`);if(i&&a)return p6(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
3157
|
+
`);let n=H(e,{bool:Ffe});if(`error`in n)return m6(n.error);let r=n.positionals[0];if(!r)return p6(`mcp auth: expected <name>`);let i=n.bools.has(`--silent`)||n.bools.has(`-s`),a=n.bools.has(`--interactive`)||n.bools.has(`-i`);if(i&&a)return p6(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-CSn_GER4.js`),s=await o(r,{fetchImpl:t.oauthFetchImpl,launcher:t.oauthLauncher}),{getServer:c}=await import(`./store-QKk0BB_L.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return p6(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return p6(`mcp auth: server "${r}" does not use OAuth`);if(!s)return p6(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-Cse0ZxeX.js`).then(e=>e.r),f=d(u);if(!f)return p6(`mcp auth: provider "${u}" is not registered`);if(a)return await v6(r,f,t);if(!f.onSilentRenew)return i?p6(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await v6(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 p6(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);u6.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?f6(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?p6(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await v6(r,f,t)}async function v6(e,t,n){if(!t.onOAuthLogin)return p6(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await b6(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?f6(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):p6(`mcp auth: interactive login for "${e}" did not complete`)}async function y6(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./account-store-BOfP1pcJ.js`).then(e=>e.t),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-Cse0ZxeX.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){u6.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function b6(){let{createOAuthLauncher:e}=await import(`./oauth-service-Bconf2Pz.js`);return e()}async function npe(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-DUC7X0GS.js`).then(e=>e.i),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 x6(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-D-gRojJc.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await import(`./global-db-DJXlpNui.js`).then(e=>e.n);return await t.create({dbName:n})}function rpe(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
3158
3158
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
3159
3159
|
const { promisify } = require('util');
|
|
3160
3160
|
const { exec } = require('child_process');
|
|
@@ -3183,7 +3183,7 @@ try {
|
|
|
3183
3183
|
if (stdout) process.stdout.write(stdout);
|
|
3184
3184
|
if (stderr) process.stderr.write(stderr);
|
|
3185
3185
|
process.exit(exitCode);
|
|
3186
|
-
`}async function ipe(e,t){let n=await x6(t.fs);await n.mkdir(d6,{recursive:!0}),await n.writeFile(`${d6}/${e}.jsh`,rpe(e)),t.scriptCatalog?.invalidateJsh()}async function ape(e,t){let n=await x6(t.fs),r=`${d6}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){u6.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function ope(e,t){let{removeAppSprinkles:n}=await import(`./apps-
|
|
3186
|
+
`}async function ipe(e,t){let n=await x6(t.fs);await n.mkdir(d6,{recursive:!0}),await n.writeFile(`${d6}/${e}.jsh`,rpe(e)),t.scriptCatalog?.invalidateJsh()}async function ape(e,t){let n=await x6(t.fs),r=`${d6}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){u6.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function ope(e,t){let{removeAppSprinkles:n}=await import(`./apps-DgoFisXN.js`);await n(e,t.fs)}async function S6(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-DgoFisXN.js`);return(await r(e,t,n.fs)).length}catch(t){return u6.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}function C6(e){return{stdout:``,stderr:`meminfo: ${e}\n`,exitCode:1}}function w6(e){if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`],n=e,r=`B`;for(let e of t){if(n<1024)break;n/=1024,r=e}return`${n.toFixed(1)} ${r}`}function spe(e){return e.attribution.length===0?`(shared)`:e.attribution.map(e=>{let t=e.container?.src??e.container?.id??e.url??`?`;return e.scope?`${e.scope} ${t}`:t}).join(`, `)}function cpe(){let e=globalThis.performance,t=e?.measureUserAgentSpecificMemory;return t?t.bind(e):null}function lpe(e){if(e[0]===`--help`||e[0]===`-h`||e[0]===`help`)return{help:!0};let t=!1;for(let n of e){if(n!==`--json`)return{error:`unknown option '${n}' — see \`meminfo --help\``};t=!0}return{help:!1,json:t}}function upe(e){let t=[`total: ${w6(e.bytes)}`],n=[...e.breakdown].filter(e=>e.bytes>0).sort((e,t)=>t.bytes-e.bytes);if(n.length>0){t.push(``,`BYTES TYPES ATTRIBUTION`);for(let e of n)t.push(`${w6(e.bytes).padEnd(10)} ${e.types.join(`,`).padEnd(20)} ${spe(e)}`)}return`${t.join(`
|
|
3187
3187
|
`)}\n`}function dpe(e={}){return V(`meminfo`,async t=>{let n=lpe(t);if(`error`in n)return C6(n.error);if(n.help)return{stdout:`meminfo - agent-cluster memory diagnostics
|
|
3188
3188
|
|
|
3189
3189
|
Usage:
|
|
@@ -3210,7 +3210,7 @@ Options:
|
|
|
3210
3210
|
-h, --help Show this help message
|
|
3211
3211
|
`}function bpe(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function k6(e){return`$${e.toFixed(2)}`}const xpe=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function Spe(e){let t=`${e.id} ${e.name??``}`;return!xpe.test(t)}function Cpe(e){let t=e.match(/^(claude-(?:opus|sonnet|haiku))/);if(t)return t[1];let n=e.match(/^(gpt-\d+)(?:\.\d+)?(-[a-z][-a-z]*)?$/);if(n)return n[1]+(n[2]??``);let r=e.match(/^gemini-[\d.]+-(.+)$/);if(r)return`gemini-${r[1]}`;let i=e.match(/^gemini-(\d+)-(.+)$/);if(i)return`gemini-${i[2]}`;let a=e.match(/^grok-[\d.]+-([\w-]+)$/);if(a)return`grok-${a[1]}`;if(e.match(/^(grok)-[\d.]+$/))return`grok`;let o=e.match(/^(o\d+(?:-[a-z]+)?)(?:-\d.*)?$/);if(o)return o[1]}function wpe(e){let t=e.toLowerCase();return t=t.replace(/-\d{8}$/,``),t=t.replace(/-\d{4}$/,``),t=t.replace(/-(preview|latest)$/,``),Cpe(t)??t.replace(/-[\d.]+$/,``)}function Tpe(e){let t=new Map;for(let n of e){let e=wpe(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function Epe(e,t,n,r,i){let a=i?vpe(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 Dpe(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=`${k6(e.cost.input)} / ${k6(e.cost.output)}`,a=`${bpe(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(`
|
|
3212
3212
|
`)+`
|
|
3213
|
-
`}function Ope(e){let t=H(e,{bool:fpe,value:E6});return`error`in t?t:{jsonMode:t.bools.has(`--json`),allMode:t.bools.has(`--all`),allVersions:t.bools.has(`--all-versions`),forceRefresh:t.bools.has(`--refresh`),noBenchmarks:t.bools.has(`--no-benchmarks`),explicitProvider:t.values.get(`--provider`)}}function kpe(e,t,n){if(t.explicitProvider){let n=e.getAvailableProviders();return n.includes(t.explicitProvider)?[t.explicitProvider]:{error:`Unknown provider: ${t.explicitProvider}. Available: ${n.join(`, `)}\n`}}return t.allMode?[...new Set(e.getAccounts().map(e=>e.providerId))]:[n]}function Ape(e,t,n,r,i,a){let o=e.getProviderModels(t).filter(Spe);if(o.length===0)return[];let s=o.map(e=>Epe(e,t,n,r,i)).sort((e,t)=>t.cost.input-e.cost.input);return a||(s=Tpe(s)),s}function jpe(e,t,n,r){let i=`${e}:${t}`,a=`${n}:${r}`;return i===a?`Currently using: ${i}\n`:`Currently using: ${i} (selected ${a} — resolved to a different model)\n`}async function Mpe(e,t){if(ni(e,{valueFlags:E6}))return{stdout:ype(),stderr:``,exitCode:0};let n=Ope(e);if(`error`in n)return D6(`models: ${n.error}`);let r=await import(`./account-store-
|
|
3213
|
+
`}function Ope(e){let t=H(e,{bool:fpe,value:E6});return`error`in t?t:{jsonMode:t.bools.has(`--json`),allMode:t.bools.has(`--all`),allVersions:t.bools.has(`--all-versions`),forceRefresh:t.bools.has(`--refresh`),noBenchmarks:t.bools.has(`--no-benchmarks`),explicitProvider:t.values.get(`--provider`)}}function kpe(e,t,n){if(t.explicitProvider){let n=e.getAvailableProviders();return n.includes(t.explicitProvider)?[t.explicitProvider]:{error:`Unknown provider: ${t.explicitProvider}. Available: ${n.join(`, `)}\n`}}return t.allMode?[...new Set(e.getAccounts().map(e=>e.providerId))]:[n]}function Ape(e,t,n,r,i,a){let o=e.getProviderModels(t).filter(Spe);if(o.length===0)return[];let s=o.map(e=>Epe(e,t,n,r,i)).sort((e,t)=>t.cost.input-e.cost.input);return a||(s=Tpe(s)),s}function jpe(e,t,n,r){let i=`${e}:${t}`,a=`${n}:${r}`;return i===a?`Currently using: ${i}\n`:`Currently using: ${i} (selected ${a} — resolved to a different model)\n`}async function Mpe(e,t){if(ni(e,{valueFlags:E6}))return{stdout:ype(),stderr:``,exitCode:0};let n=Ope(e);if(`error`in n)return D6(`models: ${n.error}`);let r=await import(`./account-store-BOfP1pcJ.js`).then(e=>e.t);if(r.getAccounts().length===0)return D6(`No provider accounts configured. Run the provider settings to add one.
|
|
3214
3214
|
`);let i=r.resolveCurrentModel(),a=i.id,o=i.provider,s=r.getSelectedProvider(),c=r.getSelectedModelId(),l;if(!n.noBenchmarks){let e=await _pe(t,n.forceRefresh);e.length>0&&(l=e)}let u=kpe(r,n,s);if(`error`in u)return D6(u.error);let d=[],f=[];for(let e of u){let t=Ape(r,e,a,o,l,n.allVersions);if(t.length===0){if(!n.allMode)return D6(`No models available for provider ${e}.\n`);continue}if(d.push(...t),!n.jsonMode){let n=r.getProviderConfig(e);f.push(Dpe(n.name,e,t,!!l))}}return n.jsonMode?{stdout:JSON.stringify(d,null,2)+`
|
|
3215
3215
|
`,stderr:``,exitCode:0}:(n.allVersions||f.push(`Showing latest versions only. Use --all-versions to see all.
|
|
3216
3216
|
`),f.push(jpe(o,a,s,c)),{stdout:f.join(`
|
|
@@ -3268,7 +3268,7 @@ Examples:
|
|
|
3268
3268
|
`)}\n`,stderr:``,exitCode:0}}async function Qpe(e,t,n){if(!t||!n)return{stdout:``,stderr:`oauth-domain add: requires <providerId> and <domain>
|
|
3269
3269
|
`,exitCode:1};let r=e.getExtraOAuthDomains(t),i=n.toLowerCase();return r.some(e=>e.toLowerCase()===i)?{stdout:`(${n} already in ${t} extras)\n`,stderr:``,exitCode:0}:(await e.setExtraOAuthDomainsAsync(t,[...r,n]),{stdout:`Added ${n} to ${t}. Reload the page to apply.\n`,stderr:``,exitCode:0})}async function $pe(e,t,n){if(!t||!n)return{stdout:``,stderr:`oauth-domain remove: requires <providerId> and <domain>
|
|
3270
3270
|
`,exitCode:1};let r=e.getExtraOAuthDomains(t),i=n.toLowerCase(),a=r.filter(e=>e.toLowerCase()!==i);return a.length===r.length?{stdout:`(${n} not found in ${t} extras)\n`,stderr:``,exitCode:0}:(await e.setExtraOAuthDomainsAsync(t,a),{stdout:`Removed ${n} from ${t}. Reload the page to apply.\n`,stderr:``,exitCode:0})}async function eme(e,t){return t?(await e.setExtraOAuthDomainsAsync(t,[]),{stdout:`Cleared extra domains for ${t}. Reload the page to apply.\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`oauth-domain clear: requires <providerId>
|
|
3271
|
-
`,exitCode:1}}async function tme(e,t,n,r){switch(t){case`list`:return Zpe(e,n);case`add`:return Qpe(e,n,r);case`remove`:return $pe(e,n,r);case`clear`:return eme(e,n);default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${t}"\n${N6()}`,exitCode:1}}}function nme(){return V(`oauth-domain`,async e=>{if(e.length===0||ni(e))return{stdout:N6(),stderr:``,exitCode:0};let t=H(e);if(`error`in t)return P6(t.error);let[n,r,i]=t.positionals,a=await import(`./account-store-
|
|
3271
|
+
`,exitCode:1}}async function tme(e,t,n,r){switch(t){case`list`:return Zpe(e,n);case`add`:return Qpe(e,n,r);case`remove`:return $pe(e,n,r);case`clear`:return eme(e,n);default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${t}"\n${N6()}`,exitCode:1}}}function nme(){return V(`oauth-domain`,async e=>{if(e.length===0||ni(e))return{stdout:N6(),stderr:``,exitCode:0};let t=H(e);if(`error`in t)return P6(t.error);let[n,r,i]=t.positionals,a=await import(`./account-store-BOfP1pcJ.js`).then(e=>e.t);try{return await tme(a,n,r,i)}catch(e){return P6(e instanceof Error?e.message:String(e))}})}function rme(){return V(`oauth-token`,async(e,t)=>{let{runOAuthToken:n}=await import(`./run-DPmOLroa.js`);return n(e,t)})}const ime=[`--download`,`-d`,`--view`,`-v`],F6=[`--size`],I6={low:256,medium:768,high:1536};function L6(){return{stdout:`usage: open [--download|-d] [--view|-v [--size <spec>]] <url|path> [url|path...]
|
|
3272
3272
|
|
|
3273
3273
|
VFS paths are served in a new browser tab via the preview service worker.
|
|
3274
3274
|
URLs (http/https/etc.) are opened directly in a new tab.
|
|
@@ -3294,7 +3294,7 @@ Examples:
|
|
|
3294
3294
|
`);let i=!1;try{i=(await t.fs.stat(e)).isDirectory}catch{}let a=rP(e,await wa(t.fs,i?e:Pa(e))),o;try{o=await r(a)}catch(e){return B6(`${e instanceof Error?e.message:String(e)}\n`)}return z6(`opened ${e} → ${a}${V6(o)}`)}async function yme(e,t,n,r){if(!Ea(e)&&e.endsWith(`.shtml`)&&t.fs)return mme(e,t,r.sprinkleManager,r.canOpenWindow,r.openExternal);if(!n.view&&!r.canOpenWindow)return B6(`open: browser APIs are unavailable in this environment
|
|
3295
3295
|
`);if(Ea(e))return hme(e,r.canOpenWindow,r.openExternal);let i=t.fs.resolvePath(t.cwd,e);return n.view?gme(e,i,t,n.sizeSpec):n.download?_me(e,i,t,r.hasDom):vme(i,t,r.canOpenWindow,r.openExternal)}function bme(e){return V(`open`,async(t,n)=>{if(t.length===0||ni(t,{valueFlags:F6}))return L6();let r=fme(t);if(`error`in r)return{stdout:``,stderr:`${r.error}\n`,exitCode:1};let{download:i,view:a,sizeSpec:o,targets:s}=r;if(s.length===0)return L6();let c=globalThis.__slicc_sprinkleManager,l=typeof window<`u`&&typeof document<`u`,d=l?null:u(),f={canOpenWindow:!!e||l||!!d,hasDom:l,sprinkleManager:c,openExternal:pme(e,l,d)},p=[];for(let e of s){let t=await yme(e,n,{view:a,download:i,sizeSpec:o},f);if(!t.ok)return t.result;p.push(t.message)}return{stdout:p.join(`
|
|
3296
3296
|
`)+`
|
|
3297
|
-
`,stderr:``,exitCode:0}})}function xme(){return V(`patch`,async(e,t)=>{let{runPatch:n}=await import(`./run
|
|
3297
|
+
`,stderr:``,exitCode:0}})}function xme(){return V(`patch`,async(e,t)=>{let{runPatch:n}=await import(`./run-CdoLZ5WY.js`);return n(e,t)})}function H6(e=`pdftk`){return V(e,async(t,n)=>{let{runPdftk:r}=await import(`./run-ChkY2Agc.js`);return r(e,t,n)})}function Sme(){return{stdout:`usage: pdftoppm [options] <input.pdf> [output-prefix]
|
|
3298
3298
|
|
|
3299
3299
|
Rasterize PDF pages to images. Writes <prefix>-<n>.<ext> per page, where <n>
|
|
3300
3300
|
is zero-padded to the digit width of the last page (out-1.png for a 9-page
|
|
@@ -3354,7 +3354,7 @@ Examples:
|
|
|
3354
3354
|
plugin list
|
|
3355
3355
|
plugin info my-plugin
|
|
3356
3356
|
plugin remove my-plugin
|
|
3357
|
-
`}function Pme(e={}){return V(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return K6(Nme());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await Ime(i,a,e);case`list`:case`ls`:return await Bme(i,e);case`info`:return await Vme(i,e);case`validate`:return await Hme(i,a,e,WL(n?.env));case`remove`:case`rm`:case`delete`:return await Ume(i,e);default:return q6(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return q6(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function Y6(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-
|
|
3357
|
+
`}function Pme(e={}){return V(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return K6(Nme());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await Ime(i,a,e);case`list`:case`ls`:return await Bme(i,e);case`info`:return await Vme(i,e);case`validate`:return await Hme(i,a,e,WL(n?.env));case`remove`:case`rm`:case`delete`:return await Ume(i,e);default:return q6(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return q6(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function Y6(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-D-gRojJc.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await import(`./global-db-DJXlpNui.js`).then(e=>e.n);return t.create({dbName:n})}async function X6(e,t,n){let r=Wme(t,e);if(await n.exists(r))return{kind:`local`,root:r};let{parseGitHubRef:i}=await import(`./github-install-WakGuTn3.js`).then(e=>e.t),a=i(e);if(a){let e=`${a.owner}/${a.repo}${a.branch?`@${a.branch}`:``}${a.path?`/${a.path}`:``}`;return{kind:`github`,ref:{...a,display:e}}}return{kind:`error`,message:`${r} does not exist and "${e}" is not a GitHub reference (owner/repo[@branch] or https://github.com/owner/repo[/tree/branch[/dir]])`}}function Fme(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`-`);return/^\.+$/.test(t)?t.replace(/\./g,`_`):t}function Z6(e){let t=[e.owner,e.repo,...e.path?[e.path]:[]];return`${G6}/${t.map(Fme).join(`--`)}`}async function Q6(e,t,n,r){let{fetchRepoZip:i,stripZipPrefix:a,writeZipFilesToDir:o}=await import(`./github-zip-Cn_DhUkt.js`).then(e=>e.i),s=await i(e.owner,e.repo,r,e.branch);if(s.status===`error`)return`failed to download ${e.display}: ${s.message}`;let c=a(s.files),l=e.path?e.path.replace(/^\/|\/$/g,``)+`/`:``;if(!c[`${l}plugin.json`])return`no plugin.json found at ${e.display} — not an Agent Plugins package`;try{await n.rm(t,{recursive:!0})}catch{}return await n.mkdir(t,{recursive:!0}),(await o(c,l,t,n,!1)).length===0?`no files found at ${e.display}`:null}async function $6(e,t){try{await e.rm(t,{recursive:!0})}catch{}}async function Ime(e,t,n){if(ni(e))return K6(`usage: plugin install <path|repo>
|
|
3358
3358
|
|
|
3359
3359
|
Loads the Agent Plugins package at <path>, or downloads it from a GitHub
|
|
3360
3360
|
reference (owner/repo, owner/repo@branch, or
|
|
@@ -3365,19 +3365,19 @@ mcp.json. On success the plugin is recorded in
|
|
|
3365
3365
|
/workspace/.plugins/plugins.json — its skills then surface through the
|
|
3366
3366
|
standard skills discovery, and each supported streamable-http MCP server
|
|
3367
3367
|
is registered in the MCP store as "<plugin>:<server>".
|
|
3368
|
-
`);let r=J6(`install`,e);if(!(`ok`in r))return r;if(r.positionals.length<1)return q6(`plugin install: expected <path|repo>`);let i=await Y6(n),a=await X6(r.positionals[0],t,i);if(a.kind===`error`)return q6(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return q6(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=Z6(a.ref),s=a.ref.display;let e=await Q6(a.ref,o,i,n.fetch);if(e)return q6(`plugin install: ${e}`)}else o=a.root;let{loadPluginFromDirectory:c}=await import(`./loader-Dw-TPPKt.js`),l=await c(i,o);if(!l.ok)return a.kind===`github`&&await $6(i,o),q6(`plugin install: plugin at ${s??o} was rejected:\n${e8(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-
|
|
3368
|
+
`);let r=J6(`install`,e);if(!(`ok`in r))return r;if(r.positionals.length<1)return q6(`plugin install: expected <path|repo>`);let i=await Y6(n),a=await X6(r.positionals[0],t,i);if(a.kind===`error`)return q6(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return q6(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=Z6(a.ref),s=a.ref.display;let e=await Q6(a.ref,o,i,n.fetch);if(e)return q6(`plugin install: ${e}`)}else o=a.root;let{loadPluginFromDirectory:c}=await import(`./loader-Dw-TPPKt.js`),l=await c(i,o);if(!l.ok)return a.kind===`github`&&await $6(i,o),q6(`plugin install: plugin at ${s??o} was rejected:\n${e8(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-TOhACrgy.js`),m=await f(d,n.fs);if(m&&m.root!==o)return a.kind===`github`&&await $6(i,o),q6(`plugin install: a plugin named "${d}" is already installed from ${m.root} (remove it first)`);let h=await zme(u,n),g=await Rme(d,m?.mcpServerNames,h.registered,n);return await p(d,{root:o,version:u.manifest.version,description:u.manifest.description,installedAt:new Date().toISOString(),mcpServerNames:h.registered,...s?{source:s}:{}},n.fs),K6(Lme(u,h,g,s??o,l.diagnostics))}function Lme(e,t,n,r,i){let a=e.manifest.name,o=t.registered,s=e.mcp.servers.filter(e=>e.status!==`supported`),c=[`Installed agent plugin "${a}"${e.manifest.version?` v${e.manifest.version}`:``} from ${r}`,` skills: ${e.skills.length}${e.skills.length>0?` (${e.skills.map(e=>e.name).join(`, `)})`:``}`,` mcp: ${o.length} registered${o.length>0?` (${o.join(`, `)})`:``}${s.length>0?`, ${s.length} skipped`:``}${n>0?`, ${n} removed from previous install`:``}`];return t.conflicts.length>0&&c.push(` warning: not bridged — MCP server name(s) already in use and not owned by this plugin: ${t.conflicts.join(`, `)} (remove them with \`mcp remove\` first)`),i.length>0&&c.push(`Diagnostics:`,e8(i)),c.join(`
|
|
3369
3369
|
`)+`
|
|
3370
|
-
`}async function Rme(e,t,n,r){let i=(t??[]).filter(e=>!n.includes(e));if(i.length===0)return 0;let{deleteServer:a,getServer:o}=await import(`./store-
|
|
3371
|
-
`);let n=J6(`list`,e);if(!(`ok`in n))return n;let{listInstalledPlugins:r}=await import(`./store-
|
|
3370
|
+
`}async function Rme(e,t,n,r){let i=(t??[]).filter(e=>!n.includes(e));if(i.length===0)return 0;let{deleteServer:a,getServer:o}=await import(`./store-QKk0BB_L.js`).then(e=>e.r),s=0;for(let t of i)(await o(t,r.fs))?.pluginOrigin===e&&await a(t,r.fs)&&(s+=1);return s}async function zme(e,t){let n=e.mcp.servers.filter(e=>e.status===`supported`);if(n.length===0)return{registered:[],conflicts:[]};let{getServer:r,setServer:i}=await import(`./store-QKk0BB_L.js`).then(e=>e.r),{McpClient:a}=await import(`./client-C6Cmi9c4.js`).then(e=>e.n),o=[],s=[];for(let c of n){let n=c.config,l=`${e.manifest.name}:${c.name}`,u=await r(l,t.fs);if(u&&u.pluginOrigin!==e.manifest.name){s.push(l);continue}let d=[];try{let e=new a({url:n.url,headers:n.headers});await e.initialize(),d=await e.toolsList()}catch{}await i(l,{url:n.url,...n.headers?{headers:n.headers}:{},tools:d,addedAt:new Date().toISOString(),pluginOrigin:e.manifest.name},t.fs),o.push(l)}return{registered:o,conflicts:s}}async function Bme(e,t){if(ni(e))return K6(`usage: plugin list
|
|
3371
|
+
`);let n=J6(`list`,e);if(!(`ok`in n))return n;let{listInstalledPlugins:r}=await import(`./store-TOhACrgy.js`),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return K6("No agent plugins installed. Use `plugin install <path>`.\n");let o=[[`NAME`,`VERSION`,`ROOT`,`MCP`]];for(let e of a){let t=i[e];o.push([e,t.version??`-`,t.root,String(t.mcpServerNames?.length??0)])}let s=o[0].map((e,t)=>Math.max(...o.map(e=>e[t].length)));return K6(o.map(e=>e.map((e,t)=>e.padEnd(s[t])).join(` `)).join(`
|
|
3372
3372
|
`)+`
|
|
3373
3373
|
`)}async function Vme(e,t){if(ni(e))return K6(`usage: plugin info <name>
|
|
3374
|
-
`);let n=J6(`info`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return q6(`plugin info: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i}=await import(`./store-
|
|
3374
|
+
`);let n=J6(`info`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return q6(`plugin info: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i}=await import(`./store-TOhACrgy.js`),a=await i(r,t.fs);if(!a)return q6(`plugin info: no installed plugin named "${r}"`);let o=await Y6(t),{loadPluginFromDirectory:s}=await import(`./loader-Dw-TPPKt.js`),c=await s(o,a.root);if(!c.ok)return q6(`plugin info: plugin at ${a.root} no longer loads:\n${e8(c.diagnostics)}`);let{plugin:l}=c,u=l.manifest,d=[`${u.name}${u.version?` v${u.version}`:``}`,...u.description?[` ${u.description}`]:[],` root: ${l.root}`,...u.license?[` license: ${u.license}`]:[],...u.homepage?[` home: ${u.homepage}`]:[],``,`Skills (${l.skills.length}):`,...l.skills.map(e=>` ${e.name} ${e.description}`),``,`MCP servers (${l.mcp.servers.length}):`,...l.mcp.servers.map(e=>e.status===`supported`?` ${e.name} ${e.config.type} ${e.config.url}`:` ${e.name} [skipped: ${e.reason}]`)];return c.diagnostics.length>0&&d.push(``,`Diagnostics:`,e8(c.diagnostics)),K6(d.join(`
|
|
3375
3375
|
`)+`
|
|
3376
3376
|
`)}async function Hme(e,t,n,r){if(ni(e))return K6(`usage: plugin validate <path|repo>
|
|
3377
3377
|
`);let i=J6(`validate`,e);if(!(`ok`in i))return i;if(i.positionals.length<1)return q6(`plugin validate: expected <path|repo>`);let a=await Y6(n),o=await X6(i.positionals[0],t,a);if(o.kind===`error`)return q6(`plugin validate: ${o.message}`);let s,c=null;if(o.kind===`github`){if(!n.fetch)return q6(`plugin validate: GitHub sources are unavailable (no network fetch configured)`);c=`${r}/.plugin-validate/${Z6(o.ref).split(`/`).pop()}`;let e=await Q6(o.ref,c,a,n.fetch);if(e)return q6(`plugin validate: ${e}`);s=c}else s=o.root;let{loadPluginFromDirectory:l}=await import(`./loader-Dw-TPPKt.js`),u;try{u=await l(a,s)}finally{c&&await $6(a,c)}if(!u.ok)return{stdout:``,stderr:`plugin validate: REJECTED\n${e8(u.diagnostics)}\n`,exitCode:1};let{plugin:d}=u,f=d.mcp.servers.filter(e=>e.status===`supported`).length,p=[`plugin validate: OK — "${d.manifest.name}"${d.manifest.version?` v${d.manifest.version}`:``}`,` skills: ${d.skills.length}`,` mcp servers: ${f} supported, ${d.mcp.servers.length-f} skipped (mcp.json ${d.mcp.status})`];return u.diagnostics.length>0&&p.push(`Diagnostics:`,e8(u.diagnostics)),K6(p.join(`
|
|
3378
3378
|
`)+`
|
|
3379
3379
|
`)}async function Ume(e,t){if(ni(e))return K6(`usage: plugin remove <name>
|
|
3380
|
-
`);let n=J6(`remove`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return q6(`plugin remove: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i,deleteInstalledPlugin:a}=await import(`./store-
|
|
3380
|
+
`);let n=J6(`remove`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return q6(`plugin remove: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i,deleteInstalledPlugin:a}=await import(`./store-TOhACrgy.js`),o=await i(r,t.fs);if(!o)return q6(`plugin remove: no installed plugin named "${r}"`);let s=0;if(o.mcpServerNames&&o.mcpServerNames.length>0){let{deleteServer:e,getServer:n}=await import(`./store-QKk0BB_L.js`).then(e=>e.r);for(let i of o.mcpServerNames)(await n(i,t.fs))?.pluginOrigin===r&&await e(i,t.fs)&&(s+=1)}await a(r,t.fs);let c=o.root.startsWith(`${G6}/`);return c&&await $6(await Y6(t),o.root),K6([`Removed agent plugin "${r}"`,` registry: removed`,` mcp servers: ${s} removed`,c?` files: removed (${o.root})`:` files: left in place (${o.root})`].join(`
|
|
3381
3381
|
`)+`
|
|
3382
3382
|
`)}function Wme(e,t){let n=t.startsWith(`/`)?t:`${e.replace(/\/$/,``)}/${t}`,r=[];for(let e of n.split(`/`))e!==``&&e!==`.`&&(e===`..`?r.pop():r.push(e));return`/${r.join(`/`)}`}function e8(e){return e.map(e=>` ${e.level===`error`?`error`:`warn `} [${e.component}] ${e.message}`).join(`
|
|
3383
3383
|
`)}const t8=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],Gme=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],Kme={running:`R`,pending:`S`,exited:`Z`,killed:`K`},qme=[`-a`,`-A`,`-e`,`--all`,`-T`,`--tree`],n8=[`-o`,`--columns`];function Jme(e={}){return V(`ps`,async t=>{if(ni(t,{valueFlags:n8}))return ohe();let n=e.processManager??Yme();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
|
|
@@ -4997,7 +4997,7 @@ pass --wait to block and print the full result.`,Ybe=new Set([`list`,`status`,`s
|
|
|
4997
4997
|
`)}`}}function ySe({name:e,folder:t,model:n,modelProviderId:r,visiblePaths:i,writablePaths:a,workspaceMode:o,allowedCommands:s,thinkingLevel:c,backgroundAfterSeconds:l,parentJid:u,defaultVisibleRoots:d,canCreateChildren:f}){return{name:e,folder:t,trigger:`@${t}`,requiresTrigger:!0,assistantLabel:t,addedAt:new Date().toISOString(),config:{...n?{modelId:n}:{},...n&&r?{modelProviderId:r}:{},...bSe(o,t,d,i,a),workspaceMode:o,...s?{allowedCommands:s}:{},...c?{thinkingLevel:c}:{},...l===void 0?{}:{backgroundAfterSeconds:l},...f===!0?{canCreateChildren:!0}:{}},configSchemaVersion:3,parentJid:u}}function bSe(e,t,n,r,i){let a=`/scoops/${t}/`;return{visiblePaths:r??(e===`private`?[]:n),writablePaths:i??(e===`private`?[a]:[a,`/shared/`])}}async function xSe(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return c9.error(`Auto-feed failed`,{name:n,error:t}),{content:`Scoop "${n}" created as "${r}" but the initial task could not be sent: ${t}. Use feed_scoop to retry.`,isError:!0}}return{content:`Scoop "${n}" created as "${r}" and task sent. It is now working on it.`}}async function SSe(e,t){let{name:n,model:r,prompt:i,visiblePaths:a,writablePaths:o,workspaceMode:s,allowedCommands:c,thinking:l,background_after:u,canCreateChildren:d}=e,f=yn(s);if(!f.ok)return{content:f.error,isError:!0};let p=lSe(l);if(!p.ok)return{content:p.content,isError:p.isError};let m=uSe(u);if(!m.ok)return{content:m.content,isError:!0};let h=dSe(r,t.resolveModelSelection);if(!h.ok)return{content:h.content,isError:h.isError};let g=cSe(n),_=u9(t).find(e=>e.name===n||e.folder===g);if(_)return{content:`A scoop named "${_.name}" (${_.folder}) already exists in your scoops. Use feed_scoop to give it another task, or drop_scoop first.`,isError:!0};let v=On(g,t.getScoops().map(e=>e.folder));try{let e=ySe({name:n,folder:v,model:h.modelId,modelProviderId:h.providerId,visiblePaths:a,writablePaths:o,workspaceMode:f.mode,allowedCommands:c,thinkingLevel:p.level,backgroundAfterSeconds:m.seconds,parentJid:t.scoop.jid,defaultVisibleRoots:zn(Vn(t.scoop)),canCreateChildren:d===!0}),r=await t.onScoopScoop(e);return c9.info(`Scoop created`,{name:n,folder:v}),i&&t.onFeedScoop?xSe(r,i,n,v,t.onFeedScoop):{content:`Scoop "${n}" created as "${v}". Use feed_scoop to give it a task.`}}catch(e){return{content:`Failed to create scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function CSe(e,t){let{scoop_name:n}=e,r=l9(t).find(d9(n));if(r?.jid===t.scoop.jid)return{content:`Cannot drop yourself.`,isError:!0};if(!r)return m9(n,t);try{return await t.onDropScoop(r.jid),c9.info(`Scoop dropped`,{name:r.name,folder:r.folder}),{content:`Scoop "${r.name}" (${r.folder}) has been dropped.`}}catch(e){return{content:`Failed to drop scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function h9(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}function g9(e,t){let n=u9(t).map(e=>e.folder).join(`, `);return{content:`No matching scoops found in your scoops (${t.scoop.folder}). Unknown: ${e.join(`, `)}. Available: ${n||`(none)`}`,isError:!0}}async function wSe(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return h9();let{resolved:r,unknown:i}=f9(n,t);return r.length===0?g9(i,t):(t.onMuteScoops(r.map(e=>e.jid)),c9.info(`Scoops muted`,{names:r.map(e=>e.folder)}),{content:`Muted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`})}function TSe(e,t){if(e.length===0)return[`No stashed completions.`];let n=[``,`Stashed completions:`];for(let r of e){let e=t.get(r.jid)??r.jid;n.push(`--- ${e} ---`),r.notificationPath&&n.push(`VFS path: ${r.notificationPath}`),n.push(r.summary)}return n}async function ESe(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return h9();let{resolved:r,unknown:i}=f9(n,t);if(r.length===0)return g9(i,t);let a=r.map(e=>e.jid),o=new Map(r.map(e=>[e.jid,e.folder])),s=await t.onUnmuteScoops(a);c9.info(`Scoops unmuted`,{names:r.map(e=>e.folder),stashedCount:s.length});let c=[`Unmuted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`];return c.push(...TSe(s,o)),{content:c.join(`
|
|
4998
4998
|
`)}}function DSe(e,t){return!Array.isArray(e)||e.length===0?h9():t!==void 0&&(typeof t!=`number`||!Number.isFinite(t)||t<0)?{content:`timeout_ms must be a non-negative finite number (or omitted).`,isError:!0}:null}function OSe(e,t,n,r){return`scoop_wait scheduled for: ${e}${r===void 0?` (no timeout)`:` (timeout: ${r}ms)`}.${t.length>0?` Unknown (skipped): ${t.join(`, `)}.`:``}${n?` Dropped before schedule (skipped): ${n}.`:``} Continue with other work — a 'scoop-wait' lick will be delivered when all listed scoops complete or the timeout fires.`}async function kSe(e,t){let{scoop_names:n,timeout_ms:r}=e,i=DSe(n,r);if(i)return i;let{resolved:a,unknown:o}=f9(n,t);if(a.length===0)return g9(o,t);let s=a.map(e=>e.jid),c=t.onScheduleScoopWait(s,r),l=new Map(a.map(e=>[e.jid,e.folder])),u=c.scheduled.map(e=>l.get(e)??e).join(`, `),d=c.unknown.map(e=>l.get(e)??e).join(`, `);return c9.info(`Wait scheduled`,{scheduled:c.scheduled.map(e=>l.get(e)??e),droppedAtSchedule:d?d.split(`, `):[],unknownNames:o,timeout_ms:r}),c.scheduled.length===0?{content:`scoop_wait could not be scheduled — every listed scoop was unregistered before the wait could start (dropped: ${d||c.unknown.join(`, `)}).${o.length>0?` Unknown names: ${o.join(`, `)}.`:``}`,isError:!0}:{content:OSe(u,o,d,r)}}function ASe(e,t){return t?e.persisted?`Approved (always) — persisted NOPASSWD rule for ${e.kind??`unknown`} pattern "${e.persistedPattern}" in /scoops/${e.scoopFolder??`<unknown>`}/etc/sudoers.`:e.persistError?`Approved (always) but could NOT persist a rule (${e.persistError}). The current action is allowed; future occurrences will prompt again.`:`Approved (always) — no persistable rule applied for this request.`:`Approved (once) — the current action proceeds; future ones will prompt again.`}async function jSe(e,t){let{lick_id:n,always:r,pattern:i}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};let a=r?{decision:`always`,...i?{pattern:i}:{}}:{decision:`allow`};try{let e=await t.onSudoResolve(n,a);return e.settled?(c9.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:ASe(e,!!r)}):{content:`Lick "${n}" is unknown, already resolved, or timed out.`,isError:!0}}catch(e){return{content:`lick_confirm failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function MSe(e,t){let{lick_id:n}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};try{let e=await t.onSudoResolve(n,{decision:`deny`});return e.settled?(c9.info(`Lick dismissed`,{id:n}),e.message?{content:e.message}:{content:`Denied — the scoop will not run this action.`}):{content:`Lick "${n}" is unknown, already resolved, or timed out.`,isError:!0}}catch(e){return{content:`lick_dismiss failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function NSe(e){let t=e.onListSudoRequests();return t.length===0?{content:`No pending sudo requests.`}:{content:`Pending sudo requests:\n${t.map(t=>{let n=e.getScoops().find(e=>e.jid===t.scoopJid)?.folder??t.scoopJid,r=t.request.suggestedPattern?` (suggested: ${t.request.suggestedPattern})`:``;return`- ${t.id} — ${n} — ${t.request.kind}: ${t.request.detail}${r}`}).join(`
|
|
4999
4999
|
`)}`}}async function PSe(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),c9.info(`Global memory updated`),{content:`Global memory updated successfully.`}}catch(e){return{content:`Failed to update global memory: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function FSe(e){return{name:`send_message`,description:`Send a progress message while still working. Your final output is also sent.`,inputSchema:{type:`object`,properties:{text:{type:`string`,description:`The message text to send`},sender:{type:`string`,description:`Optional sender name/role (e.g., "Researcher"). Defaults to assistant name.`}},required:[`text`]},execute:t=>pSe(t,e)}}function ISe(e){return{name:`sudo_request`,description:`Ask the cone for an explicit sudo escalation before running a sensitive action. Use this when you know up-front that a command, read, or write will be gated and you want a clean approval round-trip instead of letting the gate fire mid-action. Resolves with the cone's decision (allow / always / deny). If your sudoers already grants the subject with NOPASSWD, this resolves allow immediately without prompting the cone. 'always' durably widens your sandbox by appending a NOPASSWD rule to /scoops/<folder>/etc/sudoers. 'deny' (or a timeout / dropped cone) resolves fail-closed.`,inputSchema:{type:`object`,properties:{kind:{type:`string`,enum:[...p9],description:`The kind of sensitive action being requested. command = a shell command; read/write = a VFS path; secret = a credential read. Only command/read/write can be persisted with "always" (no sudoers Secret directive).`},detail:{type:`string`,description:`The concrete subject of the request (e.g., the command line "git push origin main" or the VFS path "/workspace/.git/config"). The cone sees this verbatim.`},suggested_pattern:{type:`string`,description:`Optional pre-filled glob pattern for an "always" grant (e.g., "git push*" for a command or "/workspace/.git/**" for a path). The cone may override this.`}},required:[`kind`,`detail`]},execute:t=>gSe(t,e)}}function LSe(e){return{name:`feed_scoop`,description:`Give a scoop a task. Provide a complete, self-contained prompt — the scoop has no access to your conversation. You'll be notified when it finishes.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Must be a scoop you own — use list_scoops to see them.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`}},required:[`scoop_name`,`prompt`]},execute:t=>_Se(t,e)}}function RSe(e){return{name:`list_scoops`,description:`List the scoops you own (your own subtree). Names from this list are the only ones feed_scoop / drop_scoop / scoop_mute / scoop_unmute / scoop_wait can resolve.`,inputSchema:{type:`object`,properties:{}},execute:()=>vSe(e)}}function zSe(e){return{name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model, a prompt, a workspace isolation mode (private | shared-readonly), and per-scoop sandbox shape (visible/writable paths + command allow-list). If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`},visiblePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ (not write). Pure replace — what you set is what you get. Omit to use the default for workspaceMode: shared-readonly (the default) is YOUR OWN workspace plus the shared skills tree — ["/workspace/"] for the primary cone, ["/cones/<folder>/workspace/", "/workspace/skills/"] for any other; private is []. Prefer omitting it over naming "/workspace/" explicitly, which would point the scoop at a different cone's files. Pass [] for no extra read-only paths. Note: the scoop's writablePaths are always readable too, so a true read-nothing sandbox also requires writablePaths: []. Mounts remain readable in shared-readonly; private does not auto-include them. Trailing slash recommended (e.g. "/shared/data/").`},writablePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ AND WRITE. Pure replace. Omit to use the default ["/scoops/<folder>/", "/shared/"] which gives the scoop its own sandbox plus shared space. Pass [] to block all writes — note that /tmp stays readable and writable regardless, as shared scratch space every scoop gets (so nothing secret belongs there). Trailing slash recommended.`},workspaceMode:{type:`string`,enum:[`private`,`shared-readonly`,`snapshot`,`shared-live`],description:`Workspace isolation mode. Default "shared-readonly" is today's scoop: parent workspace + skills are visible, own sandbox + /shared/ are writable, mounts stay readable. "private" is an isolated sandbox (own /scoops/<folder>/ only — no parent workspace, no implicit /shared/, mounts are NOT auto-visible). "snapshot" and "shared-live" are not implemented and are rejected. Explicit visiblePaths / writablePaths still replace the mode's path defaults.`},allowedCommands:{type:`array`,items:{type:`string`},description:`Shell command allow-list. Omit for unrestricted access to every built-in, custom, and .jsh command (the default). Pass a list of command names to restrict the scoop's shell — e.g. ["echo","cat","grep"] for a read-only text-processing scoop. Pass ["*"] for explicit unrestricted. Applies to pipelines, substitutions, and network commands too.`},thinking:{type:`string`,enum:[...tr],description:`Reasoning / thinking-level for this scoop (pi-ai effort). One of: off, minimal, low, medium, high, xhigh. Omit to inherit the global default ("off"). Non-reasoning models always clamp to "off"; "xhigh" clamps to "high" on models that do not support the max tier.`},background_after:{type:`number`,description:`Seconds this scoop's bash tool waits for a command before detaching it to the background and continuing (default 600). Lower it for a scoop that must never stall on a slow command — nobody can cancel a scoop's turn, and its detached commands report back via a Background Command lick. Use 0 to detach every command immediately.`},canCreateChildren:{type:`boolean`,description:`Explicit nested-delegation grant. When true, the new scoop may create and manage its own children (grandchildren of you). Omit or false (the default) keeps it a leaf. The grant is refused when you do not hold canCreateChildren yourself.`}},required:[`name`]},execute:t=>SSe(t,e)}}function BSe(e){return{name:`drop_scoop`,description:`Remove a scoop and stop its work. The scoop will be unregistered and its context destroyed.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Must be a scoop you own — use list_scoops to see them.`}},required:[`scoop_name`]},execute:t=>CSe(t,e)}}function VSe(e){return{name:`scoop_mute`,description:`Suspend scoop→cone notifications for the given scoops. While muted, a scoop's completion is stashed and will be delivered to the cone when you call scoop_unmute (or scoop_wait which consumes it). Use this when coordinating parallel work so each scoop's completion does not trigger its own cone turn.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to mute (e.g., ["writer-scoop", "reviewer-scoop"]).`}},required:[`scoop_names`]},execute:t=>wSe(t,e)}}function HSe(e){return{name:`scoop_unmute`,description:`Resume scoop→cone notifications for the given scoops. Any completion that landed while a scoop was muted is returned in this tool result (NOT dispatched as a new cone turn), so you can read all stashed summaries in the current turn. Scoops with no stashed completion are simply unmuted.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to unmute (e.g., ["writer-scoop"]).`}},required:[`scoop_names`]},execute:t=>ESe(t,e)}}function USe(e){return{name:`scoop_wait`,description:"Schedule a non-blocking wait for the given scoops. Returns immediately — the cone keeps its turn — and a `scoop-wait` lick is delivered when every listed scoop completes or the optional timeout fires. Use this to coordinate parallel work without freezing the cone: feed several scoops, call scoop_wait, then continue with other work; you'll be woken by the lick with all per-scoop summaries in one shot. Already-completed scoops (including those whose completion arrived while you were processing your previous turn) are folded into the same lick.",inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops YOU own (e.g., ["writer-scoop", "reviewer-scoop"]). Another cone's scoop is not a valid target.`},timeout_ms:{type:`number`,description:"Optional timeout in milliseconds. If any listed scoop has not completed by the deadline, it is reported as timed-out in the eventual `scoop-wait` lick. Omit for no timeout."}},required:[`scoop_names`]},execute:t=>kSe(t,e)}}function WSe(e){return{name:`lick_confirm`,description:`Confirm (approve) a pending actionable lick by its lick_id — currently a scoop sudo escalation raised via sudo_request. With always=true, the orchestrator additionally appends a NOPASSWD <directive> <pattern> rule to the requesting scoop's /scoops/<folder>/etc/sudoers so the same action won't prompt again. always=false (the default) is allow-once.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in the [sudo-request] notification, e.g. "lick-…"). Use list_sudo_requests to see outstanding ids.`},always:{type:`boolean`,description:`If true, persist a NOPASSWD rule into the requesting scoop's per-scoop sudoers so the action won't prompt again. Defaults to false (allow-once).`},pattern:{type:`string`,description:`Optional glob pattern to persist when always=true (e.g., "git push*" or "/workspace/.git/**"). Defaults to the request's suggestedPattern, then to the exact detail. Ignored when always=false.`}},required:[`lick_id`]},execute:t=>jSe(t,e)}}function GSe(e){return{name:`lick_dismiss`,description:`Dismiss a pending actionable lick by its lick_id. For scoop sudo escalation this denies the sensitive action. For llms.txt discovery this silently appends the advertising host to /etc/llmstxtignore.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in a sudo-request or llms.txt discovery notification).`}},required:[`lick_id`]},execute:t=>MSe(t,e)}}function KSe(e){return{name:`list_sudo_requests`,description:`List all pending cone-mediated sudo requests (lick id, requesting scoop, kind, detail). Use to find a lick_id for lick_confirm / lick_dismiss.`,inputSchema:{type:`object`,properties:{}},execute:()=>NSe(e)}}function qSe(e){return{name:`update_global_memory`,description:`Update the global CLAUDE.md memory file that is shared across all scoops. Use this instead of write_file for /shared/CLAUDE.md.`,inputSchema:{type:`object`,properties:{content:{type:`string`,description:`The new content for the global memory file`}},required:[`content`]},execute:t=>PSe(t,e)}}function JSe(e){let t=[],n=dee(e.scoop);return bn(e.scoop)||(t.push(FSe(e)),e.onSudoRequest&&t.push(ISe(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(zSe(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(LSe(e)),t.push(RSe(e)),e.onDropScoop&&t.push(BSe(e)),e.onMuteScoops&&t.push(VSe(e)),e.onUnmuteScoops&&t.push(HSe(e)),e.onScheduleScoopWait&&t.push(USe(e)),e.onSudoResolve&&(t.push(WSe(e)),t.push(GSe(e))),e.onListSudoRequests&&t.push(KSe(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(qSe(e))),t}const YSe=r(`scoop-context`);function XSe(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-g70kqGoB.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function ZSe(e){let{scoop:t,unit:n,callbacks:r}=e,i=JSe({scoop:t,onSendMessage:r.onSendMessage,getScoops:r.getScoops,getScoopTabState:r.getScoopTabState,onFeedScoop:r.onFeedScoop,onScoopScoop:r.onScoopScoop,resolveModelSelection:O,onDropScoop:r.onDropScoop,onMuteScoops:r.onMuteScoops,onUnmuteScoops:r.onUnmuteScoops,onScheduleScoopWait:r.onScheduleScoopWait,onSetGlobalMemory:r.setGlobalMemory,getGlobalMemory:r.getGlobalMemory,onSudoRequest:r.onSudoRequest,onSudoResolve:r.onSudoResolve,onListSudoRequests:r.onListSudoRequests}),a=[...iSe(e.gatedFs),Zxe(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:ft(),fireLick:e=>{let n=globalThis.__slicc_lick_handler;if(!n){YSe.warn(`No lick handler for background bash completion`,{folder:t.folder});return}n(e)}}),...i];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BDaIhclx.js`);a.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let o={scrubToolResult:ft()},s=XSe(e);return e.processManager?It(a,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},o,s):It(a,void 0,o,s)}const _9=r(`scoop-context`);async function QSe(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();_9.info(`Filesystem ready`,{folder:t.folder}),await xie(r,t,n,a);let{shell:o,gatedFs:s,skills:c}=await Ixe({scoop:t,unit:n,fs:r,tmpDir:a,skillsFs:e.skillsFs,getBrowserAPI:i.getBrowserAPI,sudoManager:e.sudoManager,capabilityBroker:e.capabilityBroker,onSudoRequest:i.onSudoRequest,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget()});e.onShellReady(o);let l=await ZSe({getTurnGuestGates:e.getTurnGuestGates,scoop:t,unit:n,callbacks:i,shell:o,fs:r,gatedFs:s,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),onStructuredOutput:e.onStructuredOutput,spawnBashJob:e.spawnBashJob}),{scoopMemory:u,globalMemory:d}=await cie(r,n,()=>i.getGlobalMemory());if(!tw(t))return _9.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let f=uie(t,n),p=rw(t,n,d,u,c),m=await e.sessions.restore(),{streamWithSessionId:h,compactFn:g,getCompactionApiKey:_}=await Cie(f,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>tw(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:(e,t)=>i.onCompactionStateChange?.(e,t),onBeforeCompaction:e.onBeforeCompaction});if(e.isDisposed())return{kind:`abandoned`};let v=jn(t);return{kind:`ready`,agent:yie({model:f,tools:l,systemPrompt:p,messages:m,thinkingLevel:iw(aw()??v.level,f),getApiKey:()=>tw(t)??void 0,transformContext:g,streamFn:h,captureStructuredOutput:t.config?.structuredOutputSchema?e.onStructuredOutput:void 0}),compactFn:g,getCompactionApiKey:_,effortOverride:v.effortOverride,toolCount:l.length}}const v9=r(`scoop-context`);var $Se=class{deps;timer=null;createdAt=0;constructor(e){this.deps=e}get sessionId(){return this.deps.sessionId}get store(){return this.deps.store}async restore(){let e=await this.restoreCanonical();if(e)return e;let t=this.deps.store;if(!t)return[];try{let e=await t.load(this.deps.sessionId);if(e){let t=tn(e.messages);return this.createdAt=e.createdAt,v9.info(`Restored agent session`,{folder:this.deps.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){v9.error(`Failed to restore agent session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),this.deps.onRestoreError(`Conversation history could not be restored. Starting fresh.`)}return[]}async restoreCanonical(){let e=this.deps.canonical;if(!e)return null;let t=null;try{t=await e.store.load(e.identity.key)}catch(e){return v9.warn(`Canonical conversation read failed; falling back to the legacy session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),null}let n=Mi(t);if(n.length===0)return null;let r=tn(n);return t&&(this.createdAt=t.createdAt),v9.info(`Restored conversation from the canonical work-unit record`,{folder:this.deps.folder,messageCount:r.length,droppedOrphans:n.length-r.length}),r}persistNow(e){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let t=this.deps.getMessages()??e??[];if(t.length===0)return;this.persistCanonical(t);let n=this.deps.store;n&&n.save({id:this.deps.sessionId,messages:t,config:{},createdAt:this.createdAt||Date.now(),updatedAt:Date.now()}).catch(e=>{v9.error(`Failed to save agent session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)})})}persistCanonical(e){let t=this.deps.canonical;t&&t.store.syncAgentMessages(t.identity,e,{createdAt:this.createdAt||Date.now()}).catch(e=>{v9.error(`Failed to save the canonical conversation record`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)})})}async clear(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.createdAt=0;let e=this.deps.canonical;e&&await e.store.delete(e.identity.key);try{await this.deps.store?.delete(this.deps.sessionId)}catch(e){v9.warn(`Failed to clear the legacy agent session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)})}}schedule(){this.deps.isDisposed()||!this.deps.store&&!this.deps.canonical||this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.isDisposed()||this.persistNow()},1e3))}};function eCe(e,t){if(!e)return null;let{text:n}=t,r=n.length>200?`${n.slice(0,197)}…`:n;return e.spawn({kind:`scoop-turn`,argv:[`prompt`,r],cwd:t.cwd,owner:t.owner,adoptAbort:t.abortController})}function tCe(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function y9(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const b9=r(`scoop-context`);var nCe=class{deps;constructor(e){this.deps=e}async run(e,t,n,r){let i=null;for(let a=1;a<=3;a++){if(this.deps.isDisposed()||r.aborted)return null;let o=await this.tryAgentPrompt(e,t,n,r);if(!o||this.deps.isDisposed()||r.aborted||(i=o,await this.handleAttemptError(o,a,r)))return null}return i}reportExhausted(e){let t=e.message;b9.error(`Agent error after retries exhausted`,{folder:this.deps.folder,error:t,maxRetries:3}),this.fail(`Scoop "${this.deps.scoopName}" failed after 3 attempts: ${t}`,t)}async tryAgentPrompt(e,t,n,r){this.deps.beginAttempt();try{if(await e.prompt(t,n),this.deps.isDisposed()||r.aborted)return null;let i=this.deps.overflow.pendingRecovery;if(i!==null&&(await i,this.deps.overflow.clearPendingRecovery(i),this.deps.isDisposed()||r.aborted))return null;let a=this.deps.getStreamError();return a?Error(a):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handleAttemptError(e,t,n){let r=e.message;return this.handleStaleAssetError(r)||this.handleNonRetryableError(r)?!0:!await this.handleRetryableError(r,t,n)&&(b9.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:ZC(r)}),!!(t<3&&(await QC(x9(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return Qre(e)?(b9.error(`Non-retryable agent error`,{folder:this.deps.folder,error:e}),this.fail(`Scoop "${this.deps.scoopName}" failed with unrecoverable error: ${e}`,e),!0):!1}handleStaleAssetError(e){return xs(e)?(b9.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),ws(this.deps.isInteractive),this.fail(`Scoop "${this.deps.scoopName}" hit a stale build after a deploy; reloading to recover.`,e),!0):!1}async handleRetryableError(e,t,n){if(!ZC(e)||t>=3)return!1;let r=x9(t);return b9.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await QC(r,n)&&!this.deps.isDisposed()}fail(e,t){XC(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function x9(e){return 1e3*2**(e-1)}function rCe(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){b9.info(`Queueing prompt via ${r.steer?`steer`:`followUp`} while processing`,{folder:r.folder,isProcessing:r.isProcessing,agentIsStreaming:i});let a={role:`user`,content:[{type:`text`,text:t},...n],timestamp:Date.now()};return r.steer?e.steer(a):e.followUp(a),!0}return!1}const S9=r(`scoop-context`);var iCe=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;promptAbortController=null;processManager=null;currentTurnProcess=null;compactFn=null;getCompactionApiKey=null;coneJid;unit;owner;skillsFs=null;sudoManager=null;capabilityBroker=null;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;sessions;runBounds;bashJobs;imageRecovery;overflow;idleCompaction=null;idleCompactionLoading=null;sessionGeneration=0;turnRunner;eventSink={textDelta:e=>{this.didStreamDeltas=!0,this.callbacks.onResponse(e,!0)},toolStart:(e,t,n)=>this.callbacks.onToolStart?.(e,t,n),toolUI:(e,t,n)=>this.callbacks.onToolUI?.(e,t,n),toolUIDone:e=>this.callbacks.onToolUIDone?.(e),toolProgress:(e,t,n)=>this.callbacks.onToolProgress?.(e,t,n),toolResult:(e,t,n,r)=>this.callbacks.onToolEnd?.(e,t,n,r),checkpoint:()=>this.sessions.schedule(),assistantMessageEnd:e=>this.handleAssistantMessageEnd(e),turnStart:()=>this.runBounds.enforceOnTurnStart(),turnCompleted:()=>this.runBounds.recordCompletedTurn(),responseDone:()=>this.callbacks.onResponseDone(),agentEnd:(e,t)=>this.handleAgentEndEvent(e,t)};constructor(e,t,n,r,i,a,o,s,c,l){this.scoop=e,this.unit=Bn(e),this.owner={kind:uee(e),scoopJid:e.jid},this.callbacks=t,this.fs=n,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.capabilityBroker=l??null,this.sessions=new $Se({store:r??null,canonical:c?{store:c,identity:{key:Sr(e),workUnitId:e.jid,workspaceId:xr(e),folder:e.folder,legacyKeys:{agentSessionId:e.jid,chatSessionId:Mn(e)}}}:null,sessionId:e.jid,folder:e.folder,getMessages:()=>this.agent?.state?.messages,isDisposed:()=>this.disposed,onRestoreError:e=>this.callbacks.onError(e)}),this.runBounds=new vie({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new aie({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new oie({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new _ie({getAgent:()=>this.agent,isDisposed:()=>this.disposed,getTurnSignal:()=>this.promptAbortController?.signal,getCompactFn:()=>this.compactFn,getCompactionApiKey:()=>this.getCompactionApiKey?.(),isImageRecoveryActive:()=>this.imageRecovery.isActive,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onExhausted:e=>this.reportExhaustedOverflow(e),setStatus:e=>this.setStatus(e),scoopName:e.name,folder:e.folder}),this.turnRunner=new nCe({isDisposed:()=>this.disposed,overflow:this.overflow,beginAttempt:()=>{this.didStreamDeltas=!1,this.promptStreamErrorMessage=null},getStreamError:()=>this.promptStreamErrorMessage,setStatus:e=>this.setStatus(e),onError:e=>this.callbacks.onError(e),onFatalError:t.onFatalError?e=>this.callbacks.onFatalError?.(e):void 0,isInteractive:this.unit.completion.mode===`interactive`,scoopName:e.name,folder:e.folder})}ownLickTarget(){return Nxe(this.unit,this.scoop,Rn(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return mee(this.callbacks.getScoops(),this.scoop)}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}get isBusy(){return this.isProcessing||(this.agent?.state?.isStreaming??!1)}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);let e=await QSe({scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,callbacks:this.callbacks,sessions:this.sessions,sudoManager:this.sudoManager,capabilityBroker:this.capabilityBroker,processManager:this.processManager,processOwner:this.owner,coneJid:this.coneJid,getTurnPid:()=>this.currentTurnProcess?.pid,getTurnGuestGates:()=>this.turnGuestGates,getLickTarget:()=>this.ownLickTarget(),getTmpDir:()=>this.ownTmpDir(),getEffortOverride:()=>this.activeEffortOverride,isDisposed:()=>this.disposed,onShellReady:e=>{this.shell=e},onStructuredOutput:e=>{this.structuredOutputValue=e,this.structuredOutputCaptured=!0},spawnBashJob:e=>this.bashJobs.spawn(e),onBeforeCompaction:this.unit.parentId===null?(e,t)=>this.snapshotBeforeCompaction(e,t):void 0});if(e.kind===`abandoned`)return;if(e.kind===`deferred`){this.setStatus(`ready`);return}this.compactFn=e.compactFn,this.getCompactionApiKey=e.getCompactionApiKey,this.activeEffortOverride=e.effortOverride,this.agent=e.agent,this.unsubscribe=this.agent.subscribe((e,t)=>this.handleAgentEvent(e,t)),this.setStatus(`ready`),S9.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:e.toolCount})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);S9.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async ensureAgentReady(){return this.agent||(await this.init(),this.agent)?!0:(this.callbacks.onError(fie(this.scoop)),!1)}cleanupPromptState(e,t,n,r){this.runBounds.disarm();let i=this.runBounds.takeExceededNote();i!==null&&this.callbacks.onError(`agent run terminated: ${i}`),(n||r.aborted)&&this.sessions.persistNow(),this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),tCe(this.processManager,t,{lastError:n,aborted:r.aborted}),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}turnGuestGates=[];async prompt(e,t=[],n){if(!await this.ensureAgentReady())return;let r=n?.guestGates??[];if(rCe(this.agent,e,t,{steer:n?.steer??!1,isProcessing:this.isProcessing,folder:this.scoop.folder})){for(let e of r)this.addTurnGuestGate(e);return}this.turnGuestGates=[...r];let i=this.agent;this.promptAbortController?.abort();let a=new AbortController;this.promptAbortController=a;let o=a.signal;this.isProcessing=!0,this.setStatus(`processing`),this.overflow.resetForRun();let s=eCe(this.processManager,{text:e,cwd:this.unit.workspace.root,owner:this.owner,abortController:a});this.currentTurnProcess=s,this.runBounds.arm();let c=null;try{if(c=await this.turnRunner.run(i,e,t,o),c&&!this.disposed&&!o.aborted){this.turnRunner.reportExhausted(c);return}!this.disposed&&!o.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(a,s,c,o)}}addTurnGuestGate(e){let t=JSON.stringify(e);this.turnGuestGates.some(e=>JSON.stringify(e)===t)||this.turnGuestGates.push(e)}stop(){y9(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.idleCompaction?.cancel(),this.isProcessing=!1,this.status!==`error`&&this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}async clearSession(e={}){this.sessionGeneration++,this.idleCompaction?.cancel(),this.clearMessages(),await this.sessions.clear(),await this.settleLiveSnapshot(e.discardLiveSnapshot===!0)}idleCompactionEnabled(){return this.unit.parentId===null&&cs(`compact-on-idle`)}armIdleCompaction(){if(!this.idleCompactionEnabled()){this.idleCompaction?.disarm();return}if(this.idleCompaction){this.idleCompaction.arm();return}this.idleCompactionLoading??=this.loadIdleCompaction(),this.idleCompactionLoading.then(e=>{!this.disposed&&this.status===`ready`&&e.arm()})}async loadIdleCompaction(){let[{IdleCompaction:e},{readIdleCompactionSettings:t}]=await Promise.all([import(`./idle-compaction-B9i1duyd.js`),import(`./idle-compaction-settings-1yyApSsQ.js`)]),n=new e({isEnabled:()=>this.idleCompactionEnabled(),getSettings:t,getAgent:()=>this.agent,isDisposed:()=>this.disposed,isBusy:()=>this.isBusy,getCompactFn:()=>this.compactFn,getCompactionApiKey:()=>this.getCompactionApiKey?.(),estimateTokens:nn,onCompacted:()=>this.sessions.persistNow(),onDiscarded:e=>this.callbacks.onCompactionStateChange?.(`cancelled`,{trigger:`idle`,roundId:e}),folder:this.scoop.folder});return this.idleCompaction=n,n}async snapshotBeforeCompaction(e,t){if(!this.fs||this.disposed)return;let n=this.sessionGeneration,{snapshotLiveSession:r}=await import(`./live-session-snapshot-BZfhzAjg.js`),i=await r({vfs:this.fs,cone:{folder:this.scoop.folder,label:this.scoop.assistantLabel},messages:e,trigger:t,stillValid:()=>!this.disposed&&n===this.sessionGeneration});return i?{transcriptPath:i.transcriptPath}:void 0}async settleLiveSnapshot(e){if(!(this.unit.parentId!==null||!this.fs))try{let{discardLiveSnapshot:t,finalizeLiveSnapshot:n}=await import(`./live-session-snapshot-BZfhzAjg.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){S9.warn(`Live snapshot settle failed (archive stays live)`,{folder:this.scoop.folder,discard:e,error:t instanceof Error?t.message:String(t)})}}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getContextFill(){return die(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=mie(this.agent,this.scoop))}async reloadSkills(){this.agent&&await gie(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){return this.agent?aw()?this.agent.state.thinkingLevel:(this.activeEffortOverride=t,hie(this.agent,e)):`off`}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.sessions.persistNow(),this.disposed=!0,this.idleCompaction?.cancel(),this.runBounds.disarm(),y9(this.processManager,this.currentTurnProcess,`SIGTERM`,this.promptAbortController),this.bashJobs.reapAll(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.compactFn=null,this.getCompactionApiKey=null,this.agent=null,this.shell=null,this.fs=null}handleAgentEvent(e,t){this.disposed||tie(e,this.eventSink,t)}setStatus(e){this.disposed||(this.status=e,e===`ready`?this.armIdleCompaction():this.idleCompaction?.cancel(),this.callbacks.onStatusChange(e))}handleAssistantMessageEnd(e){e.errorMessage||this.overflow.markAssistantSucceeded();let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}handleAgentEndEvent(e,t){this.disposed||t?.aborted||$re(e,{imageRecovery:this.imageRecovery,overflow:this.overflow,isProcessing:()=>this.isProcessing,didStreamDeltas:()=>this.didStreamDeltas,latchStreamError:e=>{this.promptStreamErrorMessage=e},onError:e=>this.callbacks.onError(e),persist:e=>this.sessions.persistNow(e)},t)}reportExhaustedOverflow(e){this.unit.completion.mode===`interactive`?this.callbacks.onError(e):this.callbacks.onFatalError?this.callbacks.onFatalError(e):this.callbacks.onError(e)}};const C9=r(`scoop-lifecycle-manager`);var aCe=class{deps;units=new Map;constructor(e){this.deps=e}getUnit(e){return this.units.get(e)}ensureUnit(e){let t=this.units.get(e);return(!t||t.isClosed)&&(t=new Yre(e,{getScoop:e=>this.deps.getScoops().get(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,[],i),clearIdleTimer:e=>this.deps.idleTimers.clear(e),forgetCompletion:(e,t)=>this.deps.completionService.forgetScoop(e,t),unregister:e=>this.unregister(e)}),this.units.set(e,t)),t}getContexts(){let e=new Map;for(let[t,n]of this.units)n.context&&e.set(t,n.context);return e}getContext(e){return this.units.get(e)?.context??void 0}syncReadGrants(e){for(let t of this.deps.getScoops().values()){if(e!==void 0&&t.folder!==e)continue;let n=this.getContext(t.jid)?.getFS();this.applyPolicyReadGrants(t,n)}}getTab(e){return this.units.get(e)?.tab??void 0}observe(e,t){return this.ensureUnit(e).observe(t)}displayJidFor(e){let t=this.deps.approverFor(e)?.jid;return t&&t!==e?t:void 0}dispatch(e,t,...n){this.units.get(e)?.dispatch(t,...n)}parentOf(e){let t=this.deps.getScoops();return(e.parentJid===null?void 0:t.get(e.parentJid))??Rn(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return _n(t.values(),e)??Rn(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){C9.warn(`Failed to initialize per-scoop sudo policy; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}applyPolicyReadGrants(e,t){if(!(t instanceof vr))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);let n=this.ensureUnit(e);if(n.context){if(n.tab?.status===`error`)C9.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{C9.debug(`Context already exists`,{jid:e});return}}let r=this.deps.getSharedFs();if(!r)throw Error(`Shared filesystem not initialized`);let i=`scoop-${t.folder}-${Date.now()}`,a=Bn(t).policy.filesystem;if(a.kind===`restricted`){let e=yn(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new vr(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:vn(a.mode)});a.kind===`restricted`&&(await this.ensureSudoersLoaded(t),this.applyPolicyReadGrants(t,o));let s=this.buildContextCallbacks(e,t),c=this.rootOf(t)?.jid,l=new iCe(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager(),this.deps.getConversationStore(),this.deps.getCapabilityBroker?.()??void 0);n.attachContext(l,i),await l.init(),n.tab?.status===`initializing`&&n.transition(`ready`)&&(this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{C9.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let u=this.deps.getScoops().get(e);u&&u.parentJid!==null&&this.deps.idleTimers.start(e),C9.info(`Scoop context created`,{jid:e,contextId:i})}async reinitAfterPromote(e){let t=this.units.get(e);if(t?.context){t.disposeContext();try{await this.createTab(e)}catch(n){let r=n instanceof Error?n.message:String(n);C9.warn(`Failed to re-init promoted unit; next prompt will retry`,{jid:e,error:r}),t.disposeContext(),this.markTabError(e,r)}}}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.units.get(e);t&&(t.teardown(),this.units.delete(e),C9.info(`Scoop context destroyed`,{jid:e}))}getTabsMap(){let e=new Map;for(let[t,n]of this.units)n.tab&&e.set(t,n.tab);return e}markTabError(e,t){let n=this.ensureUnit(e);n.transition(`error`,{contextId:n.tab?.contextId??`scoop-error-${e}`,error:t})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let e of this.units.values())e.detachContext()}async destroyAllTabs(){for(let e of Array.from(this.units.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.getTab(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 C9.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.getContext(e);o||=(await this.createTab(e),this.getContext(e));let s=this.units.get(e);if(s?.tab?.status===`initializing`){if(C9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){C9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}o=this.getContext(e)}if(!o||!s){C9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),s.tab&&s.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),C9.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();if(An(e),this.inheritModel(e),e.parentJid!==null){let n=[];for(let r of t.values())r.jid!==e.jid&&n.push(r.folder);let r=On(e.folder,n);r!==e.folder&&(C9.warn(`Scoop folder already taken — registering under a free variant`,{jid:e.jid,requested:e.folder,folder:r}),e.folder=r,e.trigger=`@${r}`,e.assistantLabel=r)}t.set(e.jid,e);try{await this.deps.db.saveScoop(e)}catch(n){throw t.delete(e.jid),n}this.deps.messageRouter.ensureQueue(e.jid),C9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&NC(`spawn`,e.folder)}catch(n){C9.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){C9.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=>{C9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}inheritModel(e){if(In(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?Nn(t):void 0)??CC();n&&Tn(e,n)}async unregister(e){let t=this.deps.getScoops();for(let n of Ln(t.values(),e))await this.unregister(n.jid);let n=t.get(e);if(n&&n.parentJid===null&&Rn(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let 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=>{C9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),n&&this.deps.getConversationStore()?.delete(Sr(n)),this.deps.getSessionStore()?.delete(e).catch(t=>{C9.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.deps.completionService.forgetScoop(e,`unregister`);let a=this.deps.approvalRouter.failScoop(e);if(a>0&&C9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),n&&this.deps.getSudoManager()?.forgetScoopPolicies(n.folder),C9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){C9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}async setModel(e,t){let n=this.deps.getScoops().get(e);if(!n)return!1;let r=n.model;Tn(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return Tn(n,r),this.getContext(e)?.updateModel(),C9.warn(`Failed to persist unit model; rolled back`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}return!0}refreshModels(){let e=this.getContexts();for(let t of e.values())t.updateModel();C9.info(`Models re-resolved on all active contexts`,{contextCount:e.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.getContexts()){let r=this.getTab(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{C9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),C9.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.getContext(e),a=i?i.setThinkingLevel(t,n):null;En(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){C9.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(),{policy:o,completion:s}=Bn(t),c=s.mode!==`interactive`;return{onResponse:(t,i)=>{a().has(e)&&(n.onResponse(e,t,i),this.dispatch(e,`onResponse`,t,i),c&&(i?r.appendResponseChunk(e,t):r.setResponseFull(e,t)))},onResponseDone:()=>{a().has(e)&&(this.units.get(e)?.touch(),n.onResponseDone(e))},onError:r=>{a().has(e)&&(this.units.get(e)?.transition(`error`,{error:r}),NC(`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:t=>{a().has(e)&&(this.units.get(e)?.transition(t),n.onStatusChange(e,t),this.dispatch(e,`onStatusChange`,t),t===`ready`&&this.deps.messageRouter.flushOnIdle(e),t===`ready`&&c&&r.notifyCompletion(e))},onCompactionStateChange:(t,r)=>{n.onCompactionStateChange?.(e,t,r)},onToolStart:(t,r,i)=>{n.onToolStart?.(e,t,r,i)},onToolEnd:(t,r,i,a)=>{n.onToolEnd?.(e,t,r,i,a)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i,this.displayJidFor(e))},onToolUIDone:t=>{n.onToolUIDone?.(e,t,this.displayJidFor(e))},onToolProgress:(t,r,i)=>{n.onToolProgress?.(e,t,r,i)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:o.canManageChildren?e=>this.getTab(e):void 0,onFeedScoop:o.canManageChildren?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:o.canCreateChildren?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return Dn(n,t),await i.registerScoop(n),n}:void 0,onDropScoop:o.canManageChildren?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:o.canManageChildren?e=>i.muteScoops(e):void 0,onUnmuteScoops:o.canManageChildren?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:o.canManageChildren?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:o.canWriteSharedMemory?e=>i.setGlobalMemory(e):void 0,appendConeMemory:o.canWriteSharedMemory?(e,n)=>i.appendConeMemory(e,{...n,memoryPath:Vn(t).memoryPath}):void 0,onSudoRequest:o.approvalAuthority===`user`?void 0:t=>i.enqueueSudoRequest(e,t),approveGuestToolCall:e=>i.approveDirectedOrUser(e),onSudoResolve:o.canResolveApprovals?(n,r)=>i.resolveActionableLick(n,r,bn(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(bn(t)?void 0:e):void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);if(C9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),NC(`error`,r.folder,t),this.units.get(e)?.transition(`error`,{error:t}),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),Bn(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(!i)return;let a={id:`scoop-error-${e}-${Date.now()}`,chatJid:i.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?.(i.jid,a)}catch(e){C9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(a).catch(e=>{C9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const w9=r(`scoop-message-router`);var oCe=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(w9.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){w9.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}`);NC(`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),w9.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);w9.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){w9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){w9.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(w9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){w9.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{w9.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`||t.channel===`bash`||t.channel===`scoop-notify`||t.channel===`scoop-idle`||t.channel===`scoop-wait`;return!e||e.parentJid===null||!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);w9.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);w9.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;n.reported||r<3e5||(n.reported=!0,w9.warn(`Busy lick queue may be starved`,{jid:e,error:`Lick queue remained deferred while scoop was busy for 300s`}),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){w9.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){w9.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){w9.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(w9.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){w9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){w9.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=Mr(Gr(Ir(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){w9.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}: ${$t(e.content,e.attachments)}`).join(`
|
|
5000
|
-
`),l=s.flatMap(e=>en(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=Mr(Gr(Ir(a),o));this.lastAgentTimestamp.set(e,d),await this.deps.db.setState(`lastAgentTs_${e}`,d);let f=s.some(e=>e.steer),p=new Set,m=[];for(let e of s){if(!e.guestGate)continue;let t=JSON.stringify(e.guestGate);p.has(t)||(p.add(t),m.push(e.guestGate))}await this.deps.sendPrompt(e,c,u.senderId,u.senderName,l,{steer:f,...m.length>0?{guestGates:m}:{}})}startMessageLoop(){this.pollInterval||=setInterval(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);w9.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`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,n={}){this.cancelDebounce(e),t&&await t.clearSession(n).catch(t=>{w9.warn(`Failed to clear the durable conversation for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.clearMessagesForScoop(e).catch(t=>{w9.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),w9.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=>{w9.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})}),await Promise.all([...this.deps.getContexts().values()].map(e=>e.clearSession().catch(e=>{w9.warn(`Failed to clear a durable conversation`,{error:e instanceof Error?e.message:String(e)})}))),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(),w9.info(`All messages cleared`)}getQueuedMessageIds(e){return(this.messageQueues.get(e)??[]).map(e=>e.id)}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 T9=r(`orchestrator`),sCe={decision:`deny`};var cCe=class{scoops=new Map;workUnits=new Mv(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new gC({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new qre({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),findParent:e=>this.parentOrDefaultRoot(e),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new KC({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new BC({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findParent:e=>this.parentOrDefaultRoot(e),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 OC({getScoops:()=>this.scoops,findApprover:e=>this.capableApproverOrDefaultRoot(e),getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>Br(e),saveMessage:e=>Nr(e)});lickRegistry=new yC({getConeShell:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},getConeFs:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getFS()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new oCe({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=>Nr(e),deleteMessage:e=>Fr(e),clearMessagesForScoop:e=>Ur(e),clearAllMessages:()=>Vr(),getMessagesSince:(e,t,n)=>zr(e,t,n),setState:(e,t)=>jr(e,t)},isExternalLickChannel:av});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new aCe({getScoops:()=>this.scoops,approverFor:e=>this.ownerRootOrDefault(e),getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getConversationStore:()=>this.conversationStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,getCapabilityBroker:()=>this.capabilityBroker,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>Ar(e),deleteScoop:e=>Hr(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>E(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,n)=>this.resolveActionableLick(e,t,n),approveDirectedOrUser:e=>this.approveDirectedOrUser(e),listPendingSudoRequests:e=>this.listPendingSudoRequests(e)},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}setCapabilityBroker(e){this.capabilityBroker=e}getCapabilityBroker(){return this.capabilityBroker}getProcessManager(){return this.processManager}async initPolicyLayerAndLoadRecords(e,t,n){return wC(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new xb({fs:e,watcher:t,capabilityBroker:this.capabilityBroker,onPolicyReload:e=>{this.lifecycle.syncReadGrants(e),this.approvalRouter.settleGrantedRequests(e)}}),await this.sudoManager.init(),n(),this.llmsTxtIgnorePolicy=new Iy(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new SC(e,t),await this.modelPolicyFile.init(),n(),Kr()),n,{stagePrefix:`orchestrator-init`})}async init(e){await Jr(),this.sharedFs=await wC(e=>_r.create({dbName:`slicc-fs`,onRepairProgress:e}),e),this.sessionStore=new Q_,this.conversationStore=new MS,this.fsWatcher=new gr,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher;let t=await this.initPolicyLayerAndLoadRecords(this.sharedFs,this.fsWatcher,e),n=Object.values(t).find(e=>Cn(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),An(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await Rr(`lastAgentTs_${e.jid}`);r&&this.messageRouter.setLastAgentTimestamp(e.jid,r)}await this.backfillModels(),await this.migrateConversations(e),await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new EC({onTaskRun:async(e,t)=>{T9.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(),T9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let t of this.scoops.values())try{await this.createScoopTab(t.jid)}catch(e){let n=e instanceof Error?e.message:String(e);T9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:t.jid,folder:t.folder,root:t.parentJid===null,error:n}),t.parentJid!==null&&this.lifecycle.markTabError(t.jid,n)}finally{e?.(`scoop-restored:${t.jid}`)}_ee(e=>this.getSessionCostsForCommand(e)),vee(async()=>{let{refreshBudgetWindow:e}=await import(`./budget-usage-source-8V_0_Lud.js`).then(e=>e.t);return e()}),this.unregisterExportService=Cb(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new tv;try{await ES({store:t,units:[...this.scoops.values()],loadAgentSession:async e=>{let t=await this.sessionStore?.load(e);return t?{messages:t.messages,createdAt:t.createdAt}:null},loadChatSession:async e=>{let t=await n.load(e);return t?{messages:t.messages,createdAt:t.createdAt}:null},onProgress:e})}catch(e){T9.warn(`Canonical conversation migration failed; staying on the legacy stores`,{error:e instanceof Error?e.message:String(e)})}}async backfillParent(e,t){if(e.parentJid===void 0){e.parentJid=Cn(e)?null:t??null;try{await Ar(e)}catch(t){T9.warn(`Failed to persist backfilled parentJid; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}async backfillModels(){let e=[...this.scoops.values()].filter(e=>!In(e));if(e.length===0)return;let t=CC(),n=[...e].sort((e,t)=>Number(e.parentJid!==null)-Number(t.parentJid!==null));for(let e of n){let n=e.parentJid?this.scoops.get(e.parentJid):void 0,r=(n?Nn(n):void 0)??t;if(r){Tn(e,r);try{await Ar(e)}catch(t){T9.warn(`Failed to persist backfilled model; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}}migrateScoopConfig(e,t){if(e.parentJid===null)return;let n=e.configSchemaVersion??0;if(!(n>=3)){if(n<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),n<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),n<3){let n=`${Wn.root}/`,r=zn(pee(t,e)),i=e.config?.visiblePaths,a=i?.length===1&&i[0]===n;r[0]!==n&&a&&(e.config={...e.config,visiblePaths:r})}e.configSchemaVersion=3}}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/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}getConversationStore(){return this.conversationStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setUnitRosterProvider?.(()=>this.getScoops().map(e=>({name:e.name,folder:e.folder}))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){return 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)}async approveDirectedOrUser(e){let{runDirectedApproval:t}=await import(`./directed-approval-BdcRpqjJ.js`);return t(e,{scoops:this.scoops,ownerRootOf:e=>this.ownerRootOrDefault(e),enqueue:(e,t,n)=>this.approvalRouter.enqueueSudoRequest(e,t,n),getSharedFs:()=>this.sharedFs,workspaceFor:Vn,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(T9.warn(`Guest approval before SudoManager init — failing closed`),sCe)}})}async enqueueDirectedApproval(e,t){return this.approveDirectedOrUser({...t,approver:e})}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t,n){return this.approvalRouter.resolveSudoRequestAndPersist(e,t,n)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}registerDiscoveryLick(e){return this.lickRegistry.registerDiscovery(e)}async resolveActionableLick(e,t,n){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t,n)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(e){return this.approvalRouter.listPendingSudoRequests(e)}registerScoop(e){return this.lifecycle.register(e)}async persistScoop(e){this.scoops.set(e.jid,e),await Ar(e)}reinitLiveUnit(e){return this.lifecycle.reinitAfterPromote(e)}async rekeyConversation(e,t){await this.conversationStore?.rekey(e,t)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}getScoopTabState(e){return this.lifecycle.getTab(e)}defaultRoot(){return Rn(this.scoops.values())[0]}parentOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return(t?.parentJid?this.scoops.get(t.parentJid):void 0)??this.defaultRoot()}capableApproverOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return Sn(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return _n(this.scoops.values(),t)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}ensureLiveUnit(e){return this.lifecycle.ensureUnit(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await _r.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await dC(this.sharedFs).catch(e=>{T9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new xb({fs:this.sharedFs,watcher:this.fsWatcher,capabilityBroker:this.capabilityBroker,onPolicyReload:e=>{this.lifecycle.syncReadGrants(e),this.approvalRouter.settleGrantedRequests(e)}}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new Iy(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new SC(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),T9.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e,t={}){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e),t)}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)}getQueuedMessageIds(e){return this.messageRouter.getQueuedMessageIds(e)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return Br(e)}sendPrompt(e,t,n,r,i=[],a){return this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}setScoopModel(e,t){return this.lifecycle.setModel(e,t)}refreshModels(){this.lifecycle.refreshModels()}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-CP0rleV0.js`).then(e=>e.r),r=await n(this.sharedFs);return[...t,...r.map(bee)]}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&&T9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.lickManager?.setDiscoveryIgnore?.(null),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=null,this.modelPolicyFile?.dispose(),this.modelPolicyFile=null,this.sudoManager?.dispose(),this.sudoManager=null,this.unregisterExportService?.(),this.unregisterExportService=null,T9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new tv,t=this.sharedFs;return new Kx({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:dS(),snapshotStore:{read:e=>rS(t,e),write:(e,n)=>nS(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.141.0`})}};const E9=r(`workflow-run-manager`),D9=`/shared/workflow-runs`,O9=1e3;function lCe(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function uCe(e){let t=new Map,n=new Map,r=e=>{let r=t.get(e);if(r)for(let t of n.get(e)??[])try{t(r)}catch(e){E9.warn(`observeRun handler threw`,e)}},i=(e,n)=>hCe(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=lCe(e,a.parentJid),d={id:c,name:a.name,source:a.source,origin:u.origin,lickTarget:u.lickTarget,status:`running`,currentPhase:null,agentsStarted:0,agentsDone:0,logs:[],startedAt:new Date().toISOString(),finishedAt:null,resultPath:null,preview:null,error:null,pid:null};t.set(c,d),pCe(t,n);let f=i(a.ctx,c),p=mCe(e.processManager,d,c,()=>r(c));return e.runRealm(a.code,[`workflow`,a.filename,c],f).then(e=>o(c,l,e)).catch(e=>s(c,e instanceof Error?e.message:String(e))).finally(()=>p()).catch(e=>E9.warn(`workflow run lifecycle error`,e)),{runId:c}}async function o(t,n,r){let{result:i,hadResult:a}=e.splitResult(r.stdout,n);return r.exitCode===137?c(t,`killed`,null,r.stderr||`killed (SIGKILL)`):r.exitCode!==0||!a?c(t,`error`,null,r.stderr||(a?`exit ${r.exitCode}`:`script produced no result`)):c(t,`done`,i,null)}function s(e,t){return c(e,`error`,null,t)}async function c(n,i,a,o){let s=t.get(n);if(!s||s.status!==`running`&&s.status!==`paused`)return;let c=`${D9}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(D9,{recursive:!0}),await e.sharedFs.writeFile(c,JSON.stringify({name:s.name,status:i,result:i===`done`?a:null,error:o,logs:s.logs,startedAt:s.startedAt,finishedAt:u},null,2)),s.resultPath=c}catch(e){let t=e instanceof Error?e.message:String(e);E9.error(`failed to write run result file`,{runId:n,resultPath:c,error:t}),o=`result file write failed: ${t}`,i===`done`&&(i=`error`)}s.status=i,s.error=o,s.finishedAt=u,s.preview=i===`done`?fCe(a):o??``,r(n),l(s)}function l(t){t.origin===`cone`&&e.fireLick({type:`workflow`,targetScoop:t.lickTarget,workflowRunId:t.id,workflowName:t.name??void 0,resultPath:t.resultPath??void 0,preview:t.preview??t.error??void 0,timestamp:new Date().toISOString(),body:{runId:t.id,status:t.status,error:t.error}})}return{start:a,getRun:e=>t.get(e)??null,listRuns:()=>Array.from(t.values()),observeRun(e,r){let i=n.get(e);i||(i=new Set,n.set(e,i)),i.add(r);let a=t.get(e);if(a)try{r(a)}catch(e){E9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function dCe(e){let t=uCe(e);return globalThis[E7]=t,E9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function fCe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function pCe(e,t,n=100){if(e.size<=n)return;let r=[...e.values()].filter(e=>e.status!==`running`&&e.status!==`paused`).sort((e,t)=>(e.finishedAt??e.startedAt).localeCompare(t.finishedAt??t.startedAt)),i=e.size-n;for(let n of r){if(i<=0)break;e.delete(n.id),t.delete(n.id),i--}}function mCe(e,t,n,r){let i=e.on(`spawn`,e=>{t.pid===null&&e.argv.includes(n)&&(t.pid=e.pid,r(),i())});return i}function hCe(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?gCe(n,t,a?.args??[],r):e===`agent`?_Ce(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function gCe(e,t,n,r){let i=e.get(t);if(i&&i.status===`running`){let[e,t=``]=n;e===`phase`?(i.currentPhase=t,i.logs.push(t)):e===`log`&&i.logs.push(t),i.logs.length>O9&&i.logs.splice(0,i.logs.length-O9),r()}return{stdout:``,stderr:``,exitCode:0}}async function _Ce(e,t,n,r){let i=e.get(t);i&&i.status===`running`&&(i.agentsStarted++,r());try{return await n()}finally{let n=e.get(t);n&&n.status===`running`&&(n.agentsDone++,r())}}const vCe=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function yCe(e,t,n){let r=bCe(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=xCe(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function bCe(e){let t=new Map;return k9(t,e.discoveryOrigin),k9(t,e.discoveryUrl),[...t.values()]}function k9(e,t){if(t){A9(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);A9(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!vCe.has(e)))A9(e,t,1,`substring`)}catch{}}}function A9(e,t,n,r){if(t.length===0)return;let i=`${r}:${t}`,a=e.get(i);(!a||n>a.weight)&&e.set(i,{text:t,weight:n,match:r})}function xCe(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=CCe(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)SCe(a,e)&&(r+=e.weight*o)}return r}function SCe(e,t){if(t.match===`substring`)return e.includes(t.text);let n=t.text.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(^|[^a-z0-9.-])(?:www\\.)?${n}($|[^a-z0-9.-])`).test(e)}function CCe(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}var wCe=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=N9(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)),t.push({name:M9,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===M9)throw new rr(`ENOTDIR`,`not a directory`,e);let n=P9(t[0]);if(n===null||!this.pidExists(n))throw new rr(`ENOENT`,`no such file or directory`,e);return j9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new rr(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=N9(e);if(t.length===1&&t[0]===M9)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new rr(`EISDIR`,`is a directory`,e);let n=P9(t[0]);if(n===null||!this.pidExists(n))throw new rr(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!j9.includes(r))throw new rr(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new rr(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=N9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===M9)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=P9(t[0]);if(n===null||!this.pidExists(n))throw new rr(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=P9(t[0]);if(n===null||!this.pidExists(n))throw new rr(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!j9.includes(r))throw new rr(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new rr(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new rr(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new rr(`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 rr(`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}renderTable(){let e={stats:this.pm.stats(),processes:this.pm.list().map(e=>({pid:e.pid,ppid:e.ppid,kind:e.kind,state:F9(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:I9(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
5000
|
+
`),l=s.flatMap(e=>en(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=Mr(Gr(Ir(a),o));this.lastAgentTimestamp.set(e,d),await this.deps.db.setState(`lastAgentTs_${e}`,d);let f=s.some(e=>e.steer),p=new Set,m=[];for(let e of s){if(!e.guestGate)continue;let t=JSON.stringify(e.guestGate);p.has(t)||(p.add(t),m.push(e.guestGate))}await this.deps.sendPrompt(e,c,u.senderId,u.senderName,l,{steer:f,...m.length>0?{guestGates:m}:{}})}startMessageLoop(){this.pollInterval||=setInterval(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);w9.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`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,n={}){this.cancelDebounce(e),t&&await t.clearSession(n).catch(t=>{w9.warn(`Failed to clear the durable conversation for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.clearMessagesForScoop(e).catch(t=>{w9.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),w9.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=>{w9.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})}),await Promise.all([...this.deps.getContexts().values()].map(e=>e.clearSession().catch(e=>{w9.warn(`Failed to clear a durable conversation`,{error:e instanceof Error?e.message:String(e)})}))),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(),w9.info(`All messages cleared`)}getQueuedMessageIds(e){return(this.messageQueues.get(e)??[]).map(e=>e.id)}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 T9=r(`orchestrator`),sCe={decision:`deny`};var cCe=class{scoops=new Map;workUnits=new Mv(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new gC({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new qre({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),findParent:e=>this.parentOrDefaultRoot(e),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new KC({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new BC({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findParent:e=>this.parentOrDefaultRoot(e),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 OC({getScoops:()=>this.scoops,findApprover:e=>this.capableApproverOrDefaultRoot(e),getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>Br(e),saveMessage:e=>Nr(e)});lickRegistry=new yC({getConeShell:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},getConeFs:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getFS()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new oCe({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=>Nr(e),deleteMessage:e=>Fr(e),clearMessagesForScoop:e=>Ur(e),clearAllMessages:()=>Vr(),getMessagesSince:(e,t,n)=>zr(e,t,n),setState:(e,t)=>jr(e,t)},isExternalLickChannel:av});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new aCe({getScoops:()=>this.scoops,approverFor:e=>this.ownerRootOrDefault(e),getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getConversationStore:()=>this.conversationStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,getCapabilityBroker:()=>this.capabilityBroker,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>Ar(e),deleteScoop:e=>Hr(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>E(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,n)=>this.resolveActionableLick(e,t,n),approveDirectedOrUser:e=>this.approveDirectedOrUser(e),listPendingSudoRequests:e=>this.listPendingSudoRequests(e)},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}setCapabilityBroker(e){this.capabilityBroker=e}getCapabilityBroker(){return this.capabilityBroker}getProcessManager(){return this.processManager}async initPolicyLayerAndLoadRecords(e,t,n){return wC(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new xb({fs:e,watcher:t,capabilityBroker:this.capabilityBroker,onPolicyReload:e=>{this.lifecycle.syncReadGrants(e),this.approvalRouter.settleGrantedRequests(e)}}),await this.sudoManager.init(),n(),this.llmsTxtIgnorePolicy=new Iy(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new SC(e,t),await this.modelPolicyFile.init(),n(),Kr()),n,{stagePrefix:`orchestrator-init`})}async init(e){await Jr(),this.sharedFs=await wC(e=>_r.create({dbName:`slicc-fs`,onRepairProgress:e}),e),this.sessionStore=new Q_,this.conversationStore=new MS,this.fsWatcher=new gr,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher;let t=await this.initPolicyLayerAndLoadRecords(this.sharedFs,this.fsWatcher,e),n=Object.values(t).find(e=>Cn(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),An(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await Rr(`lastAgentTs_${e.jid}`);r&&this.messageRouter.setLastAgentTimestamp(e.jid,r)}await this.backfillModels(),await this.migrateConversations(e),await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new EC({onTaskRun:async(e,t)=>{T9.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(),T9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let t of this.scoops.values())try{await this.createScoopTab(t.jid)}catch(e){let n=e instanceof Error?e.message:String(e);T9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:t.jid,folder:t.folder,root:t.parentJid===null,error:n}),t.parentJid!==null&&this.lifecycle.markTabError(t.jid,n)}finally{e?.(`scoop-restored:${t.jid}`)}_ee(e=>this.getSessionCostsForCommand(e)),vee(async()=>{let{refreshBudgetWindow:e}=await import(`./budget-usage-source-CjET0w7O.js`).then(e=>e.t);return e()}),this.unregisterExportService=Cb(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new tv;try{await ES({store:t,units:[...this.scoops.values()],loadAgentSession:async e=>{let t=await this.sessionStore?.load(e);return t?{messages:t.messages,createdAt:t.createdAt}:null},loadChatSession:async e=>{let t=await n.load(e);return t?{messages:t.messages,createdAt:t.createdAt}:null},onProgress:e})}catch(e){T9.warn(`Canonical conversation migration failed; staying on the legacy stores`,{error:e instanceof Error?e.message:String(e)})}}async backfillParent(e,t){if(e.parentJid===void 0){e.parentJid=Cn(e)?null:t??null;try{await Ar(e)}catch(t){T9.warn(`Failed to persist backfilled parentJid; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}async backfillModels(){let e=[...this.scoops.values()].filter(e=>!In(e));if(e.length===0)return;let t=CC(),n=[...e].sort((e,t)=>Number(e.parentJid!==null)-Number(t.parentJid!==null));for(let e of n){let n=e.parentJid?this.scoops.get(e.parentJid):void 0,r=(n?Nn(n):void 0)??t;if(r){Tn(e,r);try{await Ar(e)}catch(t){T9.warn(`Failed to persist backfilled model; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}}migrateScoopConfig(e,t){if(e.parentJid===null)return;let n=e.configSchemaVersion??0;if(!(n>=3)){if(n<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),n<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),n<3){let n=`${Wn.root}/`,r=zn(pee(t,e)),i=e.config?.visiblePaths,a=i?.length===1&&i[0]===n;r[0]!==n&&a&&(e.config={...e.config,visiblePaths:r})}e.configSchemaVersion=3}}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/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}getConversationStore(){return this.conversationStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setUnitRosterProvider?.(()=>this.getScoops().map(e=>({name:e.name,folder:e.folder}))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){return 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)}async approveDirectedOrUser(e){let{runDirectedApproval:t}=await import(`./directed-approval-BcWsqbqY.js`);return t(e,{scoops:this.scoops,ownerRootOf:e=>this.ownerRootOrDefault(e),enqueue:(e,t,n)=>this.approvalRouter.enqueueSudoRequest(e,t,n),getSharedFs:()=>this.sharedFs,workspaceFor:Vn,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(T9.warn(`Guest approval before SudoManager init — failing closed`),sCe)}})}async enqueueDirectedApproval(e,t){return this.approveDirectedOrUser({...t,approver:e})}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t,n){return this.approvalRouter.resolveSudoRequestAndPersist(e,t,n)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}registerDiscoveryLick(e){return this.lickRegistry.registerDiscovery(e)}async resolveActionableLick(e,t,n){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t,n)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(e){return this.approvalRouter.listPendingSudoRequests(e)}registerScoop(e){return this.lifecycle.register(e)}async persistScoop(e){this.scoops.set(e.jid,e),await Ar(e)}reinitLiveUnit(e){return this.lifecycle.reinitAfterPromote(e)}async rekeyConversation(e,t){await this.conversationStore?.rekey(e,t)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}getScoopTabState(e){return this.lifecycle.getTab(e)}defaultRoot(){return Rn(this.scoops.values())[0]}parentOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return(t?.parentJid?this.scoops.get(t.parentJid):void 0)??this.defaultRoot()}capableApproverOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return Sn(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return _n(this.scoops.values(),t)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}ensureLiveUnit(e){return this.lifecycle.ensureUnit(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await _r.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await dC(this.sharedFs).catch(e=>{T9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new xb({fs:this.sharedFs,watcher:this.fsWatcher,capabilityBroker:this.capabilityBroker,onPolicyReload:e=>{this.lifecycle.syncReadGrants(e),this.approvalRouter.settleGrantedRequests(e)}}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new Iy(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new SC(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),T9.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e,t={}){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e),t)}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)}getQueuedMessageIds(e){return this.messageRouter.getQueuedMessageIds(e)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return Br(e)}sendPrompt(e,t,n,r,i=[],a){return this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}setScoopModel(e,t){return this.lifecycle.setModel(e,t)}refreshModels(){this.lifecycle.refreshModels()}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-CP0rleV0.js`).then(e=>e.r),r=await n(this.sharedFs);return[...t,...r.map(bee)]}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&&T9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.lickManager?.setDiscoveryIgnore?.(null),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=null,this.modelPolicyFile?.dispose(),this.modelPolicyFile=null,this.sudoManager?.dispose(),this.sudoManager=null,this.unregisterExportService?.(),this.unregisterExportService=null,T9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new tv,t=this.sharedFs;return new Kx({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:dS(),snapshotStore:{read:e=>rS(t,e),write:(e,n)=>nS(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.141.1`})}};const E9=r(`workflow-run-manager`),D9=`/shared/workflow-runs`,O9=1e3;function lCe(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function uCe(e){let t=new Map,n=new Map,r=e=>{let r=t.get(e);if(r)for(let t of n.get(e)??[])try{t(r)}catch(e){E9.warn(`observeRun handler threw`,e)}},i=(e,n)=>hCe(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=lCe(e,a.parentJid),d={id:c,name:a.name,source:a.source,origin:u.origin,lickTarget:u.lickTarget,status:`running`,currentPhase:null,agentsStarted:0,agentsDone:0,logs:[],startedAt:new Date().toISOString(),finishedAt:null,resultPath:null,preview:null,error:null,pid:null};t.set(c,d),pCe(t,n);let f=i(a.ctx,c),p=mCe(e.processManager,d,c,()=>r(c));return e.runRealm(a.code,[`workflow`,a.filename,c],f).then(e=>o(c,l,e)).catch(e=>s(c,e instanceof Error?e.message:String(e))).finally(()=>p()).catch(e=>E9.warn(`workflow run lifecycle error`,e)),{runId:c}}async function o(t,n,r){let{result:i,hadResult:a}=e.splitResult(r.stdout,n);return r.exitCode===137?c(t,`killed`,null,r.stderr||`killed (SIGKILL)`):r.exitCode!==0||!a?c(t,`error`,null,r.stderr||(a?`exit ${r.exitCode}`:`script produced no result`)):c(t,`done`,i,null)}function s(e,t){return c(e,`error`,null,t)}async function c(n,i,a,o){let s=t.get(n);if(!s||s.status!==`running`&&s.status!==`paused`)return;let c=`${D9}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(D9,{recursive:!0}),await e.sharedFs.writeFile(c,JSON.stringify({name:s.name,status:i,result:i===`done`?a:null,error:o,logs:s.logs,startedAt:s.startedAt,finishedAt:u},null,2)),s.resultPath=c}catch(e){let t=e instanceof Error?e.message:String(e);E9.error(`failed to write run result file`,{runId:n,resultPath:c,error:t}),o=`result file write failed: ${t}`,i===`done`&&(i=`error`)}s.status=i,s.error=o,s.finishedAt=u,s.preview=i===`done`?fCe(a):o??``,r(n),l(s)}function l(t){t.origin===`cone`&&e.fireLick({type:`workflow`,targetScoop:t.lickTarget,workflowRunId:t.id,workflowName:t.name??void 0,resultPath:t.resultPath??void 0,preview:t.preview??t.error??void 0,timestamp:new Date().toISOString(),body:{runId:t.id,status:t.status,error:t.error}})}return{start:a,getRun:e=>t.get(e)??null,listRuns:()=>Array.from(t.values()),observeRun(e,r){let i=n.get(e);i||(i=new Set,n.set(e,i)),i.add(r);let a=t.get(e);if(a)try{r(a)}catch(e){E9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function dCe(e){let t=uCe(e);return globalThis[E7]=t,E9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function fCe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function pCe(e,t,n=100){if(e.size<=n)return;let r=[...e.values()].filter(e=>e.status!==`running`&&e.status!==`paused`).sort((e,t)=>(e.finishedAt??e.startedAt).localeCompare(t.finishedAt??t.startedAt)),i=e.size-n;for(let n of r){if(i<=0)break;e.delete(n.id),t.delete(n.id),i--}}function mCe(e,t,n,r){let i=e.on(`spawn`,e=>{t.pid===null&&e.argv.includes(n)&&(t.pid=e.pid,r(),i())});return i}function hCe(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?gCe(n,t,a?.args??[],r):e===`agent`?_Ce(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function gCe(e,t,n,r){let i=e.get(t);if(i&&i.status===`running`){let[e,t=``]=n;e===`phase`?(i.currentPhase=t,i.logs.push(t)):e===`log`&&i.logs.push(t),i.logs.length>O9&&i.logs.splice(0,i.logs.length-O9),r()}return{stdout:``,stderr:``,exitCode:0}}async function _Ce(e,t,n,r){let i=e.get(t);i&&i.status===`running`&&(i.agentsStarted++,r());try{return await n()}finally{let n=e.get(t);n&&n.status===`running`&&(n.agentsDone++,r())}}const vCe=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function yCe(e,t,n){let r=bCe(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=xCe(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function bCe(e){let t=new Map;return k9(t,e.discoveryOrigin),k9(t,e.discoveryUrl),[...t.values()]}function k9(e,t){if(t){A9(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);A9(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!vCe.has(e)))A9(e,t,1,`substring`)}catch{}}}function A9(e,t,n,r){if(t.length===0)return;let i=`${r}:${t}`,a=e.get(i);(!a||n>a.weight)&&e.set(i,{text:t,weight:n,match:r})}function xCe(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=CCe(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)SCe(a,e)&&(r+=e.weight*o)}return r}function SCe(e,t){if(t.match===`substring`)return e.includes(t.text);let n=t.text.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(^|[^a-z0-9.-])(?:www\\.)?${n}($|[^a-z0-9.-])`).test(e)}function CCe(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}var wCe=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=N9(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)),t.push({name:M9,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===M9)throw new rr(`ENOTDIR`,`not a directory`,e);let n=P9(t[0]);if(n===null||!this.pidExists(n))throw new rr(`ENOENT`,`no such file or directory`,e);return j9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new rr(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=N9(e);if(t.length===1&&t[0]===M9)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new rr(`EISDIR`,`is a directory`,e);let n=P9(t[0]);if(n===null||!this.pidExists(n))throw new rr(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!j9.includes(r))throw new rr(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new rr(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=N9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===M9)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=P9(t[0]);if(n===null||!this.pidExists(n))throw new rr(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=P9(t[0]);if(n===null||!this.pidExists(n))throw new rr(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!j9.includes(r))throw new rr(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new rr(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new rr(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new rr(`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 rr(`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}renderTable(){let e={stats:this.pm.stats(),processes:this.pm.list().map(e=>({pid:e.pid,ppid:e.ppid,kind:e.kind,state:F9(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:I9(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
5001
5001
|
`}renderProcFile(e,t){if(e===1)return kCe(t);let n=this.pm.get(e);switch(t){case`status`:return TCe(n);case`cmdline`:return ECe(n);case`cwd`:return DCe(n);case`stat`:return OCe(n)}}};const j9=[`status`,`cmdline`,`cwd`,`stat`],M9=`table`;function N9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function P9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function TCe(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${F9(e.status)} (${e.status})`,`Owner:\t${I9(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(`
|
|
5002
5002
|
`)+`
|
|
5003
5003
|
`}function ECe(e){return e.argv.join(`\0`)+`\0`}function DCe(e){return e.cwd+`
|
|
@@ -5006,7 +5006,7 @@ pass --wait to block and print the full result.`,Ybe=new Set([`list`,`status`,`s
|
|
|
5006
5006
|
`)+`
|
|
5007
5007
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
5008
5008
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
5009
|
-
`}}function ACe(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(RU(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(!NU(n.token))return;let a=i.get(n.id);if(a){r({type:zU,id:n.id}),a.result&&r({type:BU,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:zU,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:BU,id:n.id,...e})};(WU(n)?qU(n):LU(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 L9(){return globalThis}function jCe(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`bash`:return e.bashJobId??`bash`;case`preview`:return e.previewOrigin??`preview`;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function MCe(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`bash`:return`bash-${e.bashJobId??`unknown`}`;case`preview`:return e.previewConnId??`preview-${e.timestamp}`;case`discovery`:return e.discoveryUrl??`discovery-${e.timestamp}`;default:return e.cronId}}function NCe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}PCe(e,t)}function PCe(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=Rn(r),a=e.type===`discovery`&&!e.targetScoop?yCe(e,i.filter(Ny),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?qc(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!Ny(o)){n.debug?.(`dropping discovery lick for non-browsing scoop`,{scoop:o.folder});return}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):e.type===`discovery`&&(e.lickId=t.registerDiscoveryLick(e)??void 0);let s=yv(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=jCe(e),l=MCe(e),u=e.type,d={id:`${u}-${l}-${Date.now()}`,chatJid:o.jid,senderId:u,senderName:`${u}:${c}`,content:s.content,timestamp:e.timestamp,fromAssistant:!1,channel:u,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(d).catch(e=>{n.warn(`Lick message routing failed`,{channel:u,eventName:c,error:String(e)})})}async function FCe(e,t,n,r,i){let a=new ha,o=new cCe(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a);let s=Rt(),c=i.capabilityBroker??Wy(s,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});o.setCapabilityBroker(c),sr(c),L9().__slicc_pm=a,fJ(mJ()),L9().__slicc_browser=t,await n.bind(o,t);let l=Dr(()=>n.emitTrayRuntimeStatus()),u=Xv(()=>n.emitTrayRuntimeStatus());return await o.init(i.onBootProgress),await n.seedBuffersFromAgentState(),{processManager:a,orchestrator:o,unsubLeader:l,unsubFollower:u,sharedFs:o.getSharedFS(),capabilityBroker:c}}async function ICe(e,t,n){let{registerSessionBudgetProvider:r,registerSessionCostsProvider:i}=await import(`./cost-command-B5aRQX4l.js`).then(e=>e.t);i(t=>e.getSessionCostsForCommand(t));let{refreshBudgetWindow:a}=await import(`./budget-usage-source-
|
|
5010
|
-
`,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 BCe(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-RFOSPq0w.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-BxfjZHzO.js`);return i(e,{locationHref:self.location.href,lickWsUrl:n??null,onHostfsInvalidate:e=>{if(!r)return;let n=r.getMountBackend(e.mount);if(!(n instanceof a)){t.debug?.(`hostfs_invalidate for unknown/non-hostfs mount`,{mount:e.mount});return}n.applyHostInvalidation(e.paths).catch(n=>{t.warn(`hostfs_invalidate apply failed`,{mount:e.mount,error:n instanceof Error?n.message:String(n)})})}}).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 VCe(e,t,n,r){let i=e.getTransport();if(i.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 wy(i,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})},{...HCe(t),isOwnTab:Sy(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function HCe(e){let t=fe();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,discoverySource:`live-navigation`,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:()=>Ty()}}function UCe(e,t,n){(async()=>{try{let{getAllMountEntries:r,removeMountEntry:i}=await import(`./mount-table-store-DrF_Ifaz.js`).then(e=>e.r),{recoverMounts:a}=await import(`./mount-recovery-B1OZnCNp.js`).then(e=>e.n),{hostShadowedEntries:o,mountConfiguredHostMounts:s,withoutHostMountedTargets:c}=await import(`./auto-mount-table-0jMTi9rV.js`),l=await s(e,n),u=await r(),d=c(u,l);for(let e of o(u,l))i(e.targetPath).catch(t=>{n.warn(`failed to purge host-owned mount row`,{path:e.targetPath,error:t instanceof Error?t.message:String(t)})});if(d.length===0)return;let{needsRecovery:f}=await a(d,e,n);if(f.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:f}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function WCe(){Xr(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-1FdN6g-s.js`);return e()})}function GCe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-1FdN6g-s.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 KCe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-ClwrdzEH.js`),{ScriptCatalog:r}=await import(`./script-catalog-Bt94D0RP.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 qCe(e){return e===`node-rest`}async function JCe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);WCe();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await FCe(t,n,r,i,e);if(s(`orchestrator-ready`),f?mn(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new wCe(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await ICe(l,e,o);s(`lick-manager-ready`),f&&RCe({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),L9().__slicc_lickManager=m;let{wsBridge:h,wsRegistry:g}=await zCe({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});L9().__slicc_wsSubscribers=g;let _=null;qCe(p.adapter)&&(_=await BCe(m,o,e.localLickWsUrl??null,f));let v=VCe(n,m,o,e.appPageUrl);f&&UCe(f,m,o),a||await LCe(l),s(`cone-bootstrapped`),f&&GCe(m,o);let y=null,b=null;f&&({bshWatchdogStop:y,scriptCatalogDispose:b}=await KCe(f,n,o));let x=null;f&&e.syncFsChannelNonce&&(x=ACe({nonce:e.syncFsChannelNonce}).dispose);let S=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:m,sharedFs:f??null,processManager:c,capabilityBroker:p,async dispose(){S||(S=!0,await YCe({unsubLeader:u,unsubFollower:d,bshWatchdogStop:y,scriptCatalogDispose:b,lickWsBridgeStop:_,navigationWatcherStop:v,syncFsResponderDispose:x,sharedFs:f,wsRegistry:g,wsBridge:h,processManager:c,lickManager:m,browser:n,log:o}))}}}async function YCe(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)}XCe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function XCe(e){let t=L9();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,fJ(null)),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[E7]}const R9=`x-bypass-llm-proxy`;function ZCe(e,t,n){return t?(r,i)=>{if(!QCe(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(R9)||a.set(R9,`1`),e(r,{...i,headers:a})}:e}function QCe(e,t,n){if(ewe(e,t))return!0;let r=n?.()??null;return r?$Ce(e,r,t):!1}function $Ce(e,t,n){let r=z9(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 ewe(e,t){let n=z9(e);try{return new URL(n,t).origin===t}catch{return!0}}function z9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function twe(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 nwe=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(!rwe(e)||e.source!==`panel`)return;let t=e.payload;iwe(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,t.shell.applySessionOverrides?.({cwd:e.cwd,env:e.env});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=``;if(e.stdin)try{i=Xa(g(e.stdin))}catch{this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec with invalid stdin (expected base64)`,e.sid);return}let a=await t.shell.executeCommand(e.command,n.signal,r?.pid,i);await this.emitExecSuccess(e,a,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?B9(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,B9(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 rwe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function B9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function iwe(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 awe=class extends G7{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 owe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new nwe({transport:t,processManager:i,createShell:(a,o)=>new awe(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Tr},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function swe(e){return typeof e==`string`&&e.startsWith(`No API key configured`)}function cwe(e){if(!e)return!1;let t=e.toLowerCase();return t.includes(`the provided model identifier is invalid`)||t.includes(`model not allowed`)}function lwe(e){return e?e.toLowerCase().includes(`please log in again`):!1}function uwe(e){return e?e.toLowerCase().includes(`quota_exceeded`):!1}function V9(e){return swe(e)||cwe(e)||lwe(e)||uwe(e)}let H9=null,U9=!1;function dwe(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function fwe(e){return dwe()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function pwe(e={}){if(!U9&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){Txe(mwe),MC(hwe),Xre(W9);try{let t=fwe(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(H9=(await import(`./rum-worker-CwmNSpjO.js`)).default,self.addEventListener(`error`,e=>{let t=e;W9(`js`,t.error?.message??t.message??``)}),self.addEventListener(`unhandledrejection`,e=>{let t=e.reason;W9(`js`,t instanceof Error?t.message:String(t))})):t===`extension`?(H9=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&(window.addEventListener(`error`,e=>{let t=e;W9(`js`,t.error?.message??t.message??``)}),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;W9(`js`,t instanceof Error?t.message:String(t))}))):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),vwe(),H9=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),U9=!0,H9&&H9(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function mwe(e){H9?.(`fill`,{source:e})}function W9(e,t){let n=t;if(typeof n==`string`){if(V9(n))return;let e=G9(n);if(e===null)return;n=e}H9?.(`error`,{source:e,target:n})}function hwe(e,t,n){if(e===`error`){let e=n;if(typeof e==`string`){if(V9(e))return;let t=G9(e);if(t===null)return;e=t}H9?.(`error`,{source:`scoop:${t}`,target:e});return}H9?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function gwe(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function G9(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
|
|
5009
|
+
`}}function ACe(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(RU(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(!NU(n.token))return;let a=i.get(n.id);if(a){r({type:zU,id:n.id}),a.result&&r({type:BU,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:zU,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:BU,id:n.id,...e})};(WU(n)?qU(n):LU(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 L9(){return globalThis}function jCe(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`bash`:return e.bashJobId??`bash`;case`preview`:return e.previewOrigin??`preview`;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function MCe(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`bash`:return`bash-${e.bashJobId??`unknown`}`;case`preview`:return e.previewConnId??`preview-${e.timestamp}`;case`discovery`:return e.discoveryUrl??`discovery-${e.timestamp}`;default:return e.cronId}}function NCe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}PCe(e,t)}function PCe(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=Rn(r),a=e.type===`discovery`&&!e.targetScoop?yCe(e,i.filter(Ny),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?qc(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!Ny(o)){n.debug?.(`dropping discovery lick for non-browsing scoop`,{scoop:o.folder});return}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):e.type===`discovery`&&(e.lickId=t.registerDiscoveryLick(e)??void 0);let s=yv(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=jCe(e),l=MCe(e),u=e.type,d={id:`${u}-${l}-${Date.now()}`,chatJid:o.jid,senderId:u,senderName:`${u}:${c}`,content:s.content,timestamp:e.timestamp,fromAssistant:!1,channel:u,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(d).catch(e=>{n.warn(`Lick message routing failed`,{channel:u,eventName:c,error:String(e)})})}async function FCe(e,t,n,r,i){let a=new ha,o=new cCe(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a);let s=Rt(),c=i.capabilityBroker??Wy(s,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});o.setCapabilityBroker(c),sr(c),L9().__slicc_pm=a,fJ(mJ()),L9().__slicc_browser=t,await n.bind(o,t);let l=Dr(()=>n.emitTrayRuntimeStatus()),u=Xv(()=>n.emitTrayRuntimeStatus());return await o.init(i.onBootProgress),await n.seedBuffersFromAgentState(),{processManager:a,orchestrator:o,unsubLeader:l,unsubFollower:u,sharedFs:o.getSharedFS(),capabilityBroker:c}}async function ICe(e,t,n){let{registerSessionBudgetProvider:r,registerSessionCostsProvider:i}=await import(`./cost-command-B5aRQX4l.js`).then(e=>e.t);i(t=>e.getSessionCostsForCommand(t));let{refreshBudgetWindow:a}=await import(`./budget-usage-source-CjET0w7O.js`).then(e=>e.t);r(()=>a());let{getLickManager:o}=await import(`./lick-manager-ULemXDKa.js`).then(e=>e.n),s=o();await s.init(),e.setLickManager(s);let c=t.lickEventHandler??NCe,l={orchestrator:e,lickManager:s,log:n};return s.setEventHandler(e=>c(e,l)),s}async function LCe(e){let t=e.getScoops();Rn(t).length>0||await e.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,parentJid:null,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()})}function RCe(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;dCe({sharedFs:i,getStartingRoot:e=>{let n=Rn(t.getScoops()),r=n.find(t=>t.jid===e);return r?{jid:r.jid,lickTarget:r.jid===n[0]?.jid?void 0:r.folder}:null},fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>gJ(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>D7().slice(10,22),splitResult:(e,t)=>O7(e,t)})}async function zCe(e){let{browser:t,lickManager:n,orchestrator:r,sharedFs:i,log:a}=e,{CdpWsPageBridge:o}=await import(`./cdp-ws-page-bridge-DsbAqoSN.js`),{WsSubscriberRegistry:s}=await import(`./ws-subscribers-CKHqIv8e.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))+`
|
|
5010
|
+
`,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 BCe(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-RFOSPq0w.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-BxfjZHzO.js`);return i(e,{locationHref:self.location.href,lickWsUrl:n??null,onHostfsInvalidate:e=>{if(!r)return;let n=r.getMountBackend(e.mount);if(!(n instanceof a)){t.debug?.(`hostfs_invalidate for unknown/non-hostfs mount`,{mount:e.mount});return}n.applyHostInvalidation(e.paths).catch(n=>{t.warn(`hostfs_invalidate apply failed`,{mount:e.mount,error:n instanceof Error?n.message:String(n)})})}}).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 VCe(e,t,n,r){let i=e.getTransport();if(i.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 wy(i,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})},{...HCe(t),isOwnTab:Sy(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function HCe(e){let t=fe();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,discoverySource:`live-navigation`,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:()=>Ty()}}function UCe(e,t,n){(async()=>{try{let{getAllMountEntries:r,removeMountEntry:i}=await import(`./mount-table-store-DrF_Ifaz.js`).then(e=>e.r),{recoverMounts:a}=await import(`./mount-recovery-BbM7KXdZ.js`).then(e=>e.n),{hostShadowedEntries:o,mountConfiguredHostMounts:s,withoutHostMountedTargets:c}=await import(`./auto-mount-table-0jMTi9rV.js`),l=await s(e,n),u=await r(),d=c(u,l);for(let e of o(u,l))i(e.targetPath).catch(t=>{n.warn(`failed to purge host-owned mount row`,{path:e.targetPath,error:t instanceof Error?t.message:String(t)})});if(d.length===0)return;let{needsRecovery:f}=await a(d,e,n);if(f.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:f}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function WCe(){Xr(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-CAAKwVc2.js`);return e()})}function GCe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-CAAKwVc2.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 KCe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-ClwrdzEH.js`),{ScriptCatalog:r}=await import(`./script-catalog-Bt94D0RP.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 qCe(e){return e===`node-rest`}async function JCe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);WCe();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await FCe(t,n,r,i,e);if(s(`orchestrator-ready`),f?mn(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new wCe(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await ICe(l,e,o);s(`lick-manager-ready`),f&&RCe({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),L9().__slicc_lickManager=m;let{wsBridge:h,wsRegistry:g}=await zCe({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});L9().__slicc_wsSubscribers=g;let _=null;qCe(p.adapter)&&(_=await BCe(m,o,e.localLickWsUrl??null,f));let v=VCe(n,m,o,e.appPageUrl);f&&UCe(f,m,o),a||await LCe(l),s(`cone-bootstrapped`),f&&GCe(m,o);let y=null,b=null;f&&({bshWatchdogStop:y,scriptCatalogDispose:b}=await KCe(f,n,o));let x=null;f&&e.syncFsChannelNonce&&(x=ACe({nonce:e.syncFsChannelNonce}).dispose);let S=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:m,sharedFs:f??null,processManager:c,capabilityBroker:p,async dispose(){S||(S=!0,await YCe({unsubLeader:u,unsubFollower:d,bshWatchdogStop:y,scriptCatalogDispose:b,lickWsBridgeStop:_,navigationWatcherStop:v,syncFsResponderDispose:x,sharedFs:f,wsRegistry:g,wsBridge:h,processManager:c,lickManager:m,browser:n,log:o}))}}}async function YCe(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)}XCe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function XCe(e){let t=L9();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,fJ(null)),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[E7]}const R9=`x-bypass-llm-proxy`;function ZCe(e,t,n){return t?(r,i)=>{if(!QCe(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(R9)||a.set(R9,`1`),e(r,{...i,headers:a})}:e}function QCe(e,t,n){if(ewe(e,t))return!0;let r=n?.()??null;return r?$Ce(e,r,t):!1}function $Ce(e,t,n){let r=z9(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 ewe(e,t){let n=z9(e);try{return new URL(n,t).origin===t}catch{return!0}}function z9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function twe(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 nwe=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(!rwe(e)||e.source!==`panel`)return;let t=e.payload;iwe(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,t.shell.applySessionOverrides?.({cwd:e.cwd,env:e.env});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=``;if(e.stdin)try{i=Xa(g(e.stdin))}catch{this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec with invalid stdin (expected base64)`,e.sid);return}let a=await t.shell.executeCommand(e.command,n.signal,r?.pid,i);await this.emitExecSuccess(e,a,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?B9(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,B9(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 rwe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function B9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function iwe(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 awe=class extends G7{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 owe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new nwe({transport:t,processManager:i,createShell:(a,o)=>new awe(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Tr},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function swe(e){return typeof e==`string`&&e.startsWith(`No API key configured`)}function cwe(e){if(!e)return!1;let t=e.toLowerCase();return t.includes(`the provided model identifier is invalid`)||t.includes(`model not allowed`)}function lwe(e){return e?e.toLowerCase().includes(`please log in again`):!1}function uwe(e){return e?e.toLowerCase().includes(`quota_exceeded`):!1}function V9(e){return swe(e)||cwe(e)||lwe(e)||uwe(e)}let H9=null,U9=!1;function dwe(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function fwe(e){return dwe()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function pwe(e={}){if(!U9&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){Txe(mwe),MC(hwe),Xre(W9);try{let t=fwe(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(H9=(await import(`./rum-worker-CwmNSpjO.js`)).default,self.addEventListener(`error`,e=>{let t=e;W9(`js`,t.error?.message??t.message??``)}),self.addEventListener(`unhandledrejection`,e=>{let t=e.reason;W9(`js`,t instanceof Error?t.message:String(t))})):t===`extension`?(H9=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&(window.addEventListener(`error`,e=>{let t=e;W9(`js`,t.error?.message??t.message??``)}),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;W9(`js`,t instanceof Error?t.message:String(t))}))):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),vwe(),H9=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),U9=!0,H9&&H9(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function mwe(e){H9?.(`fill`,{source:e})}function W9(e,t){let n=t;if(typeof n==`string`){if(V9(n))return;let e=G9(n);if(e===null)return;n=e}H9?.(`error`,{source:e,target:n})}function hwe(e,t,n){if(e===`error`){let e=n;if(typeof e==`string`){if(V9(e))return;let t=G9(e);if(t===null)return;e=t}H9?.(`error`,{source:`scoop:${t}`,target:e});return}H9?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function gwe(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function G9(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
|
|
5011
5011
|
`).filter(e=>!gwe(e)).join(`
|
|
5012
|
-
`).trim();return e?e.slice(0,200).replace(/(\/[a-z]+)(?:\/[^\s/]+)+/gi,`$1/.../`):null}return t.slice(0,200).replace(/(\/[a-z]+)(?:\/[^\s/]+)+/gi,`$1/.../`)}const K9=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`);function q9(e){if(typeof e!=`string`)return{kind:`absent`};let t=G9(e);return t===null?{kind:`noise`}:{kind:`kept`,value:t,mutated:t!==e}}function _we(e){let t=q9(e.source),n=q9(e.target),r=t.kind!==`kept`,i=n.kind!==`kept`;if((t.kind!==`absent`||n.kind!==`absent`)&&r&&i)return!0;let a=!1;return t.kind===`kept`?t.mutated&&(e.source=t.value,a=!0):t.kind===`noise`&&(e.source=``,a=!0),n.kind===`kept`?n.mutated&&(e.target=n.value,a=!0):n.kind===`noise`&&(e.target=``,a=!0),a?JSON.stringify(e):null}function vwe(){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let e=navigator.sendBeacon;if(e[K9])return;let t=e.bind(navigator),n=((e,n)=>{try{let r=typeof n==`string`?n:n instanceof ArrayBuffer?new TextDecoder().decode(n):null;if(r&&r.length>0&&r.charCodeAt(0)===123){let n=JSON.parse(r);if(n?.checkpoint===`error`){let r=_we(n);if(r===!0)return!0;if(r!==null)return t(e,r)}}}catch{}return t(e,n)});n[K9]=!0,navigator.sendBeacon=n}function ywe(e){let t=new bwe(e);return t.start(),{stop:()=>t.dispose()}}var bwe=class{transport;client;writableClient;getWatcher;log;unsubscribe=null;watches=new Map;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.getWatcher=e.getWatcher??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!xwe(e)||e.source!==`panel`)return;let t=e.payload;if(Swe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(Cwe(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(wwe(t)){this.handleWatchControl(t);return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.watches)for(let t of e)t();this.watches.clear()}handleWatchControl(e){e.type===`vfs-watch`?this.handleWatch(e):this.handleUnwatch(e)}handleWatch(e){this.dropWatch(e.subscriptionId);let t=this.getWatcher?.()??null;if(!t){this.sendWatchAck({type:`vfs-watch-result`,subscriptionId:e.subscriptionId,ok:!1,error:{code:`ENOSYS`,message:`vfs-rpc-host has no watcher wired`}});return}let n=e.basePaths.map(n=>t.watch(n,()=>!0,t=>{if(!this.watches.has(e.subscriptionId))return;let n={type:`vfs-watch-event`,subscriptionId:e.subscriptionId,events:t.map(e=>({type:e.type,path:e.path,...e.entryType?{entryType:e.entryType}:{}}))};this.transport.send(n)}));this.watches.set(e.subscriptionId,n),this.sendWatchAck({type:`vfs-watch-result`,subscriptionId:e.subscriptionId,ok:!0})}handleUnwatch(e){this.dropWatch(e.subscriptionId)}dropWatch(e){let t=this.watches.get(e);if(t){this.watches.delete(e);for(let e of t)e()}}sendWatchAck(e){this.transport.send(e)}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=e.includeStats===!0?await this.client.readDir(e.path,{includeStats:!0}):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 rr(`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 rr(`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(Twe(e.type),e.requestId,new rr(`EACCES`,`vfs-rpc-host has no writable backend wired`),Ewe(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 rr(`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 rr(`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 rr(`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 xwe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Swe(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 Cwe(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 wwe(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function Twe(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 Ewe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof rr?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Dwe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=ZCe(e.bind(globalThis),t,Owe)}function Owe(){let e=Se();if(!e)return null;try{return new URL(e).origin}catch{return null}}function kwe(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 Awe=twe(e=>Nwe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Awe.handle(e.data)});function jwe(e){let t=Es(e.pageBuildId,`6.141.0-mtsqwqov`);return()=>{t&&W9(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.141.0-mtsqwqov`)}}function Mwe(e){Dwe(),xe(e.localApiBaseUrl??null),A(e.bridgeToken??null),oJ(e.syncFsBridgeEnabled??!1),Jee(e.pageLoadedAt??null),j(e.extensionDelegateId??null),kwe(e.localStorageSeed??{}),e.flagFloat&&ms(e.flagFloat)}async function Nwe(e){Cs(e.instanceId);let t=jwe(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{Mwe(e),pwe().then(t).catch(()=>{}),await p(),n(`providers-registered`);let r=Gc(e.kernelPort),i=new hy(r),a=hy.createCallbacks(i),o=new Kc(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new lte(o);Y9=await JCe({container:{},browser:s,bridge:i,callbacks:a,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null,appPageUrl:e.appPageUrl??null,onBootProgress:n});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-CftxYQ9D.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let d=Y9.sharedFs?.getWatcher();if(d){let e=null,t=new Set;for(let n of Xee)d.watch(n,e=>e.endsWith(`.shtml`),n=>{for(let e of n){let n=e.path.split(`/`).pop()?.replace(/\.shtml$/,``);n&&t.add(n)}e||=setTimeout(()=>{e=null;for(let e of t)l.reload(e).catch(()=>{});t.clear()},300)})}let{createPanelRpcClient:f}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i);$9=f({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,s.setTrayTargetProvider(Zo(u));let m=await Fwe({host:Y9,transport:r,browser:s,instanceId:e.instanceId});m&&(X9=m.stopTerminalHost,Z9=m.stopVfsRpcHost,Q9=m.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){Pwe(e.kernelPort,t)}}function Pwe(e,t){Ts(t);try{let n=t instanceof Error?t.message:String(t),r=t?.code;e.postMessage({type:`kernel-worker-boot-error`,message:n,...typeof r==`string`?{code:r}:{},...t instanceof Error&&t.stack?{stack:t.stack}:{}})}catch{}throw t}async function Fwe(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=()=>e.host.capabilityBroker.adapter===`node-rest`,r=owe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),webhook:{hasLocalNodeServer:n},crontask:{hasLocalNodeServer:n},logger:console}),i=ywe({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await Iwe(t,e.instanceId);return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a}}async function Iwe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-Czc4X1XD.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-DUC7X0GS.js`).then(e=>e.i),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())});
|
|
5012
|
+
`).trim();return e?e.slice(0,200).replace(/(\/[a-z]+)(?:\/[^\s/]+)+/gi,`$1/.../`):null}return t.slice(0,200).replace(/(\/[a-z]+)(?:\/[^\s/]+)+/gi,`$1/.../`)}const K9=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`);function q9(e){if(typeof e!=`string`)return{kind:`absent`};let t=G9(e);return t===null?{kind:`noise`}:{kind:`kept`,value:t,mutated:t!==e}}function _we(e){let t=q9(e.source),n=q9(e.target),r=t.kind!==`kept`,i=n.kind!==`kept`;if((t.kind!==`absent`||n.kind!==`absent`)&&r&&i)return!0;let a=!1;return t.kind===`kept`?t.mutated&&(e.source=t.value,a=!0):t.kind===`noise`&&(e.source=``,a=!0),n.kind===`kept`?n.mutated&&(e.target=n.value,a=!0):n.kind===`noise`&&(e.target=``,a=!0),a?JSON.stringify(e):null}function vwe(){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let e=navigator.sendBeacon;if(e[K9])return;let t=e.bind(navigator),n=((e,n)=>{try{let r=typeof n==`string`?n:n instanceof ArrayBuffer?new TextDecoder().decode(n):null;if(r&&r.length>0&&r.charCodeAt(0)===123){let n=JSON.parse(r);if(n?.checkpoint===`error`){let r=_we(n);if(r===!0)return!0;if(r!==null)return t(e,r)}}}catch{}return t(e,n)});n[K9]=!0,navigator.sendBeacon=n}function ywe(e){let t=new bwe(e);return t.start(),{stop:()=>t.dispose()}}var bwe=class{transport;client;writableClient;getWatcher;log;unsubscribe=null;watches=new Map;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.getWatcher=e.getWatcher??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!xwe(e)||e.source!==`panel`)return;let t=e.payload;if(Swe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(Cwe(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(wwe(t)){this.handleWatchControl(t);return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.watches)for(let t of e)t();this.watches.clear()}handleWatchControl(e){e.type===`vfs-watch`?this.handleWatch(e):this.handleUnwatch(e)}handleWatch(e){this.dropWatch(e.subscriptionId);let t=this.getWatcher?.()??null;if(!t){this.sendWatchAck({type:`vfs-watch-result`,subscriptionId:e.subscriptionId,ok:!1,error:{code:`ENOSYS`,message:`vfs-rpc-host has no watcher wired`}});return}let n=e.basePaths.map(n=>t.watch(n,()=>!0,t=>{if(!this.watches.has(e.subscriptionId))return;let n={type:`vfs-watch-event`,subscriptionId:e.subscriptionId,events:t.map(e=>({type:e.type,path:e.path,...e.entryType?{entryType:e.entryType}:{}}))};this.transport.send(n)}));this.watches.set(e.subscriptionId,n),this.sendWatchAck({type:`vfs-watch-result`,subscriptionId:e.subscriptionId,ok:!0})}handleUnwatch(e){this.dropWatch(e.subscriptionId)}dropWatch(e){let t=this.watches.get(e);if(t){this.watches.delete(e);for(let e of t)e()}}sendWatchAck(e){this.transport.send(e)}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=e.includeStats===!0?await this.client.readDir(e.path,{includeStats:!0}):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 rr(`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 rr(`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(Twe(e.type),e.requestId,new rr(`EACCES`,`vfs-rpc-host has no writable backend wired`),Ewe(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 rr(`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 rr(`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 rr(`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 xwe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Swe(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 Cwe(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 wwe(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function Twe(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 Ewe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof rr?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Dwe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=ZCe(e.bind(globalThis),t,Owe)}function Owe(){let e=Se();if(!e)return null;try{return new URL(e).origin}catch{return null}}function kwe(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 Awe=twe(e=>Nwe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Awe.handle(e.data)});function jwe(e){let t=Es(e.pageBuildId,`6.141.1-mtsydn83`);return()=>{t&&W9(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.141.1-mtsydn83`)}}function Mwe(e){Dwe(),xe(e.localApiBaseUrl??null),A(e.bridgeToken??null),oJ(e.syncFsBridgeEnabled??!1),Jee(e.pageLoadedAt??null),j(e.extensionDelegateId??null),kwe(e.localStorageSeed??{}),e.flagFloat&&ms(e.flagFloat)}async function Nwe(e){Cs(e.instanceId);let t=jwe(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{Mwe(e),pwe().then(t).catch(()=>{}),await p(),n(`providers-registered`);let r=Gc(e.kernelPort),i=new hy(r),a=hy.createCallbacks(i),o=new Kc(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new lte(o);Y9=await JCe({container:{},browser:s,bridge:i,callbacks:a,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null,appPageUrl:e.appPageUrl??null,onBootProgress:n});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-CftxYQ9D.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let d=Y9.sharedFs?.getWatcher();if(d){let e=null,t=new Set;for(let n of Xee)d.watch(n,e=>e.endsWith(`.shtml`),n=>{for(let e of n){let n=e.path.split(`/`).pop()?.replace(/\.shtml$/,``);n&&t.add(n)}e||=setTimeout(()=>{e=null;for(let e of t)l.reload(e).catch(()=>{});t.clear()},300)})}let{createPanelRpcClient:f}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i);$9=f({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,s.setTrayTargetProvider(Zo(u));let m=await Fwe({host:Y9,transport:r,browser:s,instanceId:e.instanceId});m&&(X9=m.stopTerminalHost,Z9=m.stopVfsRpcHost,Q9=m.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){Pwe(e.kernelPort,t)}}function Pwe(e,t){Ts(t);try{let n=t instanceof Error?t.message:String(t),r=t?.code;e.postMessage({type:`kernel-worker-boot-error`,message:n,...typeof r==`string`?{code:r}:{},...t instanceof Error&&t.stack?{stack:t.stack}:{}})}catch{}throw t}async function Fwe(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=()=>e.host.capabilityBroker.adapter===`node-rest`,r=owe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),webhook:{hasLocalNodeServer:n},crontask:{hasLocalNodeServer:n},logger:console}),i=ywe({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await Iwe(t,e.instanceId);return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a}}async function Iwe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-Czc4X1XD.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-DUC7X0GS.js`).then(e=>e.i),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())});
|