sliccy 6.141.3 → 6.141.4
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 +159 -159
- package/dist/ui/assets/{SKILL-CkexdTt9.js → SKILL-B-lyKDjk.js} +1 -1
- package/dist/ui/assets/{account-store-OqSCLUiN.js → account-store-BSIs8eWH.js} +1 -1
- package/dist/ui/assets/{account-store-CDR1C1oH.js → account-store-CfKG-Ig3.js} +1 -1
- package/dist/ui/assets/{adobe-DOKmLQCK.js → adobe--jIvF0ng.js} +1 -1
- package/dist/ui/assets/{adobe-VmM9LuAK.js → adobe-BrcV3j-w.js} +1 -1
- package/dist/ui/assets/{agent-bridge-CcjfBcbz.js → agent-bridge-DEABZego.js} +1 -1
- package/dist/ui/assets/{agent-panels-C0onsdTK.js → agent-panels-_ItKLnAu.js} +1 -1
- package/dist/ui/assets/{apply-layout-Bn1R7u85.js → apply-layout-B0AnPvJo.js} +1 -1
- package/dist/ui/assets/{apps-ZExW_fDs.js → apps-3LBDpLXu.js} +1 -1
- package/dist/ui/assets/{azure-openai-Bq1gxkhj.js → azure-openai-Cye1lDSV.js} +1 -1
- package/dist/ui/assets/{azure-openai-VEnHlRuV.js → azure-openai-HqCDLaNq.js} +1 -1
- package/dist/ui/assets/{budget-usage-source-BBh4_xMQ.js → budget-usage-source--h4cY6Ul.js} +1 -1
- package/dist/ui/assets/{cdp-D4w-FTbd.js → cdp-BX0PiRAg.js} +1 -1
- package/dist/ui/assets/{cerebras-BIJOby0i.js → cerebras-BL4Mp561.js} +1 -1
- package/dist/ui/assets/{cerebras-BewEdNd6.js → cerebras-BzO5UDZf.js} +1 -1
- package/dist/ui/assets/{composer-speech-BMDdMTKQ.js → composer-speech-4JiTrymN.js} +1 -1
- package/dist/ui/assets/{connect-surface-79MIyGAY.js → connect-surface-COdJoI-e.js} +1 -1
- package/dist/ui/assets/{directed-approval-BcPMLVWo.js → directed-approval-Blbo1tMy.js} +1 -1
- package/dist/ui/assets/{fs-DsEo-CTs.js → fs-CxM_n_WI.js} +2 -2
- package/dist/ui/assets/{fs-BFK8H_mF.js → fs-luCL6DCO.js} +1 -1
- package/dist/ui/assets/{github-DZ4if-qZ.js → github-CkKjkah0.js} +1 -1
- package/dist/ui/assets/{github-BhmFLTRs.js → github-DYjXr1_m.js} +2 -2
- package/dist/ui/assets/{github-copilot-U9KFOJEm.js → github-copilot-BH7WyhE6.js} +1 -1
- package/dist/ui/assets/{github-copilot-DnRaZK_M.js → github-copilot-BgdxHbZb.js} +1 -1
- package/dist/ui/assets/{github-install-2Ug7GRRI.js → github-install-DCTLf8fO.js} +1 -1
- package/dist/ui/assets/{github-zip-BgbkZRd2.js → github-zip-B98l3J_a.js} +1 -1
- package/dist/ui/assets/{hear-CdVBwJxW.js → hear-BjVVAhs0.js} +1 -1
- package/dist/ui/assets/{help-02vmB0PN.js → help-S6yh95LF.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-DntrRTxU.js → js-realm-worker-DPLcRbzk.js} +1 -1
- package/dist/ui/assets/{kernel-worker-cOT-nF92.js → kernel-worker-CFvPuOAi.js} +33 -33
- package/dist/ui/assets/{local-llm-DO05qCpu.js → local-llm-BDyp_VE9.js} +1 -1
- package/dist/ui/assets/{local-llm-Ct2zoONz.js → local-llm-DRegic15.js} +1 -1
- package/dist/ui/assets/{main-Kp4I5rQC.js → main-DRyLg5pd.js} +3 -3
- package/dist/ui/assets/{main-cherry-CZYiEfWz.js → main-cherry-D1YCAckw.js} +1 -1
- package/dist/ui/assets/{mount-BlGkBXLX.js → mount-BehlIVTc.js} +1 -1
- package/dist/ui/assets/{mount-tnzaYGv8.js → mount-hVHVLao0.js} +3 -3
- package/dist/ui/assets/{mount-recovery-BkELRMZC.js → mount-recovery-Ds6xJnFc.js} +1 -1
- package/dist/ui/assets/{new-session-CK-dv8Uj.js → new-session-Cvy359ZG.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-DvfcDL78.js → oauth-bootstrap-0NJ1uts7.js} +2 -2
- package/dist/ui/assets/{onboarding-orchestrator-B5mIIefF.js → onboarding-orchestrator-Q2fKoNJZ.js} +1 -1
- package/dist/ui/assets/{openai-codex-DCX9X0rw.js → openai-codex-DqGAC_RJ.js} +1 -1
- package/dist/ui/assets/{openai-codex-DendXsAj.js → openai-codex-K0Kx4ldr.js} +1 -1
- package/dist/ui/assets/{openrouter-8be8gr7i.js → openrouter-BL1BgW8W.js} +1 -1
- package/dist/ui/assets/{openrouter-free-DD6Qaosl.js → openrouter-free-CY-4NfFi.js} +1 -1
- package/dist/ui/assets/{openrouter-free-BfMTb2W7.js → openrouter-free-OvrtzVRw.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-CmQPsN12.js → openrouter-oauth-B7IMQSSe.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-vKJGFRVJ.js → openrouter-oauth-CUoyHM94.js} +1 -1
- package/dist/ui/assets/{openrouter-nXMshaNH.js → openrouter-x2bz26jc.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-BENTXBlL.js → panel-rpc-handlers-Bcgk807g.js} +2 -2
- package/dist/ui/assets/{panelize-shell-toaG2G-p.js → panelize-shell-BgTzzpy_.js} +1 -1
- package/dist/ui/assets/{provider-Cc9fYW0-.js → provider-665TUltd.js} +2 -2
- package/dist/ui/assets/{provider-7ZZ5IAaH.js → provider-DesDs-vM.js} +1 -1
- package/dist/ui/assets/provider-settings-D4bmGLB0.js +1 -0
- package/dist/ui/assets/provider-store-access-BYNLuUjQ.js +1 -0
- package/dist/ui/assets/provider-store-access-DTu0j6hV.js +1 -0
- package/dist/ui/assets/{providers-CccaVwQm.js → providers-CFCRFvFH.js} +2 -2
- package/dist/ui/assets/{providers-DHrNt71c.js → providers-DdkKCDPr.js} +1 -1
- package/dist/ui/assets/{quick-llm-K9vKc8Ud.js → quick-llm-DDPHThwA.js} +1 -1
- package/dist/ui/assets/{recovery-screen-BYRgSmRA.js → recovery-screen-BxSagH2C.js} +1 -1
- package/dist/ui/assets/{run-DJMGsrtb.js → run-DP2klSX1.js} +1 -1
- package/dist/ui/assets/{run-DJPYQDHB.js → run-DVF88haQ.js} +1 -1
- package/dist/ui/assets/{run-CR5q-DCz.js → run-mty6BV1K.js} +2 -2
- package/dist/ui/assets/{setup-feature-flags-remote-C1qq4ZTv.js → setup-feature-flags-remote-BHnboyDd.js} +1 -1
- package/dist/ui/assets/sidecar-repair-BTfXbONN.js +1 -0
- package/dist/ui/assets/{silent-renew-backoff-Ccx1cluB.js → silent-renew-backoff-CefoN4SB.js} +1 -1
- package/dist/ui/assets/{skills-DlpDPS0V.js → skills-DQ9l8ZBo.js} +1 -1
- package/dist/ui/assets/slicc-version-Dao6QpwG.js +1 -0
- package/dist/ui/assets/{snapshot-features-BIZ6PQ0S.js → snapshot-features-CsC80g1q.js} +1 -1
- package/dist/ui/assets/{snapshot-CTWR15MP.js → snapshot-x1OXJvjv.js} +1 -1
- package/dist/ui/assets/{soundscape-CkW-Gcfy.js → soundscape-lMcnjSro.js} +1 -1
- package/dist/ui/assets/{speak-BrovnTsm.js → speak-DAMy1Kok.js} +1 -1
- package/dist/ui/assets/{sprinkle-manager-B5nR8afu.js → sprinkle-manager-jUfWlPSr.js} +1 -1
- package/dist/ui/assets/{sprinkle-renderer-D4iP6_5Z.js → sprinkle-renderer-DRjk0Axq.js} +1 -1
- package/dist/ui/assets/{state-XgRu82mi.js → state-DnkBl3YO.js} +1 -1
- package/dist/ui/assets/{store-CYMOamMP.js → store-CvgWI8Er.js} +1 -1
- package/dist/ui/assets/{store-C-UwOtjF.js → store-CyOgmeoj.js} +1 -1
- package/dist/ui/assets/{sudo-ocACPtd7.js → sudo-BUdJPcIH.js} +1 -1
- package/dist/ui/assets/{sync-dialog-CwJUqcs0.js → sync-dialog-D1W1SkvI.js} +1 -1
- package/dist/ui/assets/{transformers-env--mgWdw0R.js → transformers-env-DnyPjSfP.js} +1 -1
- package/dist/ui/assets/{tray-sidecar-l3_U61FU.js → tray-sidecar-Cq4YlygL.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-DlCzP4lD.js → upgrade-detection-DgoklRjO.js} +1 -1
- package/dist/ui/assets/{voice-reply-ChfXGGOt.js → voice-reply-oNIB61T4.js} +1 -1
- package/dist/ui/assets/{wc-attach-CnFlhppo.js → wc-attach-Dm3guiHt.js} +2 -2
- package/dist/ui/assets/{wc-extension-DeX-TlqV.js → wc-extension-B-HQw_fj.js} +2 -2
- package/dist/ui/assets/{wc-follower-CC8jLdo7.js → wc-follower-UnBMtKdu.js} +3 -3
- package/dist/ui/assets/{wc-follower-oauth-BUNweTOx.js → wc-follower-oauth-CUFehOmO.js} +1 -1
- package/dist/ui/assets/{wc-live-PsUc0Bl_.js → wc-live-B6vu9NGR.js} +6 -6
- package/dist/ui/assets/{wc-nav-BANvh-0o.js → wc-nav-BCixgrNu.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-DPixxui2.js → wc-onboarding-hbn2eX0f.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-DD_FPDH3.js → wc-placeholder-VxPXRa-X.js} +3 -3
- package/dist/ui/assets/{wc-settings-Cp5TJPHd.js → wc-settings-DjO1GovJ.js} +3 -3
- package/dist/ui/assets/{wc-shell-ngaz1xGJ.js → wc-shell-CdkXzmml.js} +3 -3
- package/dist/ui/assets/{wc-shortcut-config-DArDfV9f.js → wc-shortcut-config-DRFDW5Tg.js} +1 -1
- package/dist/ui/assets/{wc-shortcuts-CLBUOdsH.js → wc-shortcuts-udkJj992.js} +1 -1
- package/dist/ui/assets/{wc-sprinkles-B8KJmUa3.js → wc-sprinkles-CiVxUeGF.js} +2 -2
- package/dist/ui/assets/{wc-transcript-export-Dn0bSMDk.js → wc-transcript-export-BCh_MVB_.js} +2 -2
- package/dist/ui/assets/{wc-tray-BkFcSYHj.js → wc-tray-B33mq_SX.js} +4 -4
- package/dist/ui/assets/welcome-detection-DtOhe2WK.js +1 -0
- package/dist/ui/assets/{whisper-session-C_0wh0Zg.js → whisper-session-BsYu0J3h.js} +2 -2
- package/dist/ui/assets/{xai-grok-jQN78mEE.js → xai-grok-BULrVqKw.js} +1 -1
- package/dist/ui/assets/{xai-grok-DMHiFuln.js → xai-grok-Cud8PiSx.js} +1 -1
- package/dist/ui/index.html +3 -3
- package/dist/ui/packages/webapp/index.html +3 -3
- package/package.json +1 -1
- package/dist/ui/assets/provider-settings-DJ5mCQCp.js +0 -1
- package/dist/ui/assets/provider-store-access-DExU-wl1.js +0 -1
- package/dist/ui/assets/provider-store-access-jrpXOE2e.js +0 -1
- package/dist/ui/assets/sidecar-repair-C8zxoZAq.js +0 -1
- package/dist/ui/assets/slicc-version-Cjlsyldl.js +0 -1
- package/dist/ui/assets/welcome-detection-CM-e1SiO.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-CTWR15MP.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-DHrNt71c.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-OqSCLUiN.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 vt,h as yt,ht as R,i as bt,it as xt,j as St,jt as Ct,k as wt,kt as Tt,l as Et,lt as Dt,m as Ot,mt as kt,nt as At,o as jt,ot as Mt,p as Nt,pt as Pt,q as Ft,rt as ree,s as It,st as iee,t as Lt,tt as Rt,u as zt,ut as Bt,v as Vt,vt as Ht,w as Ut,wt as Wt,x as Gt,xt as z,y as Kt,yt as qt,z as Jt,zt as Yt}from"./core-BkHMrXyn.js";import{a as Xt}from"./models-4WTk3EBD.js";import{o as Zt,t as Qt}from"./compat-uEPf6-XW.js";import{t as $t}from"./__vite-browser-external-5eBdwsFd.js";import{n as en,r as tn}from"./attachments-u2K0aIPI.js";import{i as nn,n as rn,r as an,t as aee}from"./context-compaction-DRymamfD.js";import{n as oee,t as see}from"./mime-types-D7IV6i7k.js";import{t as on}from"./secrets-bridge-client-C3MaYf_O.js";import{t as sn}from"./image-markers-DuyWsic3.js";import{i as cn,r as cee}from"./budget-usage-source-BBh4_xMQ.js";import{a as ln,i as un,n as dn,t as fn}from"./path-utils-DNJG-zQf.js";import{a as pn,i as mn,n as hn,r as gn,t as _n}from"./agent-bridge-CcjfBcbz.js";import{C as vn,D as yn,O as bn,S as xn,T as Sn,_ as Cn,a as wn,c as Tn,d as En,f as Dn,g as On,h as kn,k as An,l as jn,m as Mn,n as Nn,o as Pn,p as Fn,r as In,s as Ln,t as Rn,u as zn,v as Bn,w as Vn,x as lee}from"./record-CUBwpX6h.js";import{a as Hn,c as Un,i as uee,l as Wn,n as Gn,o as dee,r as Kn,s as fee,t as qn,u as Jn}from"./descriptor-ZWA6ck4d.js";import{a as Yn,c as Xn,i as Zn,l as Qn,o as $n,r as er,s as tr,u as nr}from"./agent-message-to-chat-xGeYopQz.js";import{n as rr,t as ir}from"./thinking-level-5x0UAu9N.js";import{n as ar,t as or}from"./types-Dgm4REV3.js";import{i as sr}from"./mount-index-D9w_zMSm.js";import{a as cr,c as lr,i as ur,l as dr,n as fr,o as pr,r as mr,s as hr,u as gr}from"./mount-BlGkBXLX.js";import{o as _r}from"./mount-table-store-DrF_Ifaz.js";import{t as vr}from"./remote-cache-BE5T1-53.js";import{i as yr,n as br,r as xr}from"./fs-BFK8H_mF.js";import{r as Sr,t as Cr}from"./mount-recovery-BkELRMZC.js";import{r as wr,t as Tr}from"./key-CRGEBjHQ.js";import{a as Er,c as Dr,i as Or,n as kr,o as Ar,r as jr,s as Mr}from"./lick-urls-BX4Jyu_T.js";import{C as Nr,D as Pr,E as Fr,S as Ir,_ as Lr,a as Rr,b as zr,d as Br,g as Vr,h as Hr,m as Ur,n as Wr,o as Gr,r as Kr,s as qr,t as Jr,u as Yr,w as Xr,y as Zr}from"./db-DSIYsBgP.js";import"./tray-storage-keys-DbThbnIh.js";import"./tray-runtime-config-C3Ti4Pik.js";import{n as Qr,r as $r,t as ei}from"./slicc-version-Cjlsyldl.js";import{a as ti,i as ni,n as B,r as ri,t as pee}from"./browser-q8slJ96R.js";import{t as V}from"./subcommand-flags-BZi7j78Q.js";import{n as ii,r as ai,t as oi}from"./subcommand-help-CgO7wRS5.js";import{a as mee,i as hee,n as gee,r as _ee}from"./cost-command-B5aRQX4l.js";import{a as vee,c as si,d as yee,f as ci,h as li,i as bee,l as ui,m as di,n as fi,o as xee,p as pi,r as mi,s as See,t as Cee,u as wee}from"./sudoers-KgJRnN4b.js";import{a as hi,i as Tee,n as Eee,o as gi,r as _i,s as vi}from"./skills-DlpDPS0V.js";import{a as yi,c as bi,i as xi,l as Si,n as Ci,o as wi,r as Ti,t as Ei}from"./types-BfwydWt7.js";import{n as Di,t as Oi}from"./boundary-Cp9c_bPu.js";import"./rest-paths-Dia19u9P.js";import{t as ki}from"./html-B_Hg2WOy.js";import{n as Ai,t as ji}from"./llm-session-id-BZyXP_j2.js";import{a as Mi,i as Ni}from"./frozen-archive-format-CP0rleV0.js";import{n as Pi,r as Fi}from"./derive-TWFNEJkb.js";import{i as Ii,r as Li}from"./browser-2rCVqcqy.js";import{n as Ri,t as zi}from"./safe-buffer-OLJ0qaLt.js";import"./global-db-DJXlpNui.js";import{S as Bi,_ as Vi,a as Hi,b as Ui,c as Wi,d as Gi,f as Ki,g as qi,h as Ji,i as Yi,l as Xi,n as Zi,o as Qi,p as $i,r as ea,s as ta,t as na,u as ra,v as H,x as ia,y as aa}from"./state-XgRu82mi.js";import{a as oa,i as sa,r as ca,t as la}from"./git-config-Bdgu8kD2.js";import{a as ua,c as da,i as fa,o as pa,r as ma,s as ha,t as ga}from"./script-catalog-Bt94D0RP.js";import{t as _a}from"./process-manager-BkhAohXT.js";import{A as va,C as ya,F as ba,I as xa,N as Sa,P as Ca,_ as wa,a as Ta,b as Ea,c as Da,d as Oa,f as ka,g as Aa,h as ja,i as Ma,j as Na,l as Pa,m as Fa,n as Ia,o as La,p as Ra,r as za,s as Ba,t as Va,u as Ha,v as Ua,x as Wa,y as Ga}from"./shared-pVZLJOGO.js";import{t as Ka}from"./realm-browser-fetch-V3uggGbM.js";import{n as qa,t as Ja}from"./esbuild-wasm-CY2jFm-D.js";import{n as Ya,t as Xa}from"./wasm-compiler-Ct7QZURL.js";import{n as Za,r as Qa,t as $a}from"./just-bash-compat-_TMo8UnL.js";import{_ as eo,a as to,c as no,f as ro,g as io,h as ao,l as oo,m as so,n as co,p as lo,r as uo,u as fo,v as po,y as mo}from"./github-zip-BgbkZRd2.js";import{a as ho,c as go,d as _o,f as vo,i as yo,l as bo,n as xo,o as So,p as Co,r as wo,s as To,u as Eo}from"./github-install-2Ug7GRRI.js";import{n as Dee,t as Oee}from"./magick-wasm-DrHkiveP.js";import{i as kee,n as Do,r as Aee,t as Oo}from"./pdf-raster-BWk6ezTX.js";import{a as jee,c as Mee,d as Nee,f as Pee,i as Fee,l as Iee,n as Lee,o as Ree,p as zee,r as ko,s as Bee,t as Vee,u as Hee}from"./installer-CTX50_zb.js";import{n as Ao,r as jo,t as Uee}from"./extension-media-capture-BwxRQ-WA.js";import{t as Wee}from"./local-llm-Ct2zoONz.js";import{t as Gee}from"./client-C6Cmi9c4.js";import{t as Kee}from"./redirect-uri-BKkf61lT.js";let Mo=null;function qee(e){Mo=e!==null&&Number.isFinite(e)&&e>0?e:null}function Jee(){if(Mo!==null)return Mo;let e=globalThis.performance?.timeOrigin;return typeof e==`number`&&Number.isFinite(e)&&e>0?e:Date.now()}const Yee=[`/workspace`,`/shared`,`/scoops`,`/home`];var No=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 Po(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 Fo=r(`cdp`);function Xee(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 Zee=class{ws=null;nextId=1;_superseded=!1;pending=new No;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,Fo.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Fo.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(),Fo.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),Fo.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 Po(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;Fo.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Fo.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;Fo.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,Fo.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?Fo.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):Fo.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(Xee(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{}}}},Io=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 Lo(e,t){if(e?.aborted)throw new Io(t)}function Qee(e,t){return e?{signal:e,error:()=>new Io(t)}:void 0}function $ee(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new Io(n));return}let a=()=>{clearTimeout(o),i(new Io(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function ete(e,t,n){return t?t.aborted?Promise.reject(new Io(n)):new Promise((r,i)=>{let a=()=>i(new Io(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 Ro=r(`har-recorder`);var tte=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)}`;Lo(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Lo(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Lo(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}`),Ro.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=>{Ro.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=>{Ro.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 nte(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Ro.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 Ro.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)),Ro.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 Ro.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 nte(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){Ro.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Ro.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const zo=`(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-x1OXJvjv.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-DdkKCDPr.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-BSIs8eWH.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 vt,h as yt,ht as R,i as bt,it as xt,j as St,jt as Ct,k as wt,kt as Tt,l as Et,lt as Dt,m as Ot,mt as kt,nt as At,o as jt,ot as Mt,p as Nt,pt as Pt,q as Ft,rt as ree,s as It,st as iee,t as Lt,tt as Rt,u as zt,ut as Bt,v as Vt,vt as Ht,w as Ut,wt as Wt,x as Gt,xt as z,y as Kt,yt as qt,z as Jt,zt as Yt}from"./core-BkHMrXyn.js";import{a as Xt}from"./models-4WTk3EBD.js";import{o as Zt,t as Qt}from"./compat-uEPf6-XW.js";import{t as $t}from"./__vite-browser-external-5eBdwsFd.js";import{n as en,r as tn}from"./attachments-u2K0aIPI.js";import{i as nn,n as rn,r as an,t as aee}from"./context-compaction-DRymamfD.js";import{n as oee,t as see}from"./mime-types-D7IV6i7k.js";import{t as on}from"./secrets-bridge-client-C3MaYf_O.js";import{t as sn}from"./image-markers-DuyWsic3.js";import{i as cn,r as cee}from"./budget-usage-source--h4cY6Ul.js";import{a as ln,i as un,n as dn,t as fn}from"./path-utils-DNJG-zQf.js";import{a as pn,i as mn,n as hn,r as gn,t as _n}from"./agent-bridge-DEABZego.js";import{C as vn,D as yn,O as bn,S as xn,T as Sn,_ as Cn,a as wn,c as Tn,d as En,f as Dn,g as On,h as kn,k as An,l as jn,m as Mn,n as Nn,o as Pn,p as Fn,r as In,s as Ln,t as Rn,u as zn,v as Bn,w as Vn,x as lee}from"./record-CUBwpX6h.js";import{a as Hn,c as Un,i as uee,l as Wn,n as Gn,o as dee,r as Kn,s as fee,t as qn,u as Jn}from"./descriptor-ZWA6ck4d.js";import{a as Yn,c as Xn,i as Zn,l as Qn,o as $n,r as er,s as tr,u as nr}from"./agent-message-to-chat-xGeYopQz.js";import{n as rr,t as ir}from"./thinking-level-5x0UAu9N.js";import{n as ar,t as or}from"./types-Dgm4REV3.js";import{i as sr}from"./mount-index-D9w_zMSm.js";import{a as cr,c as lr,i as ur,l as dr,n as fr,o as pr,r as mr,s as hr,u as gr}from"./mount-BehlIVTc.js";import{o as _r}from"./mount-table-store-DrF_Ifaz.js";import{t as vr}from"./remote-cache-BE5T1-53.js";import{i as yr,n as br,r as xr}from"./fs-luCL6DCO.js";import{r as Sr,t as Cr}from"./mount-recovery-Ds6xJnFc.js";import{r as wr,t as Tr}from"./key-CRGEBjHQ.js";import{a as Er,c as Dr,i as Or,n as kr,o as Ar,r as jr,s as Mr}from"./lick-urls-BX4Jyu_T.js";import{C as Nr,D as Pr,E as Fr,S as Ir,_ as Lr,a as Rr,b as zr,d as Br,g as Vr,h as Hr,m as Ur,n as Wr,o as Gr,r as Kr,s as qr,t as Jr,u as Yr,w as Xr,y as Zr}from"./db-DSIYsBgP.js";import"./tray-storage-keys-DbThbnIh.js";import"./tray-runtime-config-C3Ti4Pik.js";import{n as Qr,r as $r,t as ei}from"./slicc-version-Dao6QpwG.js";import{a as ti,i as ni,n as B,r as ri,t as pee}from"./browser-q8slJ96R.js";import{t as V}from"./subcommand-flags-BZi7j78Q.js";import{n as ii,r as ai,t as oi}from"./subcommand-help-CgO7wRS5.js";import{a as mee,i as hee,n as gee,r as _ee}from"./cost-command-B5aRQX4l.js";import{a as vee,c as si,d as yee,f as ci,h as li,i as bee,l as ui,m as di,n as fi,o as xee,p as pi,r as mi,s as See,t as Cee,u as wee}from"./sudoers-KgJRnN4b.js";import{a as hi,i as Tee,n as Eee,o as gi,r as _i,s as vi}from"./skills-DQ9l8ZBo.js";import{a as yi,c as bi,i as xi,l as Si,n as Ci,o as wi,r as Ti,t as Ei}from"./types-BfwydWt7.js";import{n as Di,t as Oi}from"./boundary-Cp9c_bPu.js";import"./rest-paths-Dia19u9P.js";import{t as ki}from"./html-B_Hg2WOy.js";import{n as Ai,t as ji}from"./llm-session-id-BZyXP_j2.js";import{a as Mi,i as Ni}from"./frozen-archive-format-CP0rleV0.js";import{n as Pi,r as Fi}from"./derive-TWFNEJkb.js";import{i as Ii,r as Li}from"./browser-2rCVqcqy.js";import{n as Ri,t as zi}from"./safe-buffer-OLJ0qaLt.js";import"./global-db-DJXlpNui.js";import{S as Bi,_ as Vi,a as Hi,b as Ui,c as Wi,d as Gi,f as Ki,g as qi,h as Ji,i as Yi,l as Xi,n as Zi,o as Qi,p as $i,r as ea,s as ta,t as na,u as ra,v as H,x as ia,y as aa}from"./state-DnkBl3YO.js";import{a as oa,i as sa,r as ca,t as la}from"./git-config-Bdgu8kD2.js";import{a as ua,c as da,i as fa,o as pa,r as ma,s as ha,t as ga}from"./script-catalog-Bt94D0RP.js";import{t as _a}from"./process-manager-BkhAohXT.js";import{A as va,C as ya,F as ba,I as xa,N as Sa,P as Ca,_ as wa,a as Ta,b as Ea,c as Da,d as Oa,f as ka,g as Aa,h as ja,i as Ma,j as Na,l as Pa,m as Fa,n as Ia,o as La,p as Ra,r as za,s as Ba,t as Va,u as Ha,v as Ua,x as Wa,y as Ga}from"./shared-pVZLJOGO.js";import{t as Ka}from"./realm-browser-fetch-V3uggGbM.js";import{n as qa,t as Ja}from"./esbuild-wasm-CY2jFm-D.js";import{n as Ya,t as Xa}from"./wasm-compiler-Ct7QZURL.js";import{n as Za,r as Qa,t as $a}from"./just-bash-compat-_TMo8UnL.js";import{_ as eo,a as to,c as no,f as ro,g as io,h as ao,l as oo,m as so,n as co,p as lo,r as uo,u as fo,v as po,y as mo}from"./github-zip-B98l3J_a.js";import{a as ho,c as go,d as _o,f as vo,i as yo,l as bo,n as xo,o as So,p as Co,r as wo,s as To,u as Eo}from"./github-install-DCTLf8fO.js";import{n as Dee,t as Oee}from"./magick-wasm-DrHkiveP.js";import{i as kee,n as Do,r as Aee,t as Oo}from"./pdf-raster-BWk6ezTX.js";import{a as jee,c as Mee,d as Nee,f as Pee,i as Fee,l as Iee,n as Lee,o as Ree,p as zee,r as ko,s as Bee,t as Vee,u as Hee}from"./installer-CTX50_zb.js";import{n as Ao,r as jo,t as Uee}from"./extension-media-capture-BwxRQ-WA.js";import{t as Wee}from"./local-llm-DRegic15.js";import{t as Gee}from"./client-C6Cmi9c4.js";import{t as Kee}from"./redirect-uri-BKkf61lT.js";let Mo=null;function qee(e){Mo=e!==null&&Number.isFinite(e)&&e>0?e:null}function Jee(){if(Mo!==null)return Mo;let e=globalThis.performance?.timeOrigin;return typeof e==`number`&&Number.isFinite(e)&&e>0?e:Date.now()}const Yee=[`/workspace`,`/shared`,`/scoops`,`/home`];var No=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 Po(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 Fo=r(`cdp`);function Xee(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 Zee=class{ws=null;nextId=1;_superseded=!1;pending=new No;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,Fo.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Fo.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(),Fo.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),Fo.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 Po(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;Fo.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Fo.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;Fo.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,Fo.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?Fo.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):Fo.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(Xee(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{}}}},Io=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 Lo(e,t){if(e?.aborted)throw new Io(t)}function Qee(e,t){return e?{signal:e,error:()=>new Io(t)}:void 0}function $ee(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new Io(n));return}let a=()=>{clearTimeout(o),i(new Io(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function ete(e,t,n){return t?t.aborted?Promise.reject(new Io(n)):new Promise((r,i)=>{let a=()=>i(new Io(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 Ro=r(`har-recorder`);var tte=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)}`;Lo(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Lo(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Lo(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}`),Ro.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=>{Ro.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=>{Ro.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 nte(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Ro.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 Ro.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)),Ro.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 Ro.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 nte(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){Ro.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Ro.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const zo=`(function() {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
// ===== DOM Utilities =====
|
|
@@ -988,7 +988,7 @@ Rules:
|
|
|
988
988
|
- Do NOT add preamble, commentary, or any heading other than the single consolidated one.`}],timestamp:Date.now()},a=await Qt(e.model,{systemPrompt:r,messages:[i]},{apiKey:e.apiKey,maxTokens:4096,headers:e.headers,signal:e.signal});if(a.stopReason===`error`)throw Error(`Restructure call failed: ${a.errorMessage||`Unknown error`}`);let o=a.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
989
989
|
`).trim();if(!o)throw Error(`Restructure call returned empty content`);return`${t}${t.length===0||t.endsWith(`
|
|
990
990
|
`)?``:`
|
|
991
|
-
`}${o}\n`}async function WS(e){if(!e.model||!e.apiKey)return{restructured:!1,reason:`no-llm`};let t=e.memoryPath??RS,n=``;try{let r=await e.vfs.readFile(t,{encoding:`utf-8`});n=typeof r==`string`?r:new TextDecoder().decode(r)}catch{return{restructured:!1,reason:`missing-file`}}let r=await HS(e.vfs),i=BS(r),a=i*1.25;if(n.length<=a)return{restructured:!1,reason:`under-threshold`};LS.info(`Cone memory over threshold — restructuring`,{size:n.length,budget:i,threshold:a,sessionCount:r});try{let r=await US({currentContent:n,budget:i,model:e.model,apiKey:e.apiKey,headers:e.headers,signal:e.signal});return await e.vfs.writeFile(t,r),LS.info(`Cone memory restructured`,{before:n.length,after:r.length}),{restructured:!0}}catch(e){return LS.warn(`Cone memory restructure failed — leaving appended content in place`,{error:e instanceof Error?e.message:String(e)}),{restructured:!1,reason:`error`}}}const GS=`focus`,KS={type:`leaf`,surfaceId:`chat`};function qS(e,t={},n={}){return{zones:{top:null,left:null,middle:null,right:null,bottom:null,...e},rowFr:{top:1,center:1,bottom:1,...n},colFr:{left:1,middle:1,right:1,...t}}}const JS={focus:{name:`focus`,tree:qS({left:KS},{left:3,middle:1})}};function YS(e){return JS[e]??null}const XS=r(`skills`),ZS=Object.assign({"/packages/vfs-root/AGENTS.md":()=>import(`./CLAUDE-DM1onrcU.js`).then(e=>e.default),"/packages/vfs-root/CLAUDE.md":()=>import(`./CLAUDE-DM1onrcU.js`).then(e=>e.default),"/packages/vfs-root/etc/APPROVALS.md":()=>import(`./APPROVALS-CoZKeFYV.js`).then(e=>e.default),"/packages/vfs-root/etc/slicc/keys.json":()=>import(`./keys-BMebW-sj.js`).then(e=>e.default),"/packages/vfs-root/shared/CLAUDE.md":()=>import(`./CLAUDE-CWMPcWVI.js`).then(e=>e.default),"/packages/vfs-root/shared/MEMORY.md":()=>import(`./MEMORY-BEEBDXkY.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/connect-llm.shtml":()=>import(`./connect-llm-FevTa-aV.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/welcome.shtml":()=>import(`./welcome-CyCMJDqG.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/automation/SKILL.md":()=>import(`./SKILL-DA3Jh760.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/biome/SKILL.md":()=>import(`./SKILL-BNnF2azP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/cherry/SKILL.md":()=>import(`./SKILL-BTVvFyRd.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/delegation/SKILL.md":()=>import(`./SKILL-C75-EDP7.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/SKILL.md":()=>import(`./SKILL-Br-bRfNe.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/patterns.md":()=>import(`./patterns-ChiGbijt.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dns/SKILL.md":()=>import(`./SKILL-BKyxMoME.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/ffmpeg/SKILL.md":()=>import(`./SKILL-C6co9TnL.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/handoff/SKILL.md":()=>import(`./SKILL-oOIS8LAm.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/image-processing/SKILL.md":()=>import(`./SKILL-DpjPj8Lx.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/meminfo/SKILL.md":()=>import(`./SKILL-DXIigmDy.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/mount/SKILL.md":()=>import(`./SKILL-BPuaCaUr.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/package-execution/SKILL.md":()=>import(`./SKILL-BS0BC3cr.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/playwright-cli/SKILL.md":()=>import(`./SKILL-saWWhAfi.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":()=>import(`./SKILL-CJIzo9DA.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/jsh-runtime-extensions.md":()=>import(`./jsh-runtime-extensions-6coWmZ2q.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/slicc/SKILL.md":()=>import(`./SKILL-CRLGKQWi.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/SKILL.md":()=>import(`./SKILL-Dkk5iZlJ.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/icon-example.md":()=>import(`./icon-example-LUkiEXyS.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/style-guide.md":()=>import(`./style-guide-HRBOnsqo.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/ssh/SKILL.md":()=>import(`./SKILL-BflWplWz.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/theme/SKILL.md":()=>import(`./SKILL-Dh6a4Qu2.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/transcript-export/SKILL.md":()=>import(`./SKILL-CkfptFag.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/upgrade/SKILL.md":()=>import(`./SKILL-DGS-d3qt.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/v86/SKILL.md":()=>import(`./SKILL-
|
|
991
|
+
`}${o}\n`}async function WS(e){if(!e.model||!e.apiKey)return{restructured:!1,reason:`no-llm`};let t=e.memoryPath??RS,n=``;try{let r=await e.vfs.readFile(t,{encoding:`utf-8`});n=typeof r==`string`?r:new TextDecoder().decode(r)}catch{return{restructured:!1,reason:`missing-file`}}let r=await HS(e.vfs),i=BS(r),a=i*1.25;if(n.length<=a)return{restructured:!1,reason:`under-threshold`};LS.info(`Cone memory over threshold — restructuring`,{size:n.length,budget:i,threshold:a,sessionCount:r});try{let r=await US({currentContent:n,budget:i,model:e.model,apiKey:e.apiKey,headers:e.headers,signal:e.signal});return await e.vfs.writeFile(t,r),LS.info(`Cone memory restructured`,{before:n.length,after:r.length}),{restructured:!0}}catch(e){return LS.warn(`Cone memory restructure failed — leaving appended content in place`,{error:e instanceof Error?e.message:String(e)}),{restructured:!1,reason:`error`}}}const GS=`focus`,KS={type:`leaf`,surfaceId:`chat`};function qS(e,t={},n={}){return{zones:{top:null,left:null,middle:null,right:null,bottom:null,...e},rowFr:{top:1,center:1,bottom:1,...n},colFr:{left:1,middle:1,right:1,...t}}}const JS={focus:{name:`focus`,tree:qS({left:KS},{left:3,middle:1})}};function YS(e){return JS[e]??null}const XS=r(`skills`),ZS=Object.assign({"/packages/vfs-root/AGENTS.md":()=>import(`./CLAUDE-DM1onrcU.js`).then(e=>e.default),"/packages/vfs-root/CLAUDE.md":()=>import(`./CLAUDE-DM1onrcU.js`).then(e=>e.default),"/packages/vfs-root/etc/APPROVALS.md":()=>import(`./APPROVALS-CoZKeFYV.js`).then(e=>e.default),"/packages/vfs-root/etc/slicc/keys.json":()=>import(`./keys-BMebW-sj.js`).then(e=>e.default),"/packages/vfs-root/shared/CLAUDE.md":()=>import(`./CLAUDE-CWMPcWVI.js`).then(e=>e.default),"/packages/vfs-root/shared/MEMORY.md":()=>import(`./MEMORY-BEEBDXkY.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/connect-llm.shtml":()=>import(`./connect-llm-FevTa-aV.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/welcome.shtml":()=>import(`./welcome-CyCMJDqG.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/automation/SKILL.md":()=>import(`./SKILL-DA3Jh760.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/biome/SKILL.md":()=>import(`./SKILL-BNnF2azP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/cherry/SKILL.md":()=>import(`./SKILL-BTVvFyRd.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/delegation/SKILL.md":()=>import(`./SKILL-C75-EDP7.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/SKILL.md":()=>import(`./SKILL-Br-bRfNe.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/patterns.md":()=>import(`./patterns-ChiGbijt.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dns/SKILL.md":()=>import(`./SKILL-BKyxMoME.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/ffmpeg/SKILL.md":()=>import(`./SKILL-C6co9TnL.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/handoff/SKILL.md":()=>import(`./SKILL-oOIS8LAm.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/image-processing/SKILL.md":()=>import(`./SKILL-DpjPj8Lx.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/meminfo/SKILL.md":()=>import(`./SKILL-DXIigmDy.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/mount/SKILL.md":()=>import(`./SKILL-BPuaCaUr.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/package-execution/SKILL.md":()=>import(`./SKILL-BS0BC3cr.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/playwright-cli/SKILL.md":()=>import(`./SKILL-saWWhAfi.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":()=>import(`./SKILL-CJIzo9DA.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/jsh-runtime-extensions.md":()=>import(`./jsh-runtime-extensions-6coWmZ2q.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/slicc/SKILL.md":()=>import(`./SKILL-CRLGKQWi.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/SKILL.md":()=>import(`./SKILL-Dkk5iZlJ.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/icon-example.md":()=>import(`./icon-example-LUkiEXyS.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/style-guide.md":()=>import(`./style-guide-HRBOnsqo.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/ssh/SKILL.md":()=>import(`./SKILL-BflWplWz.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/theme/SKILL.md":()=>import(`./SKILL-Dh6a4Qu2.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/transcript-export/SKILL.md":()=>import(`./SKILL-CkfptFag.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/upgrade/SKILL.md":()=>import(`./SKILL-DGS-d3qt.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/v86/SKILL.md":()=>import(`./SKILL-B-lyKDjk.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/welcome/SKILL.md":()=>import(`./SKILL-D40-t9w0.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/workflows/SKILL.md":()=>import(`./SKILL-Bt-RhG0L.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/x-search/SKILL.md":()=>import(`./SKILL-CED8RXQP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/x-search/x_search.jsh":()=>import(`./x_search-C-5p00-C.js`).then(e=>e.default)}),QS=Object.assign({"/packages/vfs-root/shared/sounds/chime.mp3":()=>import(`./chime-CPc6qSh5.js`).then(e=>e.default)});function $S(e){let t=e.split(`,`)[1],n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}const eC={};function tC(){let e={};for(let[t,n]of Object.entries(ZS))e[t]=n;for(let[t,n]of Object.entries(QS))e[t]=async()=>$S(await n());for(let[t,n]of Object.entries(eC)){let r=t.replace(`/packages/dev-tools/vfs-dev-skills/`,`/packages/vfs-root/workspace/skills/`);e[r]=()=>Promise.resolve(n)}return e}function nC(e){let t=new Map;for(let n of e){if(t.has(n.metadata.name)){XS.debug(`Skipped shadowed runtime skill`,{name:n.metadata.name,path:n.path,winnerPath:t.get(n.metadata.name)?.path});continue}t.set(n.metadata.name,n)}return Array.from(t.values())}function rC(e){let t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);if(!t)return{metadata:{},body:e};let[,n,r]=t,i={};for(let e of n.split(`
|
|
992
992
|
`)){let t=e.match(/^(\w[\w-]*):\s*(.*)$/);if(!t)continue;let[,n,r]=t,a=r.trim();switch(n){case`name`:i.name=a;break;case`description`:i.description=a;break;case`allowed-tools`:i.allowedTools=a.split(`,`).map(e=>e.trim());break;case`layout`:i.layout=a;break;case`theme`:i.theme=a}}return{metadata:i,body:r}}async function iC(e,t){let n=await aC(e,t),r=await oC(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=nC([...i,...r,...a]);return XS.info(`Skills loaded`,{count:o.length,dir:t}),o}async function aC(e,t){let n=await Eee(e,t),r=[];for(let t of n)if(t.skillFilePath)try{let{metadata:n,body:i}=rC(await e.readTextFile(t.skillFilePath)),a=n.name||t.name;r.push({metadata:{name:a,description:n.description||t.description||``,allowedTools:n.allowedTools},content:i,path:t.skillFilePath,source:t.source}),XS.debug(`Loaded discovered skill`,{name:a,path:t.skillFilePath,source:t.source})}catch{XS.debug(`Failed to load discovered skill`,{name:t.name,path:t.skillFilePath})}return r}async function oC(e,t){let n=[];try{let r=await e.readDir(t);for(let i of r)if(i.type===`file`&&i.name.endsWith(`.md`)){let r=`${t}/${i.name}`;try{let t=await e.readFile(r,{encoding:`utf-8`}),{metadata:a,body:o}=rC(typeof t==`string`?t:new TextDecoder().decode(t)),s=a.name||i.name.replace(`.md`,``);n.push({metadata:{name:s,description:a.description||``,allowedTools:a.allowedTools},content:o,path:r}),XS.debug(`Loaded standalone skill`,{name:s,path:r})}catch{}}}catch{XS.debug(`Standalone skills directory not found`,{dir:t})}return n}function sC(e){return e.length===0?``:`
|
|
993
993
|
---
|
|
994
994
|
AVAILABLE SKILLS
|
|
@@ -1643,7 +1643,7 @@ except BaseException:
|
|
|
1643
1643
|
`)?a:`${a}\n`;t(n>0?`${` `.repeat(n)}${o}`:o)}function uH(e,t,n){let r=iH(n);if(e.has(r)){t(`Label '${r}' already exists for console.time()`);return}e.set(r,aH())}function dH(e,t,n,r){let i=iH(r),a=e.get(i);if(a===void 0){t(`No such label '${i}' for console.timeEnd()`);return}e.delete(i),n(`${i}: ${oH(aH()-a)}`)}function fH(e,t,n,r,i){let a=iH(r),o=e.get(a);if(o===void 0){t(`No such label '${a}' for console.timeLog()`);return}let s=`${a}: ${oH(aH()-o)}`;i.length===0?n(s):n(s,...i)}function pH(e,t,n){let r=iH(n),i=(e.get(r)??0)+1;e.set(r,i),t(`${r}: ${i}`)}function mH(e,t,n){let r=iH(n);if(!e.has(r)){t(`Count for '${r}' does not exist`);return}e.set(r,0)}function hH(e,t,n){n.length>0&&t(...n),e.depth+=1}function gH(e){e.depth>0&&--e.depth}function _H(e,t){let n=new Map,r=new Map,i={depth:0},a=(...t)=>sH(e,i.depth,t),o=(...e)=>sH(t,i.depth,e),s=(...e)=>hH(i,a,e);return{log:a,info:a,debug:a,dirxml:a,table:a,warn:o,error:o,dir:(e,t)=>a(e),clear:()=>void 0,group:s,groupCollapsed:s,groupEnd:()=>gH(i),assert:(e,...t)=>cH(o,e,t),trace:(...e)=>lH(o,t,i.depth,e),time:e=>uH(r,o,e),timeEnd:e=>dH(r,o,a,e),timeLog:(e,...t)=>fH(r,o,a,e,t),count:e=>pH(n,a,e),countReset:e=>mH(n,o,e)}}function vH(e,t,n){let r=!!e.env?.NO_COLOR,i=!1,a=0,o=e=>{i=!0,a=e},s=bH(e.stdin??``,o),c=JV(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:ba},version:`v${ba}`,platform:`linux`,arch:`x64`,cwd:()=>e.cwd,exit:e=>{let t=Number.isFinite(e)?Number(e):0;throw o(t),new tH(t)},stdin:s,stdout:l,stderr:u},getDidCallProcessExit:()=>i,getExitCode:()=>a,recordExit:o}}var yH=class extends KI.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 tH){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 bH(e,t){return new yH(e,t)}function xH(e){if(e===``)return[];let t=e.split(`
|
|
1644
1644
|
`);return t[t.length-1]===``&&t.pop(),t.map(e=>e.endsWith(`\r`)?e.slice(0,-1):e)}function SH(e){if(typeof e==`string`)return e;if(e&&typeof e.read==`function`){let t=e.read();return typeof t==`string`?t:``}return``}function CH(e){return new TextDecoder(`utf-8`).decode(YF(e))}function wH(e){if(e&&typeof e.write==`function`)return e}var TH=class extends BI{terminal=!1;lines;cursor=0;closed=!1;flushScheduled=!1;output;onExit;constructor(e,t,n){super(),this.lines=xH(CH(SH(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 tH&&this.onExit){this.closed=!0,this.onExit(e.code);return}throw e}}};function EH(e){let t=(t,n)=>{let r,i;if(t&&typeof t==`object`&&`input`in t){let e=t;r=e.input,i=wH(e.output)}else r=t,i=wH(n);if(r==null)throw TypeError(`readline.createInterface: an 'input' stream is required`);return new TH(r,i,e)},n=(...e)=>{let t=e[e.length-1];return typeof t==`function`&&queueMicrotask(()=>t()),!0},r={createInterface:t,Interface:TH,emitKeypressEvents:()=>void 0,cursorTo:n,moveCursor:n,clearLine:n,clearScreenDown:n};return{...r,promises:r}}var DH=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`?`: ${OH(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 OH(e){try{return JSON.stringify(e)}catch{return String(e)}}function kH(e){return new Promise(t=>setTimeout(t,e))}function AH(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 jH(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?AH(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 NH(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`application/json`)||/[+/]json(;|$|\s)/.test(t)}function PH(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 FH(e){if(NH(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 IH(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 LH(e,t){return Object.keys(e).some(e=>e.toLowerCase()===t.toLowerCase())}async function RH(e,t,n){let r=await t(n);r&&!LH(e,`authorization`)&&(e.Authorization=`Bearer ${r}`)}function zH(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 BH(e,t){return{body:t,headers:Object.fromEntries(e.headers.entries()),status:e.status}}async function VH(e,t){let n=await FH(e);return t?BH(e,n):n}async function HH(e,t){let n=await FH(e).catch(()=>null);throw new DH(e.status,e.statusText,t,n)}function UH(e,t){let n=PH(e.headers.get(`retry-after`));return n===null?500*2**t:n}async function WH(e,t,n,r){let i=null;for(let a=0;a<e.maxAttempts;a++){let{signal:o,clearTimeout:s}=zH(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 VH(l,r.raw);if(!(a+1<e.maxAttempts&&e.retryOn.has(l.status)))return HH(l,t);await e.sleep(UH(l,a))}if(i)return HH(i,t);throw Error(`http: no attempts made for ${n.method??`GET`} ${t}`)}function GH(e){let t=e.sleep??kH;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=jH(n.baseUrl,o,s.params),l=MH(n.headers,s.headers);n.token&&await RH(l,n.token,{method:a,path:o,url:c});let u=IH(s.body,l),d={method:a,headers:l};return u!==void 0&&(d.body=u),WH({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 KH(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 qH(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`,KH(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 JH(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(qH(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 YH(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 XH(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=YH(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 ZH(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 QH(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 QH(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(lr(e)){let t=await hr(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 $H(e){return{findTab:t=>e.call(`browser`,`findTab`,[tU(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,nU(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[YH(t),eU(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[YH(t),eU(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[YH(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[YH(t),n]),fetch:(t,n,r={})=>Ka(n,r).then(n=>e.call(`browser`,`evalAsync`,[YH(t),n])),websocket:XH(e)}}function eU(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 tU(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 nU(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function rU(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function iU(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:rU(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}const aU=new Set([204,205,304]),oU=new Set([`content-encoding`,`transfer-encoding`,`content-length`]);function sU(e,t){let n=cU(e.body),r=lU(e.headers),i=aU.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 uU(a,n),a}function cU(e){return e.byteLength===0?new Uint8Array:e.slice()}function lU(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(!oU.has(n.toLowerCase()))try{t.set(n,r)}catch{}return t}function uU(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 dU(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 fU(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function pU(e){return e==null?[]:Array.isArray(e)?e:[e]}function mU(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:fU(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,dU(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,dU(r)]),receiveFeatureReport:async t=>fU((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 hU(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>mU(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[pU(t)]))[0];if(!n)throw Error(`No device selected.`);return mU(e,n)}}}function gU(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 _U=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 };`)}},vU=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=gU(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 _U(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 _U(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?.())}},yU=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 vU(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()}},bU=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 vU(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 yU(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 xU(e){let t=async t=>new bU(e),n=async(t,n)=>new bU(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}const SU=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`]),CU={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 wU(e,t){let n=CU[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function TU(e){return{...e,time:$V,fmt:EI,pool:YV}}function EU(e,t){return e?.startsWith(`/`)?eH(e):t}function DU(e){return e.includes(`require`)||e.includes(`import`)||/(?:^|[;\n}])\s*export\b/.test(e)}async function OU(e,t,n,r){return DU(t)?e.call(`module`,`buildGraph`,[t,EU(r,n),r]):{files:[],entryMap:{},edges:{},edgeErrors:{},errors:{}}}function kU(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 AU(e){return{playwright:xU(e)}}function jU(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o,shimmedPackages:s={},nodeReadline:c,nodeOsModule:l=dR,nodeUtilModule:u=uL}=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=iR({requireFrom:(e,t)=>b(e,t),resolveFrom:(e,t)=>y(e,t)}),h=e=>{if(typeof e==`string`&&e.startsWith(`sliccy:`))return{hit:!0,value:PU(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,nodeModule:m});if(a.hit)return a;if(SU.has(t))throw wU(e,t);if(Ca.has(t))throw IU(e,t);return t in s?{hit:!0,value:s[t]}:{hit:!1}},g=(e,n,r)=>{let i=h(n);if(i.hit)return i.value;let a=e?.[n];if(a)return _(a);let o=r===null?t.errors[n]:t.edgeErrors?.[r]?.[n];throw o?Error(o):NU(n)};function _(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=>g(t.edges[e],n,e),c=eH(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`&&kU(o.exports),o.exports}function v(e){return d.has(e)}function y(e,n){if(xa(n))return n;let r=t.edges[e]?.[n];if(r)return r;let i=eH(e);if(rR(n)){let e=tR(i,n,v);if(e)return e}else{let e=nR(i,n,v);if(e)return e}let a=t.edgeErrors?.[e]?.[n];throw a?Error(a):NU(n)}function b(e,t){let n=h(t);return n.hit?n.value:_(y(e,t))}return{require:e=>g(t.entryMap,e,null)}}function MU(e,t){let{fsBridge:n,processShim:r,childProcess:i,nodeOsModule:a,nodeUtilModule:o,nodeReadline:s,nodeModule:c}=t;return e===`fs`||e===`fs/promises`?{hit:!0,value:n}:e===`path`?{hit:!0,value:KL}:e===`crypto`?{hit:!0,value:FL}: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:RI}:e===`assert/strict`?{hit:!0,value:LI}:e===`util`?{hit:!0,value:o}:e===`events`?{hit:!0,value:VI}:e===`os`?{hit:!0,value:a}:e===`tty`?{hit:!0,value:fR}:e===`stream`?{hit:!0,value:KI}:e===`url`?{hit:!0,value:YL}:e===`zlib`?{hit:!0,value:KV}:e===`readline`&&s?{hit:!0,value:s}:e===`readline/promises`&&s?{hit:!0,value:s.promises}:e===`module`&&c?{hit:!0,value:c}:{hit:!1}}function NU(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 PU(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 FU={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function IU(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${FU[t]||``}`)}async function LU(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";
|
|
1645
1645
|
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof tH?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function RU(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?dU(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,dU(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function zU(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>RU(e,t)),request:async t=>RU(e,await e.call(`serial`,`request`,[pU(t)]))}}function BU(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 VU(e,t){let n=t.handle,r=e=>({status:e.status,data:fU(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,dU(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,dU(r)])}}function HU(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>VU(e,t)),request:async t=>VU(e,await e.call(`usb`,`request`,[pU(t)]))}}function UU(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function WU(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 GU(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function KU(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function qU(e){let t=UU(e.argv[1]??``),n=WU(t),r=KU(n,`references`),i=KU(n,`assets`),a=KU(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)+`
|
|
1646
|
-
`),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 ${GU(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 JU=new Map,YU=new Map;function XU(e){let t=crypto.randomUUID();return JU.set(t,e),t}function ZU(e){return JU.get(e)??null}function QU(e,t){if(!JU.has(e))return t.abort(),()=>{};let n=YU.get(e);return n||(n=new Set,YU.set(e,n)),n.add(t),()=>{let n=YU.get(e);n&&(n.delete(t),n.size===0&&YU.delete(e))}}function $U(e){JU.delete(e);let t=YU.get(e);if(t){YU.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function eW(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 tW(e){let t=ZU(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 eW(e)}}function nW(e){return`slicc-sync-fs-`+e}const rW=`sync-fs-ack`,iW=`sync-fs-res`,aW=6e5,oW=5e3,sW=`exec`;function cW(e){return e.channel===sW}function lW(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 uW(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,aW)}async function dW(e){let t=ZU(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=lW(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()},uW(e.timeoutMs,aW)),o=QU(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`}:eW(e)}finally{clearTimeout(a),o()}}function fW(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function pW(e){let t=hW(e);if(gW(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw fW(`EIO`,e.label);_W(t,e.label)}function mW(e){let t=pW(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw fW(`EIO`,e.label)}}function hW(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 fW(`EIO`,e.label)}return t}function gW(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function _W(e,t){throw fW(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function vW(e){return(t,n,r)=>{let i=mW({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:sW})),timeoutMs:n+oW,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw fW(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function yW(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 bW(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??vW(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&yW(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=uW(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 xW(e,t){return fW(e,`sync-fs bridge, '${t}'`)}function SW(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function CW(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:SW(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return pW(r(`GET`,e))},writeFile(e,t){pW(r(`POST`,e,t))},stat(e){let t=mW(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw xW(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=mW(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw xW(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=mW(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw xW(`EIO`,e);return t},exists(e){let t=mW(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw xW(`EIO`,e);return t},mkdir(e){pW(r(`POST`,e,void 0,`mkdir`))},rm(e){pW(r(`POST`,e,void 0,`rm`))}}}const wW=new TextEncoder,TW=new TextDecoder;function EW(e){if(!e.ok)return{status:4,payload:wW.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:wW.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function DW(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(TW.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(TW.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 OW(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 kW(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function AW(e,t,n={}){let{header:r,window:i}=OW(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 fW(`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 fW(`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 fW(`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 fW(`EIO`,a)}}finally{Atomics.store(r,0,0)}return DW(f,d)}}}function jW(e,t){return fW(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 NW(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 jW(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw jW(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw jW(`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 jW(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!MW(t))throw jW(`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 jW(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw jW(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function PW(e){return(t,n,r)=>{let i=e.call({...t,channel:sW},n+oW,r);if(!i.ok)throw fW(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 fW(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function FW(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 qF(r)}function IW(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function LW(e,t){return t?NW(t):e.syncFsToken?CW(e.syncFsToken):void 0}function RW(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return AW(e.syncSab,t)}function zW(e,t,n,r,i){let a=RW(e,t),o=LW(e,a);if(Object.assign(r,pI(n,e.cwd,o,i)),e.syncFsToken)return bW(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:PW(a)}:{}})}function BW(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:Qr().version,writable:!1,enumerable:!1,configurable:!1})}function VW(e,t,n){let r=gI({isTTY:!e,noColor:e});return{colorApi:r,cliApi:mI({writeStdout:t,writeStderr:n,exit:e=>{throw new tH(e)},color:r})}}function HW(e,t,n){return{readStdinBytes:()=>YF(e.stdin??``),writeStdout:t,writeStderr:n}}function UW(e){return{usbBridge:HU(e),serialBridge:zU(e),hidBridge:hU(e)}}async function WW(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=_H(i,a),s=vH(e,i,a),{colorApi:c,cliApi:l}=VW(!!e.env?.NO_COLOR,i,a),u=new iF(t),d=HW(e,i,a),f=sI(u,C,d),p=await FW(u,e.cwd,IW(e,a)),m=zW(e,t,p,f,d),h=iU(u,p,e.cwd,a),g=JH(h,{cwd:e.cwd}),_=qU({argv:e.argv,fs:f,exec:h}),v=$H(u),{usbBridge:y,serialBridge:b,hidBridge:x}=UW(u),S=GH({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e);return sU(await u.call(`fetch`,`request`,[n,await ZH(t,e)]),n)}let w=TU({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=eH(T),D=await OU(u,e.code,e.cwd,T),ee=jU({graph:D,fsBridge:f,processShim:s.processShim,childProcess:yL(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:AU(u),nodeReadline:EH({output:{write:i},onExit:s.recordExit}),nodeOsModule:uR(e.env),nodeUtilModule:lL(e=>a(`${e}\n`))}).require,te={exports:{},filename:e.filename},ne=D.entrySource!==void 0;await GW({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 GW(e){let t=globalThis;BW(),t.__slicc_compileWasm=t=>e.rpc.call(`wasm`,`compile`,[t]);let n=BU(globalThis,{onCallbackError(e){if(!(e instanceof tH))throw e}});n.install();try{let r=await KW({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 KW(e){let t=await LU(e.entryCode,e.bridges,e.writeStderr,e.isEsmEntry);return await qW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?(e.timers.clearPending(),e.proc.getExitCode()):(await JW(e.rpc,e.timers,e.proc),e.proc.getDidCallProcessExit()&&e.timers.clearPending(),await qW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?e.proc.getExitCode():t)}async function qW(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 JW(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 YW(){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 XW(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=YW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&WW(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 ZW(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=YW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&hF(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 QW=XW(),$W=ZW();function eG(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?nG():$W({kind:e,ctx:t}):typeof Worker<`u`?tG():QW({kind:e,ctx:t})}function tG(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return rG(new Worker(new URL(`/assets/js-realm-worker-DntrRTxU.js`,``+import.meta.url),{type:`module`}))}function nG(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return rG(new Worker(new URL(`/assets/py-realm-worker-CMUAG309.js`,``+import.meta.url),{type:`module`}))}function rG(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 iG(){if(Ra())return decodeURIComponent(Aa(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function aG(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function oG(e){return e instanceof Error?e.message:String(e)}function sG(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function cG(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:sG(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function lG(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:sG(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const uG=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,dG=/\bimport\s*\.\s*meta\b/g;function fG(e,t){let n=JSON.stringify(t);return e.replace(uG,n).replace(dG,`({ url: ${n} })`)}async function pG(e,t,n,r){let i=await e();return i.transpileModule(fG(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function mG(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>qa(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Oa(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Ea(e))return e;let a=aG(t),o;try{return await cG(n,e,t,a)}catch(e){o=e}try{return await pG(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${oG(o)}; typescript fallback: ${oG(e)}`)}}}function hG(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>qa(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Oa(t));return async({source:e,filename:t})=>{if(!Ea(e)&&!Ga(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?aG(t):void 0,o=i?t:`[eval].js`,s;try{return await lG(n,e,t,a)}catch(e){s=e}try{return await pG(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${oG(s)}; typescript fallback: ${oG(e)}`)}}}function gG(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
1646
|
+
`),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 ${GU(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 JU=new Map,YU=new Map;function XU(e){let t=crypto.randomUUID();return JU.set(t,e),t}function ZU(e){return JU.get(e)??null}function QU(e,t){if(!JU.has(e))return t.abort(),()=>{};let n=YU.get(e);return n||(n=new Set,YU.set(e,n)),n.add(t),()=>{let n=YU.get(e);n&&(n.delete(t),n.size===0&&YU.delete(e))}}function $U(e){JU.delete(e);let t=YU.get(e);if(t){YU.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function eW(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 tW(e){let t=ZU(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 eW(e)}}function nW(e){return`slicc-sync-fs-`+e}const rW=`sync-fs-ack`,iW=`sync-fs-res`,aW=6e5,oW=5e3,sW=`exec`;function cW(e){return e.channel===sW}function lW(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 uW(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,aW)}async function dW(e){let t=ZU(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=lW(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()},uW(e.timeoutMs,aW)),o=QU(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`}:eW(e)}finally{clearTimeout(a),o()}}function fW(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function pW(e){let t=hW(e);if(gW(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw fW(`EIO`,e.label);_W(t,e.label)}function mW(e){let t=pW(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw fW(`EIO`,e.label)}}function hW(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 fW(`EIO`,e.label)}return t}function gW(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function _W(e,t){throw fW(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function vW(e){return(t,n,r)=>{let i=mW({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:sW})),timeoutMs:n+oW,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw fW(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function yW(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 bW(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??vW(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&yW(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=uW(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 xW(e,t){return fW(e,`sync-fs bridge, '${t}'`)}function SW(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function CW(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:SW(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return pW(r(`GET`,e))},writeFile(e,t){pW(r(`POST`,e,t))},stat(e){let t=mW(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw xW(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=mW(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw xW(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=mW(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw xW(`EIO`,e);return t},exists(e){let t=mW(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw xW(`EIO`,e);return t},mkdir(e){pW(r(`POST`,e,void 0,`mkdir`))},rm(e){pW(r(`POST`,e,void 0,`rm`))}}}const wW=new TextEncoder,TW=new TextDecoder;function EW(e){if(!e.ok)return{status:4,payload:wW.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:wW.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function DW(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(TW.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(TW.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 OW(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 kW(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function AW(e,t,n={}){let{header:r,window:i}=OW(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 fW(`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 fW(`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 fW(`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 fW(`EIO`,a)}}finally{Atomics.store(r,0,0)}return DW(f,d)}}}function jW(e,t){return fW(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 NW(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 jW(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw jW(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw jW(`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 jW(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!MW(t))throw jW(`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 jW(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw jW(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function PW(e){return(t,n,r)=>{let i=e.call({...t,channel:sW},n+oW,r);if(!i.ok)throw fW(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 fW(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function FW(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 qF(r)}function IW(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function LW(e,t){return t?NW(t):e.syncFsToken?CW(e.syncFsToken):void 0}function RW(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return AW(e.syncSab,t)}function zW(e,t,n,r,i){let a=RW(e,t),o=LW(e,a);if(Object.assign(r,pI(n,e.cwd,o,i)),e.syncFsToken)return bW(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:PW(a)}:{}})}function BW(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:Qr().version,writable:!1,enumerable:!1,configurable:!1})}function VW(e,t,n){let r=gI({isTTY:!e,noColor:e});return{colorApi:r,cliApi:mI({writeStdout:t,writeStderr:n,exit:e=>{throw new tH(e)},color:r})}}function HW(e,t,n){return{readStdinBytes:()=>YF(e.stdin??``),writeStdout:t,writeStderr:n}}function UW(e){return{usbBridge:HU(e),serialBridge:zU(e),hidBridge:hU(e)}}async function WW(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=_H(i,a),s=vH(e,i,a),{colorApi:c,cliApi:l}=VW(!!e.env?.NO_COLOR,i,a),u=new iF(t),d=HW(e,i,a),f=sI(u,C,d),p=await FW(u,e.cwd,IW(e,a)),m=zW(e,t,p,f,d),h=iU(u,p,e.cwd,a),g=JH(h,{cwd:e.cwd}),_=qU({argv:e.argv,fs:f,exec:h}),v=$H(u),{usbBridge:y,serialBridge:b,hidBridge:x}=UW(u),S=GH({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e);return sU(await u.call(`fetch`,`request`,[n,await ZH(t,e)]),n)}let w=TU({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=eH(T),D=await OU(u,e.code,e.cwd,T),ee=jU({graph:D,fsBridge:f,processShim:s.processShim,childProcess:yL(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:AU(u),nodeReadline:EH({output:{write:i},onExit:s.recordExit}),nodeOsModule:uR(e.env),nodeUtilModule:lL(e=>a(`${e}\n`))}).require,te={exports:{},filename:e.filename},ne=D.entrySource!==void 0;await GW({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 GW(e){let t=globalThis;BW(),t.__slicc_compileWasm=t=>e.rpc.call(`wasm`,`compile`,[t]);let n=BU(globalThis,{onCallbackError(e){if(!(e instanceof tH))throw e}});n.install();try{let r=await KW({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 KW(e){let t=await LU(e.entryCode,e.bridges,e.writeStderr,e.isEsmEntry);return await qW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?(e.timers.clearPending(),e.proc.getExitCode()):(await JW(e.rpc,e.timers,e.proc),e.proc.getDidCallProcessExit()&&e.timers.clearPending(),await qW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?e.proc.getExitCode():t)}async function qW(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 JW(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 YW(){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 XW(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=YW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&WW(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 ZW(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=YW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&hF(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 QW=XW(),$W=ZW();function eG(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?nG():$W({kind:e,ctx:t}):typeof Worker<`u`?tG():QW({kind:e,ctx:t})}function tG(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return rG(new Worker(new URL(`/assets/js-realm-worker-DPLcRbzk.js`,``+import.meta.url),{type:`module`}))}function nG(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return rG(new Worker(new URL(`/assets/py-realm-worker-CMUAG309.js`,``+import.meta.url),{type:`module`}))}function rG(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 iG(){if(Ra())return decodeURIComponent(Aa(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function aG(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function oG(e){return e instanceof Error?e.message:String(e)}function sG(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function cG(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:sG(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function lG(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:sG(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const uG=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,dG=/\bimport\s*\.\s*meta\b/g;function fG(e,t){let n=JSON.stringify(t);return e.replace(uG,n).replace(dG,`({ url: ${n} })`)}async function pG(e,t,n,r){let i=await e();return i.transpileModule(fG(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function mG(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>qa(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Oa(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Ea(e))return e;let a=aG(t),o;try{return await cG(n,e,t,a)}catch(e){o=e}try{return await pG(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${oG(o)}; typescript fallback: ${oG(e)}`)}}}function hG(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>qa(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Oa(t));return async({source:e,filename:t})=>{if(!Ea(e)&&!Ga(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?aG(t):void 0,o=i?t:`[eval].js`,s;try{return await lG(n,e,t,a)}catch(e){s=e}try{return await pG(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${oG(s)}; typescript fallback: ${oG(e)}`)}}}function gG(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
1647
1647
|
`);return t===-1?``:e.slice(t+1)}function _G(e){return ln(e).dir}const vG=[`node`,`require`,`default`],yG=[`node`,`import`,`default`],bG=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,xG=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,SG=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,CG=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,wG=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function TG(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function EG(e){let t=Wa(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!TG(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(bG,`require`,`require`),r(xG,`import`,`import`),r(SG,`import`,`import`),r(CG,`import`,`export`),r(wG,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function DG(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=gG(e);if(n===`esm`){if(!r)throw Error(`Cannot load ESM module '${t}': no transpile hook configured (run: ${Va} esbuild-wasm)`);return await r({source:i,path:t,kind:n})}return i}async function OG(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??vG,s=e.importConditions??yG,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 DG(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=_G(e),m={},h={};for(let{specifier:e,kind:t}of EG(n)){let n;try{n=await ya(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 ya(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 kG(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||Sa.has(e)||SU.has(e))}function AG(e,t){for(let[n,r]of Object.entries(t))e[n]={...e[n]??{},...r}}async function jG(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 EG(t))if(kG(e))try{let t=await OG({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?yG:vG,requireConditions:vG,importConditions:yG});for(let e of t.files)s.has(e.path)||(s.set(e.path,e),c.push(e.path));Object.assign(l,t.entryMap),AG(u,t.edges),AG(d,t.edgeErrors)}catch(t){f[e]=t instanceof Error?t.message:String(t)}let p;o&&(Ea(t)||Ga(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 NG(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function PG(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&NG(e)===NG(t)&&!!e.productName}var FG=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(PG(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 IG=null;function LG(){return IG||=new FG,IG}const RG=4194304;function zG(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 BG(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function VG(e){e.opened||await e.open()}function HG(e,t){if(e>4194304)throw Error(`${t} exceeds the ${RG}-byte (4 MiB) v1 limit`)}function UG(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function WG(e,t){return(await t.getDevices()).map(t=>zG(e.register(t),t))}async function GG(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>zG(e.register(t),t))}function KG(e,t){return zG(t,BG(e,t))}async function qG(e,t){await BG(e,t).open()}async function JG(e,t){await BG(e,t).close()}async function YG(e,t,n,r){HG(r.byteLength,`send report payload`);let i=BG(e,t);await VG(i),await i.sendReport(n,r)}async function XG(e,t,n,r){HG(r.byteLength,`send feature report payload`);let i=BG(e,t);await VG(i),await i.sendFeatureReport(n,r)}async function ZG(e,t,n){let r=BG(e,t);return await VG(r),{reportId:n,bytes:UG(await r.receiveFeatureReport(n))}}async function QG(e,t,n){let r=BG(e,t);await VG(r);let i=e=>{n({reportId:e.reportId,bytes:UG(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const $G=6e4;function eK(){return cw()}function tK(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),$G);lw(`hid-device`,e??[],void 0,{timeoutMs:$G}).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 nK(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var rK=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 WG(this.registry,this.hid())}async request(e){if(eK()){let t=await tK(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=>zG(this.registry.register(e),e))}return GG(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(KG(this.registry,e))}open(e){return qG(this.registry,e)}close(e){return JG(this.registry,e)}sendReport(e,t,n){return YG(this.registry,e,t,nK(n))}sendFeatureReport(e,t,n){return XG(this.registry,e,t,nK(n))}async receiveFeatureReport(e,t){let n=await ZG(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return QG(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},iK=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:nK(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:nK(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 aK(e,t){return e&&MG()?new rK(LG()):t?new iK(t):null}function oK(e){return async function(t,n){let r=t instanceof Request?t:null,i=sK(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=lK(r?.headers,n?.headers),s=await fK(n,r,a,o);s.defaultContentType&&!uK(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 sK(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function cK(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 lK(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=cK(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function uK(e,t){return dK(e,t)!==void 0}function dK(e,t){let n=t.toLowerCase(),r;for(let[t,i]of Object.entries(e))t.toLowerCase()===n&&(r=i);return r}async function fK(e,t,n,r){if(e&&`body`in e&&e.body!==void 0)return pK(e.body,n);if(t&&n!==`GET`&&n!==`HEAD`){let e=t.body!==null,n=new Uint8Array(await t.arrayBuffer()),i=dK(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 pK(e,t){if(lr(e)){if(t===`GET`||t===`HEAD`)return{};let n=await hr(e);return{body:n.bytes,defaultContentType:n.contentType}}return{body:await mK(e,t),defaultContentType:gK(e,t)}}async function mK(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 hK(e){return e instanceof Uint8Array||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob}function gK(e,t){if(e instanceof URLSearchParams)return`application/x-www-form-urlencoded;charset=UTF-8`;if(!(t===`GET`||t===`HEAD`||!hK(e)))return typeof Blob<`u`&&e instanceof Blob&&e.type?e.type:`application/octet-stream`}function _K(){return globalThis.navigator?.serial??null}var vK=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 yK=null;function bK(){return yK||=new vK,yK}const xK=4194304;function SK(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 CK(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function wK(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function TK(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 EK(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 DK(e){if(await EK(e),e.opened){try{await e.port.close()}catch{}e.opened=!1}}async function OK(e,t){let n=await t.getPorts();for(let{entry:t}of e.retainOnly(n))await DK(t);return n.map(t=>{let n=e.register(t);return SK(n,e.get(n))})}async function kK(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return SK(i,e.get(i))}function AK(e,t){return SK(t,CK(e,t))}async function jK(e,t,n){let r=CK(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=CK(e,t);await EK(n);try{await n.port.close()}catch(e){if(!NK(e))throw e}n.opened=!1}function NK(e){let t=e instanceof Error?e.message:String(e);return/already closed|not open/i.test(t)}function PK(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 FK(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 IK(e,t,n){let r=CK(e,t),i=Math.min(n.maxBytes??4194304,xK),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=TK(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=PK(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=wK(c,a.value);let e=u();if(e)return e}}return c}async function LK(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${xK}-byte (4 MiB) v1 limit`);return await FK(CK(e,t)).write(n),n.length}async function RK(e,t){return CK(e,t).port.getSignals()}async function zK(e,t,n){await CK(e,t).port.setSignals(n)}const BK=6e4;function VK(){return cw()}function HK(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),BK);lw(`serial-port`,e??[],void 0,{timeoutMs:BK}).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 UK(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var WK=class{registry;constructor(e){this.registry=e}serial(){let e=_K();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return OK(this.registry,this.serial())}async request(e){if(VK()){let t=await HK(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 SK(r,this.registry.get(r))}return kK(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(AK(this.registry,e))}open(e,t){return jK(this.registry,e,t)}close(e){return MK(this.registry,e)}read(e,t){return IK(this.registry,e,t)}write(e,t){return LK(this.registry,e,t)}getSignals(e){return RK(this.registry,e)}setSignals(e,t){return zK(this.registry,e,t)}},GK=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?UK(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:UK(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 KK(e,t){return e&&_K()?new WK(bK()):t?new GK(t):null}function qK(){return globalThis.navigator?.usb??null}function JK(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var YK=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(JK(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 XK=null;function ZK(){return XK||=new YK,XK}const QK=4194304,$K=new Set([`in`,`out`]),eq=new Set([`bulk`,`interrupt`,`isochronous`]);function tq(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=>$K.has(e.direction)&&eq.has(e.type)).map(e=>({endpointNumber:e.endpointNumber,direction:e.direction,type:e.type,packetSize:e.packetSize}))}))}))}))}function nq(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:tq(t.configurations)}:{}}}function rq(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function iq(e,t){if(e>4194304)throw Error(`${t} exceeds the ${QK}-byte (4 MiB) v1 limit`)}function aq(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function oq(e,t){return(await t.getDevices()).map(t=>nq(e.register(t),t))}async function sq(e,t,n){let r=await t.requestDevice({filters:n});return nq(e.register(r),r)}function cq(e,t){return nq(t,rq(e,t))}async function lq(e,t){await rq(e,t).open()}async function uq(e,t){await rq(e,t).close()}async function dq(e,t,n){await rq(e,t).selectConfiguration(n)}async function fq(e,t,n){await rq(e,t).claimInterface(n)}async function pq(e,t,n){await rq(e,t).releaseInterface(n)}async function mq(e,t,n,r){iq(r,`control-in length`);let i=await rq(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?aq(i.data):new ArrayBuffer(0)}}async function hq(e,t,n,r){iq(r.byteLength,`control-out payload`);let i=await rq(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function gq(e,t,n,r){iq(r,`transfer-in length`);let i=await rq(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?aq(i.data):new ArrayBuffer(0)}}async function _q(e,t,n,r){iq(r.byteLength,`transfer-out payload`);let i=await rq(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function vq(e,t){await rq(e,t).reset()}async function yq(e,t,n,r){await rq(e,t).clearHalt(n,r)}const bq=6e4;function xq(){return cw()}function Sq(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),bq);lw(`usb-device`,e??[],void 0,{timeoutMs:bq}).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 Cq(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var wq=class{registry;constructor(e){this.registry=e}usb(){let e=qK();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return oq(this.registry,this.usb())}async request(e){if(xq()){let t=await Sq(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 nq(this.registry.register(n),n)}return sq(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(cq(this.registry,e))}open(e){return lq(this.registry,e)}close(e){return uq(this.registry,e)}selectConfig(e,t){return dq(this.registry,e,t)}claim(e,t){return fq(this.registry,e,t)}release(e,t){return pq(this.registry,e,t)}async controlIn(e,t,n){let r=await mq(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return hq(this.registry,e,t,Cq(n))}async transferIn(e,t,n){let r=await gq(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return _q(this.registry,e,t,Cq(n))}clearHalt(e,t,n){return yq(this.registry,e,t,n)}reset(e){return vq(this.registry,e)}},Tq=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:Cq(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:Cq(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 Eq(e,t){return e&&qK()?new wq(ZK()):t?new Tq(t):null}function Dq(e,t,n,r={}){let{header:i,window:a}=OW(t),o=new Map,s=!1,c=r.dispatch??(e=>cW(e)?dW(e):tW(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}=EW(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 Oq=r(`realm-host`);function kq(e,t,n={}){let r=new Map,i=n.syncFsBridgeEnabled?XU({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;Aq(e,i,t,n,o,c)};e.addEventListener(`message`,l);let u=i&&n.syncSab?Dq(e,n.syncSab,i):void 0;return e.start?.(),{syncFsToken:i,dispose:()=>{if(!a){a=!0,u?.dispose(),i&&$U(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 Aq(e,t,n,r,i,a){try{let o=await jq(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=bJ(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 jq(e,t,n,r,i){switch(e.channel){case`vfs`:return Lq(e.op,e.args,t);case`exec`:return Xq(e.op,e.args,t,i);case`fetch`:return eJ(e.op,e.args,t);case`browser`:return iJ(e.op,e.args,Mq(n),n);case`usb`:return _J(e.op,e.args,Pq(n));case`serial`:return vJ(e.op,e.args,Fq(n));case`hid`:return yJ(e.op,e.args,Iq(n),r);case`module`:return nJ(e.op,e.args,t);case`wasm`:return rJ(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 Nq(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 Pq(e){if(e.usbBackend)return e.usbBackend;let t=Eq(d(),u());if(!t)throw Error(`usb is not available in this runtime`);return t}function Fq(e){if(e.serialBackend)return e.serialBackend;let t=KK(d(),u());if(!t)throw Error(`serial is not available in this runtime`);return t}function Iq(e){if(e.hidBackend)return e.hidBackend;let t=aK(d(),u());if(!t)throw Error(`hid is not available in this runtime`);return t}async function Lq(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 Kq(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await qq(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const Rq=10485760;function zq(e){return e.fileCount>=500||e.totalBytes>=Rq}function Bq(e){return e.entries.length>=2e4}async function Vq(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 Hq(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 Uq(e,t,n,r,i){if(n>1048576||zq(r)||r.totalBytes+n>Rq){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 Wq(e,t,i,r);return}r.entries.push({path:t,content:a,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=a.byteLength}async function Wq(e,t,n,r){let i;try{i=await e.fs.stat(t)}catch{return}if(i.isDirectory){await Vq(e,t,n,r);return}r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:i.size})}async function Gq(e,t,n){if(Bq(n))return;let r=[t];for(;r.length>0;){if(Bq(n))return;let t=r.pop(),i;try{i=await e.fs.lstat(t)}catch{}if(i?.isSymbolicLink){await Hq(e,t,i.size,n);continue}let a;try{a=await e.fs.stat(t)}catch{continue}a.isDirectory?await Vq(e,t,r,n):a.isFile&&await Uq(e,t,a.size,n,r)}}async function Kq(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await Gq(e,t,n),t!==`/tmp`&&await Gq(e,`/tmp`,n),{entries:n.entries}}async function qq(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 Jq=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),Yq=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function Xq(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 Qq(t,n,r);if(e===`kill`)return $q(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function Zq(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 Qq(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??{};Zq(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 $q(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&Jq.has(r)?r:`SIGTERM`;Yq.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 eJ(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?oK(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 tJ(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 nJ(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=tJ(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return jG({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:mG({ipk:s}),transpileEntry:hG({ipk:s})})}async function rJ(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 Xa(e=>n.fs.readFileBuffer(e),i)}async function iJ(e,t,n,r){switch(e){case`findTab`:return sJ(n,t[0]??{});case`ensureTab`:{let e=t[0];return cJ(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return lJ(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return lJ(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return pJ(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return mJ(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await Nq(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return Nq(r).update(e,n)}case`wsClose`:{let e=t[0];return Nq(r).close(e)}case`wsList`:return Nq(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 fJ(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function aJ(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function oJ(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=aJ()?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){Oq.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function sJ(e,t){let n=await oJ(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=hJ(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 cJ(e,t,n){let r=await oJ(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=gJ(t);if(e){let t=r.find(t=>gJ(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function lJ(e,t,n,r){return e.withTab(t,async e=>uJ(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function uJ(e){if(typeof e!=`string`)return e;let t=dJ(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=dJ(t);if(typeof e==`object`&&e)return e}return t}return e}function dJ(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 fJ(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(){
|
|
1648
1648
|
try {
|
|
1649
1649
|
var entries = performance.getEntriesByType('resource');
|
|
@@ -1660,7 +1660,7 @@ except BaseException:
|
|
|
1660
1660
|
})()`,{returnByValue:!0}))return})}async function pJ(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 mJ(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 hJ(e){try{return new URL(e).hostname}catch{return null}}function gJ(e){try{return new URL(e).origin}catch{return null}}async function _J(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 vJ(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 yJ(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 bJ(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 xJ(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?SJ(e.syncSabBytes):void 0,a=kq(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+`
|
|
1661
1661
|
`,exitCode:1},1)}},l=e=>{let t=e.message??`realm error`;f({stdout:``,stderr:t+`
|
|
1662
1662
|
`,exitCode:1},1)},u=()=>{f({stdout:``,stderr:`realm-runner: worker message could not be deserialized
|
|
1663
|
-
`,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 SJ(e){if(kW())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let CJ=!1;function wJ(e){CJ=e}function TJ(){return CJ}const EJ=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 DJ(e){return EJ[e]??null}function OJ(e,t){let n=DJ(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let kJ=null;function AJ(e){let t=kJ;return kJ=e,t}async function jJ(){if(!kJ)return{};try{return await kJ()??{}}catch{return{}}}function MJ(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-
|
|
1663
|
+
`,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 SJ(e){if(kW())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let CJ=!1;function wJ(e){CJ=e}function TJ(){return CJ}const EJ=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 DJ(e){return EJ[e]??null}function OJ(e,t){let n=DJ(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let kJ=null;function AJ(e){let t=kJ;return kJ=e,t}async function jJ(){if(!kJ)return{};try{return await kJ()??{}}catch{return{}}}function MJ(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-BSIs8eWH.js`).then(e=>e.t);return OJ(t(),e())}}async function NJ(e,t,n,r,i={}){return await n.fs.exists(e)?PJ(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 PJ(e,t,n,r,i={}){let a=i.realmFactory??FJ(),o=r?.processManager??RJ()??LJ(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await xJ({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:{...s.kind===`scoop`?{}:await jJ(),...Object.fromEntries(n.env.entries())},cwd:n.cwd,filename:c,stdin:Za(n.stdin),ctx:n,ppid:r?.getParentPid?.(),syncFsBridgeEnabled:TJ()})}function FJ(){return typeof Worker<`u`||typeof document<`u`?eG():XW()}let IJ=null;function LJ(){return IJ||=new _a,IJ}function RJ(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function zJ(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 BJ=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=It();if(!e)return null;let t=e.onUpdate;return e=>{t({content:[{type:`progress`,progress:e}]})}}scrubbed(e){return this.scrubLabel?VJ(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=HJ(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:HJ(i)})})}};async function VJ(e,t){if(!t)return t;try{return await e(t)}catch{return`[label withheld: secret scrub unavailable]`}}function HJ(e,t=80){return e.length>t?`${e.slice(0,t-1)}…`:e}function UJ(e,t){return t.length?`${e} ${t.join(` `)}`:e}function WJ(e){try{let t=new URL(e);return`↓ ${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return`↓ ${e}`}}function GJ(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:WJ(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 KJ={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}},qJ=new Set([`xargs`,`watch`,`parallel`,`bash`,`sh`,`eval`,`source`,`.`]);function JJ(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 YJ(e,t){switch(e.type){case`CommandSubstitution`:return oY(e.body,t);case`DoubleQuoted`:{let n=0;for(let r of e.parts){let e=YJ(r,t);if(e===null)return null;n+=e}return n}case`ProcessSubstitution`:return null;default:return 0}}function XJ(e,t){let n=0;for(let r of e.parts){let e=YJ(r,t);if(e===null)return null;n+=e}return n}function ZJ(e,t){let n=0;for(let r of e.assignments){if(!r.value)continue;let e=XJ(r.value,t);if(e===null)return null;n+=e}for(let r of e.args){let e=XJ(r,t);if(e===null)return null;n+=e}if(!e.name)return n;let r=JJ(e.name);if(r===null||qJ.has(r))return null;if(!t.has(r))return n;n+=1;let i=KJ[r];if(i){let r=e.args.map(JJ);if(r.some(e=>e===null))return null;let a=r[i(r)];if(a===void 0)return n;if(qJ.has(a))return null;t.has(a)&&(n+=1)}return n}function QJ(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 $J(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||JJ(r.name)!==`seq`)return null;let i=r.args.map(e=>{let t=JJ(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 eY(e){let t=0;for(let n of e){let e=n.type===`Word`?tY(n.word):QJ(n);if(e===null)return null;t+=e}return t}function tY(e){let t=$J(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=eY(t.items);if(e===null)return null;n*=e;break}default:return null}return n}function nY(e){let t=0;for(let n of e){let e=tY(n);if(e===null)return null;t+=e}return t}function rY(e,t){let n=0;for(let r of e){let e=aY(r,t);if(e===null)return null;n+=e}return n}function iY(e,t){switch(e.type){case`SimpleCommand`:return ZJ(e,t);case`For`:{if(!e.words)return null;let n=nY(e.words),r=rY(e.body,t);return n===null||r===null?null:e.words.filter(e=>$J(e)!==null&&t.has(`seq`)).length+n*r}case`Subshell`:case`Group`:return rY(e.body,t);case`FunctionDef`:return 0;default:return null}}function aY(e,t){let n=0;for(let r of e.pipelines)for(let e of r.commands){let r=iY(e,t);if(r===null)return null;n+=r}return n}function oY(e,t){return rY(e.statements,t)}function sY(e,t){let n=oY(e,t);return{totalSteps:n!==null&&n>0?n:null}}function cY(e){return e.split(`
|
|
1664
1664
|
`).map(e=>e.trim()).find(e=>e.length>0&&!e.startsWith(`#`))||`bash`}var lY=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 uY=globalThis.setTimeout.bind(globalThis);function dY(e){let t=e/1e3;return`sleep ${Number.isInteger(t)?t:t.toFixed(1)}`}function fY(e,t={}){let n=t.now??Date.now,r=t.setTimeout??uY,i=t.isAborted??(()=>!1),a=t.label??dY,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 pY=globalThis.setTimeout.bind(globalThis);function mY(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 hY(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 gY(e,t,n={}){let r=n.now??Date.now,i=n.setTimeout??pY;return{...e,async execute(n,a){let o=hY(n),s=o>=0?mY(n[o]):null;if(!t.hasSink()||s===null||s<=0)return e.execute(n,a);let c=t.allocateId(`timeout`),l=UJ(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 _Y=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 vY(e,t,n={}){if((n.skip??_Y).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=UJ(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 yY(e){return hi(`sudo`,e)}async function bY(e,t){let n=e.trim();if(!n||bee(ui(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:yY(r)};if(r.decision===`always`){let e=r.pattern?.trim()||n;await t.persistGrant(e)}return{allowed:!0}}const xY={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 SY(e,t=[],n){let r=xY[e],i=t.length?` data-action-data='${JSON.stringify({filters:t}).replace(/'/g,`'`)}'`:``,a=e===`directory`&&n?`<div class="sprinkle-action-card__meta">Target: ${ki(n)}</div>`:``;return`
|
|
1665
1665
|
<div class="sprinkle-action-card">
|
|
1666
1666
|
<div class="sprinkle-action-card__header">
|
|
@@ -1778,7 +1778,7 @@ Examples:
|
|
|
1778
1778
|
skill list
|
|
1779
1779
|
skill info bluebubbles
|
|
1780
1780
|
skill read bluebubbles
|
|
1781
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
1781
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-DQ9l8ZBo.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${oX()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:cX(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
1782
1782
|
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:lX(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
|
|
1783
1783
|
`,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+`
|
|
1784
1784
|
`,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 fX=[{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=>yo(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 pX(e){let t={skills:[],dryRun:!1,json:!1};for(let n=0;n<e.length;n++){let r=e[n],i=fX.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 mX(e,t){return!e||!t||e.byteLength!==t.byteLength?!1:e.every((e,n)=>e===t[n])}async function hX(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 gX(e,t,n,r){let i=await hX(e,t);return lo(n)?i?{status:`kept-local`,write:!1}:{status:`added`,write:!0}:i?mX(i,r)?{status:`unchanged`,write:!1}:{status:`updated`,write:!0}:{status:`added`,write:!0}}async function _X(e,t,n,r){let i={changes:[],writes:[],removals:[]};for(let[r,a]of n){let n=`${t}/${r}`,{status:o,write:s}=await gX(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 so(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 vX(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 oo(t),d=await _o(s,c,o.ref,u,!0);if(d&&r.sha===d&&await yX(e,n,r))return{...o,to:d,outcome:`current`,changes:[]};let f=await bX(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 _X(e,`${io}/${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 TX(e,{changes:h,writes:g,removals:_}),await Co(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 yX(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 bX(e,t,n,r,i,a,o){let s=await uo(e,t,a,i??`main`);if(s.status===`ok`){let i=to(s.files),a=n||xX(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:wX(i,a),path:a}}try{return{files:CX(SX(await co(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 xX(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 SX(e){return new Map([...e].filter(([e])=>no(e)))}function CX(e){return new Map([...e].sort(([e],[t])=>e.localeCompare(t)))}function wX(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);no(e)&&r.set(e,i)}return CX(r)}async function TX(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 EX(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 iX(o,s,t);if(!c.ok)return{...a,outcome:`error`,error:c.error};let l=`${io}/${n}/SKILL.md`,u=await hX(e,l),d=new TextEncoder().encode(c.content),f=u!==void 0&&nX(new TextDecoder().decode(u))===nX(c.content);if(mX(u,d)||f)return{...a,changes:[{path:`SKILL.md`,status:`unchanged`}]};let p=u?`updated`:`added`;return i||(await e.mkdir(`${io}/${n}`,{recursive:!0}),await e.writeFile(l,d),await Co(e,n,{...r,files:[`SKILL.md`]})),{...a,outcome:`updated`,changes:[{path:`SKILL.md`,status:p}]}}function DX(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 OX(e,t,n,r){let i=yo(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 kX(e,t,n){if(t.length===0){let t=await vo(e);return{targets:t.provenanced,missing:[],skipped:t.unattributed}}let r=[],i=[];for(let a of t){let t=await Eo(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?OX(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 AX(e){return e.reason===`not-installed`?`upskill: no skill named "${e.name}" is installed — check \`upskill list\`
|
|
@@ -1811,7 +1811,7 @@ Examples:
|
|
|
1811
1811
|
`,{stdout:s,stderr:``,exitCode:0}}function KX(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
1812
1812
|
`,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
|
|
1813
1813
|
`,exitCode:1}}function qX(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
|
|
1814
|
-
`,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=KX(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 JX(e){let t=await(await import(`./skills-
|
|
1814
|
+
`,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=KX(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 JX(e){let t=await(await import(`./skills-DQ9l8ZBo.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${oX()}`,stderr:``,exitCode:0}:{stdout:cX(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function YX(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-DQ9l8ZBo.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 Eo(n,t),a=i?bo(i):"Installed from: (no provenance recorded — reinstall to enable `upskill update`)\n";return{stdout:lX(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+`
|
|
1815
1815
|
`,stderr:``,exitCode:0}}async function XX(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 So(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 ZX(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 xo(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 QX(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await xo(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 $X(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 eZ(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await oo(r),l=await wo(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:$X(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:$X(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 uo(i,a,r,o);if(e.status===`ok`){let r=await _o(i,a,o,c),s=await XX(u,i,a,to(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 ZX(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await QX(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 go()),{stdout:p,stderr:m,exitCode:+!!m}}async function tZ(e,t,n,r){switch(e[0]){case`tabs`:return WX(t,n,r,e.includes(`--json`));case`recommendations`:return GX(t,n,e.includes(`--install`));case`update`:case`upgrade`:return PX(e.slice(1),t,n);case`list`:return JX(t);case`info`:case`read`:return YX(e[0],e[1],t);case`search`:return rZ(e,n);default:return null}}function nZ(e,t,n){return B(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return uX();let a=await tZ(r,e,t,n);if(a)return a;let o=qX(r);if(o.earlyReturn)return o.earlyReturn;if(!o.sourceRef)return uX();if(o.sourceRef.startsWith(`tessl:`))return iZ(o.sourceRef,o.force,e,t);let s=$Y(o.sourceRef);if(s)return aX(s.hostname,s.task,e,t,o.force);let c=yo(o.sourceRef);return c?eZ(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 rZ(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?zX(a,t,i):uX()}async function iZ(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
1816
1816
|
`,exitCode:1};let a=await IX(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await oo(r);return xo(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function aZ(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
1817
1817
|
|
|
@@ -2232,7 +2232,7 @@ Examples:
|
|
|
2232
2232
|
`;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+=`
|
|
2233
2233
|
`;return t}async function z1(e,t){let n=V(e.slice(1),{});if(`error`in n)return I1(n.error);if(!t()){let e=await k1();if(!e)return M1(`list`);let t=await e.listCronTasks();return t.length===0?{stdout:`No active cron tasks
|
|
2234
2234
|
`,stderr:``,exitCode:0}:{stdout:R1(t),stderr:``,exitCode:0}}let{ok:r,data:i}=await P1(`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
|
|
2235
|
-
`,stderr:``,exitCode:0}:{stdout:R1(a),stderr:``,exitCode:0}}async function B1(e,t){let n=e[0],r=V(e.slice(1),{});if(`error`in r)return I1(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 k1();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 P1(`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 V1(e={}){let t=e.hasLocalNodeServer??(()=>!1);return B(`crontask`,async(e,n)=>{let r=e[0];if(!r||oi(e,{valueFlags:F1}))return N1();try{switch(r){case`create`:return await L1(e,n.env,t);case`list`:return await z1(e,t);case`delete`:case`kill`:return await B1(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 H1(e){return B(`curlwright`,async(t,n)=>{let{runCurlwright:r}=await import(`./run-
|
|
2235
|
+
`,stderr:``,exitCode:0}:{stdout:R1(a),stderr:``,exitCode:0}}async function B1(e,t){let n=e[0],r=V(e.slice(1),{});if(`error`in r)return I1(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 k1();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 P1(`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 V1(e={}){let t=e.hasLocalNodeServer??(()=>!1);return B(`crontask`,async(e,n)=>{let r=e[0];if(!r||oi(e,{valueFlags:F1}))return N1();try{switch(r){case`create`:return await L1(e,n.env,t);case`list`:return await z1(e,t);case`delete`:case`kill`:return await B1(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 H1(e){return B(`curlwright`,async(t,n)=>{let{runCurlwright:r}=await import(`./run-DVF88haQ.js`);return r(e,t,n)})}const U1=`slicc-fs`;async function W1(){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===U1)}catch{return!0}}async function G1(){let e=globalThis.indexedDB;return e?new Promise(t=>{let n;try{n=e.deleteDatabase(U1)}catch{t(`error`);return}n.onsuccess=()=>t(`deleted`),n.onerror=()=>t(`error`),n.onblocked=()=>t(`blocked`)}):`error`}async function K1(){if(!await W1())return{kind:`absent`,message:`legacy slicc-fs IDB not present — nothing to clean`};let e=await G1();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 q1(){return`slicc-fs-cleanup — delete the legacy slicc-fs IndexedDB
|
|
2236
2236
|
|
|
2237
2237
|
Usage:
|
|
2238
2238
|
slicc-fs-cleanup Delete the legacy slicc-fs IDB.
|
|
@@ -2724,7 +2724,7 @@ Options:
|
|
|
2724
2724
|
`,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(!Ki(e))throw e}t.sessionDirsCreated=!0}}async function hue(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(`
|
|
2725
2725
|
`),p=`/.playwright/snapshots/page-${Wi(new Date)}.yml`;return await t.writeFile(p,f),p})}catch{return null}}async function gue(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(`
|
|
2726
2726
|
`)+`
|
|
2727
|
-
`,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-
|
|
2727
|
+
`,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-CsC80g1q.js`)}async function _ue(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(`
|
|
2728
2728
|
`);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 vue(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() {
|
|
2729
2729
|
this.scrollIntoView({ block: 'center' });
|
|
2730
2730
|
const r = this.getBoundingClientRect();
|
|
@@ -2802,7 +2802,7 @@ Options:
|
|
|
2802
2802
|
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
2803
2803
|
return el.files.length;
|
|
2804
2804
|
})()`,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`,Due],[`state-load`,Oue],[`console`,Uce],[`requests`,eue],[`request`,tue],[`request-headers`,nue],[`request-body`,rue],[`response-headers`,iue],[`response-body`,aue],[`mousemove`,Tle],[`mousedown`,Ele],[`mouseup`,Dle],[`mousewheel`,Ole],[`drop`,kle],[`route`,fue],[`route-list`,pue],[`unroute`,mue],[`generate-locator`,Zce],[`highlight`,Qce]]);function Uue(){let e=(Yi.string??[]).map(e=>`--${e}`),t=new Set(Yi.boolean??[]);for(let[e,n]of Object.entries(Yi.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 Wue(e){return e.map(e=>e===`--no-iframes`||e.startsWith(`--no-iframes=`)?e.replace(`--no-iframes`,`--_noiframes`):e)}function Gue(e){return{...e,bool:[...e.bool??[],`--_noiframes`],value:[...e.value??[],`--_noiframes`]}}const Y4=2e3;function Kue(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 que(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.
|
|
2805
|
-
`;return{...r,stderr:r.stderr+c}}async function Jue(e,t,n){let r=n instanceof Error?n.message:String(n);return{stdout:``,stderr:`Error: ${(t.tab?await Xi(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 Yue(e,t,n){let r=Hue.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 Jue(n.browser,n.flags,r)}}async function Xue(e,t,n,r){let i=V(Wue(n),Gue(r));if(`error`in i)return{answer:{stdout:``,stderr:`${e} ${t}: ${i.error}\n`,exitCode:1}};let a;try{({flags:a}=Ji(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-
|
|
2805
|
+
`;return{...r,stderr:r.stderr+c}}async function Jue(e,t,n){let r=n instanceof Error?n.message:String(n);return{stdout:``,stderr:`Error: ${(t.tab?await Xi(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 Yue(e,t,n){let r=Hue.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 Jue(n.browser,n.flags,r)}}async function Xue(e,t,n,r){let i=V(Wue(n),Gue(r));if(`error`in i)return{answer:{stdout:``,stderr:`${e} ${t}: ${i.error}\n`,exitCode:1}};let a;try{({flags:a}=Ji(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-S6yh95LF.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 Zue(e,t,n){let r=t?Gi(t,n):null,i=Uue();return B(e,async(a,o)=>{if(a.length===0||a[0]===`help`||a[0]===`--help`||a[0]===`-h`){let{formatHelp:t}=await import(`./help-S6yh95LF.js`);return{stdout:t(e)+`
|
|
2806
2806
|
`,stderr:``,exitCode:0}}let s=a[0],c=a.slice(1),l=await Xue(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=Kue(t,f),m=await Yue(e,s,{browser:t,fs:n,state:r,positional:u,flags:d,scratchDir:cR(o.env),onTab:(e,n)=>t.withTab(e,n,{signal:o.signal}),signal:o.signal}),h=d.tab??null,g=null;na.has(s)&&m.exitCode===0&&h&&(g=await hue(t,n,h,r));try{await gue(n,r,{command:s,args:c,result:m,snapshotPath:g,targetId:h})}catch{}return que(t,p,f,m)})}const Que=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`,...ea,`sprinkle`]],[`Clipboard`,[`pbcopy`,`pbpaste`,`xclip`,`xsel`]],[`Filesystem`,[`mount`,`umount`,`fswatch`]],[`Scoops & agents`,[`agent`,`mcp`,`webhook`,`crontask`]],[`Process`,[`ps`,`kill`,`meminfo`,`uptime`]],[`Shell builtins (limited)`,[...WZ]]]);function $ue(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:
|
|
2807
2807
|
`);let a=[];for(let[e,t]of Que){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(`
|
|
2808
2808
|
`)+`
|
|
@@ -2972,7 +2972,7 @@ no-op.
|
|
|
2972
2972
|
`)}\n`:``,exitCode:c.errors.length===0?0:1}}function pfe(e,t){if(t.length===0)return`${e}\n└── (empty)\n`;let n=[`${e}`];for(let e=0;e<t.length;e++){let r=e===t.length-1?`└──`:`├──`;n.push(`${r} ${t[e].name}@${t[e].version}`)}return`${n.join(`
|
|
2973
2973
|
`)}\n`}async function mfe(e,t,n,r){let{global:i,specs:a}=D3(t);if(a.length===0)return{stdout:``,stderr:`${e}: uninstall requires at least one package name\n`,exitCode:1};let o;try{o=await Ree(a,{fs:r.fs,fetch:r.fetch,cwd:n.cwd,global:i})}catch(t){return{stdout:``,stderr:`${e}: uninstall failed: ${O3(t)}\n`,exitCode:1}}let s=o.results.filter(e=>e.removed).map(t=>`${e}: removed ${t.name}`),c=o.results.filter(e=>!e.removed).map(e=>e.name),l=o.errors.map(t=>`${e}: failed to uninstall ${t.spec}: ${O3(t.error)}`);c.length>0&&l.push(`${e}: ${c.join(`, `)} not installed${i?` globally`:``}`);let u=o.errors.length>0;return i&&await k3(r),{stdout:s.length>0?`${s.join(`
|
|
2974
2974
|
`)}\n`:``,stderr:l.length>0?`${l.join(`
|
|
2975
|
-
`)}\n`:``,exitCode:+!!u}}async function hfe(e,t,n,r){let{global:i}=D3(t);try{let e=i?await Fee(r.fs):await jee(r.fs,n.cwd);return{stdout:pfe(i?Na:n.cwd,e),stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: list failed: ${O3(t)}\n`,exitCode:1}}}async function gfe(e,t,n,r){let{global:i}=D3(t);return{stdout:`${i?va:`${n.cwd.replace(/\/$/,``)}/node_modules`}\n`,stderr:``,exitCode:0}}function j3(e,t){let n=e===`i`;return B(e,async(r,i)=>{if(dfe(r))return{stdout:E3(e),stderr:``,exitCode:0};if(n)return A3(e,r,i,t);if(r.length===0)return{stdout:E3(e),stderr:`${e}: missing subcommand\n`,exitCode:1};let a=r[0],o=r.slice(1);return afe.has(a)?A3(e,o,i,t):ofe.has(a)?mfe(e,o,i,t):sfe.has(a)?hfe(e,o,i,t):a===`root`?gfe(e,o,i,t):Pde.has(a)?T3(e,o,i,{fs:t.fs}):Fde.has(a)?T3(e,r,i,{fs:t.fs}):{stdout:``,stderr:`${e}: unknown subcommand '${a}' (supported: install, uninstall, list, root, run)\n`,exitCode:1}})}const M3=`0.5.
|
|
2975
|
+
`)}\n`:``,exitCode:+!!u}}async function hfe(e,t,n,r){let{global:i}=D3(t);try{let e=i?await Fee(r.fs):await jee(r.fs,n.cwd);return{stdout:pfe(i?Na:n.cwd,e),stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: list failed: ${O3(t)}\n`,exitCode:1}}}async function gfe(e,t,n,r){let{global:i}=D3(t);return{stdout:`${i?va:`${n.cwd.replace(/\/$/,``)}/node_modules`}\n`,stderr:``,exitCode:0}}function j3(e,t){let n=e===`i`;return B(e,async(r,i)=>{if(dfe(r))return{stdout:E3(e),stderr:``,exitCode:0};if(n)return A3(e,r,i,t);if(r.length===0)return{stdout:E3(e),stderr:`${e}: missing subcommand\n`,exitCode:1};let a=r[0],o=r.slice(1);return afe.has(a)?A3(e,o,i,t):ofe.has(a)?mfe(e,o,i,t):sfe.has(a)?hfe(e,o,i,t):a===`root`?gfe(e,o,i,t):Pde.has(a)?T3(e,o,i,{fs:t.fs}):Fde.has(a)?T3(e,r,i,{fs:t.fs}):{stdout:``,stderr:`${e}: unknown subcommand '${a}' (supported: install, uninstall, list, root, run)\n`,exitCode:1}})}const M3=`0.5.455`,N3=`v86 is not installed in node_modules: run \`${Va} v86@${M3}\` (no network fallback)`;let P3=null;async function _fe(e={}){return P3||=bfe(e.ipk).catch(e=>{throw P3=null,e}),P3}const vfe=[{js:`build/libv86.mjs`,wasm:`build/v86.wasm`}];async function yfe(e,t){for(let{js:n,wasm:r}of vfe){let i=`${e}/${n}`,a=`${e}/${r}`;if(await t.exists(i)&&await t.exists(a))return{jsPath:i,wasmPath:a}}return null}async function F3(e){let t;try{t=await ya(`v86/package.json`,e.fromDir,e.reader)}catch{return null}if(t.type!==`file`)return null;let n=await yfe(ln(t.path).dir,e.reader);if(!n)return null;try{let r=await e.reader.readFile(t.path),i=String(JSON.parse(r).version??`0.5.455`);return{jsSource:await e.reader.readFile(n.jsPath),wasmBytes:await e.readBytes(n.wasmPath),version:i}}catch{return null}}async function bfe(e){if(Ra())throw Error(`v86 is not available in Node runtime`);if(!e)throw Error(N3);let t=await F3(e);if(!t)throw Error(N3);let n=URL.createObjectURL(new Blob([t.jsSource],{type:`text/javascript`})),r;try{r=await import(n)}finally{URL.revokeObjectURL(n)}let i=r.V86??r.default;if(typeof i!=`function`)throw Error(`v86: installed package did not export a V86 constructor`);return{V86:i,wasmModule:await Ya(t.wasmBytes),version:t.version}}function xfe(e){return async t=>(await WebAssembly.instantiate(e,t)).exports}const I3={command:`biome`,example:`biome check foo.js`,bootstrap:`${Va} ${SQ}`},L3={command:`playwright-cli`,example:`playwright-cli open https://example.com`},R3={command:`puppeteer`,example:`puppeteer open https://example.com`},z3={command:`convert`,example:`convert input.png output.jpg`,bootstrap:`${Va} @imagemagick/magick-wasm@${Oee}`},B3={...z3,command:`magick`,example:`magick input.png output.jpg`},V3={command:`pdftoppm`,example:`pdftoppm -png -r 150 doc.pdf page`},H3={"@biomejs/biome":I3,biome:I3,esbuild:{command:`esbuild`,example:`esbuild --bundle src/index.js --outfile=dist/bundle.js`,bootstrap:`${Va} esbuild-wasm@${Ja}`},playwright:L3,"@playwright/test":L3,"playwright-core":L3,puppeteer:R3,"puppeteer-core":R3,typescript:{command:`tsc`,example:`tsc --noEmit`,bootstrap:za},"pdf-poppler":V3,"pdf-to-img":V3,pdf2pic:V3,"pdf-img-convert":V3,poppler:V3,"poppler-utils":V3,imagemagick:z3,"imagemagick-cli":z3,"imagemagick-convert":z3,"magick-cli":B3,"@imagemagick/magick-wasm":B3,ffmpeg:{command:`ffmpeg`,example:`ffmpeg -i input.mp4 output.webm`,bootstrap:`${Va} @ffmpeg/core@${jo}`},"@ffmpeg/ffmpeg":{command:`ffmpeg`,example:`ffmpeg -i input.mp4 output.webm`,bootstrap:`${Va} @ffmpeg/core@${jo}`},ffprobe:{command:`ffprobe`,example:`ffprobe -v error -show_format -of json input.mp4`,bootstrap:`${Va} @ffmpeg/core@${jo}`},"@ffprobe-installer/ffprobe":{command:`ffprobe`,example:`ffprobe -v error -show_format -of json input.mp4`,bootstrap:`${Va} @ffmpeg/core@${jo}`},sqlite3:{command:`sqlite3`,example:`sqlite3 database.db "SELECT 1"`},v86:{command:`v86`,example:`v86 start -cdrom alpine.iso`,bootstrap:`${Va} v86@${M3}`}};function Sfe(e){return Object.hasOwn(H3,e)?H3[e]:void 0}function U3(e){return/^[A-Za-z0-9_./:=@%+-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function Cfe(e,t,n,r){let i=n.length?[r.command,...n].map(U3).join(` `):r.example,a=[`${e}: SLICC has a built-in \`${r.command}\` for npm package \`${t}\`.`,` try: ${i}`];return r.bootstrap&&a.push(` first run: ${r.bootstrap}`),a.push(` install anyway: ${[e,`--force`,t,...n].map(U3).join(` `)}`),`${a.join(`
|
|
2976
2976
|
`)}\n`}const wfe=/require\(\s*["']([^"']+)["']\s*\)/;function W3(e){return`${e} - run an installed package's executable bin
|
|
2977
2977
|
|
|
2978
2978
|
Usage:
|
|
@@ -3060,7 +3060,7 @@ Common base URLs:
|
|
|
3060
3060
|
`)+`
|
|
3061
3061
|
`,stderr:``,exitCode:0}}function npe(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(`
|
|
3062
3062
|
`)+`
|
|
3063
|
-
`,stderr:``,exitCode:0}}function rpe(){return B(s6,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:$fe(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./account-store-
|
|
3063
|
+
`,stderr:``,exitCode:0}}function rpe(){return B(s6,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:$fe(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./account-store-BSIs8eWH.js`).then(e=>e.t),{verifyConnection:a}=await import(`./local-llm-DRegic15.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.
|
|
3064
3064
|
`,exitCode:1};let c=await a(s,t(s6)??void 0);if(!c.ok)return epe(s,c);if(o===`discover`){let e=n(s6)??``;return i(s6,e,s,c.models.join(`, `)),npe(s,c)}return tpe(s,c)})}function ipe(){return{stdout:`usage: man <topic>
|
|
3065
3065
|
|
|
3066
3066
|
Fetches documentation for a given topic from sliccy.com.
|
|
@@ -3098,20 +3098,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
3098
3098
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
3099
3099
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
3100
3100
|
short name resolves on the PATH.
|
|
3101
|
-
`);let n=V(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-
|
|
3101
|
+
`);let n=V(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-CvgWI8Er.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 dpe(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 Ape(i,t);let m=await S6(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-DesDs-vM.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(`
|
|
3102
3102
|
`)+`
|
|
3103
|
-
`)}async function dpe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-
|
|
3104
|
-
`);let n=V(e,{});if(`error`in n)return m6(n.error);let{ensureAllMcpProvidersRegistered:r}=await import(`./provider-
|
|
3103
|
+
`)}async function dpe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-BSIs8eWH.js`).then(e=>e.t),c=await Ope(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 Kee(zt()),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 fpe(e,t){if(oi(e))return f6(`usage: mcp list
|
|
3104
|
+
`);let n=V(e,{});if(`error`in n)return m6(n.error);let{ensureAllMcpProvidersRegistered:r}=await import(`./provider-DesDs-vM.js`);await r();let{listServers:i}=await import(`./store-CvgWI8Er.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(`
|
|
3105
3105
|
`)+`
|
|
3106
3106
|
`}async function ppe(e,t){if(oi(e))return f6(`usage: mcp search <query>
|
|
3107
3107
|
|
|
3108
3108
|
Case-insensitive substring search across the cached tools of every
|
|
3109
3109
|
registered MCP server. Matches tool name OR description and prints a
|
|
3110
3110
|
table of (server, tool, description, match-field) rows.
|
|
3111
|
-
`);let n=V(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-
|
|
3112
|
-
`);let n=V(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-
|
|
3111
|
+
`);let n=V(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-DesDs-vM.js`);await a();let{listServers:o}=await import(`./store-CvgWI8Er.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,mpe(e.description),e.match]);return f6(h6(u))}function mpe(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function hpe(e,t){if(e.length===0||oi(e))return e.length===0?p6(`mcp delete: expected <name>`):f6(`usage: mcp delete <name>
|
|
3112
|
+
`);let n=V(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-DesDs-vM.js`);await i(r);let{deleteServer:o}=await import(`./store-CvgWI8Er.js`).then(e=>e.r),s=await o(r,t.fs);await jpe(r,t),await Mpe(r,t);let c=`mcp:${r}`,l=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./account-store-BSIs8eWH.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(`
|
|
3113
3113
|
`)+`
|
|
3114
|
-
`)}async function gpe(e,t){if(e.length===0)return p6(`mcp invoke: expected <name>`);if(oi(e.slice(0,1)))return f6(vpe());let n=V([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-
|
|
3114
|
+
`)}async function gpe(e,t){if(e.length===0)return p6(`mcp invoke: expected <name>`);if(oi(e.slice(0,1)))return f6(vpe());let n=V([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-DesDs-vM.js`);await a(r);let{getServer:o}=await import(`./store-CvgWI8Er.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||oi(i.slice(0,1)))return f6(ype(r,s,c));let l=V([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}=_pe(i.slice(1));if(oi(p))return f6(bpe(r,d));let h=xpe(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=Tpe(await _.toolsCall(u,h.value));return m.length>0&&(v.stderr=m.map(e=>`${e}\n`).join(``)+v.stderr),v}function _pe(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 vpe(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
3115
3115
|
|
|
3116
3116
|
mcp invoke <name> List tools on <name>.
|
|
3117
3117
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -3141,7 +3141,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
3141
3141
|
|
|
3142
3142
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
3143
3143
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
3144
|
-
`);let n=V(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-
|
|
3144
|
+
`);let n=V(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-DesDs-vM.js`);await i(r);let{getServer:a,setServer:o}=await import(`./store-CvgWI8Er.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 Dpe(e,t){if(oi(e))return f6(`usage: mcp auth <name> [--silent | --interactive]
|
|
3145
3145
|
|
|
3146
3146
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
3147
3147
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -3153,7 +3153,7 @@ Options:
|
|
|
3153
3153
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
3154
3154
|
directly. Use after revoking a refresh token or
|
|
3155
3155
|
when the AS no longer accepts the cached one.
|
|
3156
|
-
`);let n=V(e,{bool:spe});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-
|
|
3156
|
+
`);let n=V(e,{bool:spe});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-DesDs-vM.js`),s=await o(r,{fetchImpl:t.oauthFetchImpl,launcher:t.oauthLauncher}),{getServer:c}=await import(`./store-CvgWI8Er.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-DdkKCDPr.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-BSIs8eWH.js`).then(e=>e.t),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-DdkKCDPr.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 Ope(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-luCL6DCO.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 kpe(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
3157
3157
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
3158
3158
|
const { promisify } = require('util');
|
|
3159
3159
|
const { exec } = require('child_process');
|
|
@@ -3182,7 +3182,7 @@ try {
|
|
|
3182
3182
|
if (stdout) process.stdout.write(stdout);
|
|
3183
3183
|
if (stderr) process.stderr.write(stderr);
|
|
3184
3184
|
process.exit(exitCode);
|
|
3185
|
-
`}async function Ape(e,t){let n=await x6(t.fs);await n.mkdir(d6,{recursive:!0}),await n.writeFile(`${d6}/${e}.jsh`,kpe(e)),t.scriptCatalog?.invalidateJsh()}async function jpe(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 Mpe(e,t){let{removeAppSprinkles:n}=await import(`./apps-
|
|
3185
|
+
`}async function Ape(e,t){let n=await x6(t.fs);await n.mkdir(d6,{recursive:!0}),await n.writeFile(`${d6}/${e}.jsh`,kpe(e)),t.scriptCatalog?.invalidateJsh()}async function jpe(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 Mpe(e,t){let{removeAppSprinkles:n}=await import(`./apps-3LBDpLXu.js`);await n(e,t.fs)}async function S6(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-3LBDpLXu.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 Npe(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 Ppe(){let e=globalThis.performance,t=e?.measureUserAgentSpecificMemory;return t?t.bind(e):null}function Fpe(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 Ipe(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)} ${Npe(e)}`)}return`${t.join(`
|
|
3186
3186
|
`)}\n`}function Lpe(e={}){return B(`meminfo`,async t=>{let n=Fpe(t);if(`error`in n)return C6(n.error);if(n.help)return{stdout:`meminfo - agent-cluster memory diagnostics
|
|
3187
3187
|
|
|
3188
3188
|
Usage:
|
|
@@ -3209,7 +3209,7 @@ Options:
|
|
|
3209
3209
|
-h, --help Show this help message
|
|
3210
3210
|
`}function Kpe(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 qpe=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function Jpe(e){let t=`${e.id} ${e.name??``}`;return!qpe.test(t)}function Ype(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 Xpe(e){let t=e.toLowerCase();return t=t.replace(/-\d{8}$/,``),t=t.replace(/-\d{4}$/,``),t=t.replace(/-(preview|latest)$/,``),Ype(t)??t.replace(/-[\d.]+$/,``)}function Zpe(e){let t=new Map;for(let n of e){let e=Xpe(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function Qpe(e,t,n,r,i){let a=i?Wpe(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 $pe(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=`${Kpe(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(`
|
|
3211
3211
|
`)+`
|
|
3212
|
-
`}function eme(e){let t=V(e,{bool:Rpe,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 tme(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 nme(e,t,n,r,i,a){let o=e.getProviderModels(t).filter(Jpe);if(o.length===0)return[];let s=o.map(e=>Qpe(e,t,n,r,i)).sort((e,t)=>t.cost.input-e.cost.input);return a||(s=Zpe(s)),s}function rme(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 ime(e,t){if(oi(e,{valueFlags:E6}))return{stdout:Gpe(),stderr:``,exitCode:0};let n=eme(e);if(`error`in n)return D6(`models: ${n.error}`);let r=await import(`./account-store-
|
|
3212
|
+
`}function eme(e){let t=V(e,{bool:Rpe,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 tme(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 nme(e,t,n,r,i,a){let o=e.getProviderModels(t).filter(Jpe);if(o.length===0)return[];let s=o.map(e=>Qpe(e,t,n,r,i)).sort((e,t)=>t.cost.input-e.cost.input);return a||(s=Zpe(s)),s}function rme(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 ime(e,t){if(oi(e,{valueFlags:E6}))return{stdout:Gpe(),stderr:``,exitCode:0};let n=eme(e);if(`error`in n)return D6(`models: ${n.error}`);let r=await import(`./account-store-BSIs8eWH.js`).then(e=>e.t);if(r.getAccounts().length===0)return D6(`No provider accounts configured. Run the provider settings to add one.
|
|
3213
3213
|
`);let i=r.resolveCurrentModel(),a=i.id,o=i.provider,s=r.getSelectedProvider(),c=r.getSelectedModelId(),l;if(!n.noBenchmarks){let e=await Upe(t,n.forceRefresh);e.length>0&&(l=e)}let u=tme(r,n,s);if(`error`in u)return D6(u.error);let d=[],f=[];for(let e of u){let t=nme(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($pe(n.name,e,t,!!l))}}return n.jsonMode?{stdout:JSON.stringify(d,null,2)+`
|
|
3214
3214
|
`,stderr:``,exitCode:0}:(n.allVersions||f.push(`Showing latest versions only. Use --all-versions to see all.
|
|
3215
3215
|
`),f.push(rme(o,a,s,c)),{stdout:f.join(`
|
|
@@ -3267,7 +3267,7 @@ Examples:
|
|
|
3267
3267
|
`)}\n`,stderr:``,exitCode:0}}async function wme(e,t,n){if(!t||!n)return{stdout:``,stderr:`oauth-domain add: requires <providerId> and <domain>
|
|
3268
3268
|
`,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 Tme(e,t,n){if(!t||!n)return{stdout:``,stderr:`oauth-domain remove: requires <providerId> and <domain>
|
|
3269
3269
|
`,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>
|
|
3270
|
-
`,exitCode:1}}async function Dme(e,t,n,r){switch(t){case`list`:return Cme(e,n);case`add`:return wme(e,n,r);case`remove`:return Tme(e,n,r);case`clear`:return Eme(e,n);default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${t}"\n${N6()}`,exitCode:1}}}function Ome(){return B(`oauth-domain`,async e=>{if(e.length===0||oi(e))return{stdout:N6(),stderr:``,exitCode:0};let t=V(e);if(`error`in t)return P6(t.error);let[n,r,i]=t.positionals,a=await import(`./account-store-
|
|
3270
|
+
`,exitCode:1}}async function Dme(e,t,n,r){switch(t){case`list`:return Cme(e,n);case`add`:return wme(e,n,r);case`remove`:return Tme(e,n,r);case`clear`:return Eme(e,n);default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${t}"\n${N6()}`,exitCode:1}}}function Ome(){return B(`oauth-domain`,async e=>{if(e.length===0||oi(e))return{stdout:N6(),stderr:``,exitCode:0};let t=V(e);if(`error`in t)return P6(t.error);let[n,r,i]=t.positionals,a=await import(`./account-store-BSIs8eWH.js`).then(e=>e.t);try{return await Dme(a,n,r,i)}catch(e){return P6(e instanceof Error?e.message:String(e))}})}function kme(){return B(`oauth-token`,async(e,t)=>{let{runOAuthToken:n}=await import(`./run-mty6BV1K.js`);return n(e,t)})}const Ame=[`--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...]
|
|
3271
3271
|
|
|
3272
3272
|
VFS paths are served in a new browser tab via the preview service worker.
|
|
3273
3273
|
URLs (http/https/etc.) are opened directly in a new tab.
|
|
@@ -3293,7 +3293,7 @@ Examples:
|
|
|
3293
3293
|
`);let i=!1;try{i=(await t.fs.stat(e)).isDirectory}catch{}let a=XN(e,await Da(t.fs,i?e:La(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 Gme(e,t,n,r){if(!ka(e)&&e.endsWith(`.shtml`)&&t.fs)return Bme(e,t,r.sprinkleManager,r.canOpenWindow,r.openExternal);if(!n.view&&!r.canOpenWindow)return B6(`open: browser APIs are unavailable in this environment
|
|
3294
3294
|
`);if(ka(e))return Vme(e,r.canOpenWindow,r.openExternal);let i=t.fs.resolvePath(t.cwd,e);return n.view?Hme(e,i,t,n.sizeSpec):n.download?Ume(e,i,t,r.hasDom):Wme(i,t,r.canOpenWindow,r.openExternal)}function Kme(e){return B(`open`,async(t,n)=>{if(t.length===0||oi(t,{valueFlags:F6}))return L6();let r=Rme(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:zme(e,l,d)},p=[];for(let e of s){let t=await Gme(e,n,{view:a,download:i,sizeSpec:o},f);if(!t.ok)return t.result;p.push(t.message)}return{stdout:p.join(`
|
|
3295
3295
|
`)+`
|
|
3296
|
-
`,stderr:``,exitCode:0}})}function qme(){return B(`patch`,async(e,t)=>{let{runPatch:n}=await import(`./run-
|
|
3296
|
+
`,stderr:``,exitCode:0}})}function qme(){return B(`patch`,async(e,t)=>{let{runPatch:n}=await import(`./run-DP2klSX1.js`);return n(e,t)})}function H6(e=`pdftk`){return B(e,async(t,n)=>{let{runPdftk:r}=await import(`./run-ChkY2Agc.js`);return r(e,t,n)})}function Jme(){return{stdout:`usage: pdftoppm [options] <input.pdf> [output-prefix]
|
|
3297
3297
|
|
|
3298
3298
|
Rasterize PDF pages to images. Writes <prefix>-<n>.<ext> per page, where <n>
|
|
3299
3299
|
is zero-padded to the digit width of the last page (out-1.png for a 9-page
|
|
@@ -3353,7 +3353,7 @@ Examples:
|
|
|
3353
3353
|
plugin list
|
|
3354
3354
|
plugin info my-plugin
|
|
3355
3355
|
plugin remove my-plugin
|
|
3356
|
-
`}function ohe(e={}){return B(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return K6(ahe());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await che(i,a,e);case`list`:case`ls`:return await fhe(i,e);case`info`:return await phe(i,e);case`validate`:return await mhe(i,a,e,cR(n?.env));case`remove`:case`rm`:case`delete`:return await hhe(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-
|
|
3356
|
+
`}function ohe(e={}){return B(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return K6(ahe());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await che(i,a,e);case`list`:case`ls`:return await fhe(i,e);case`info`:return await phe(i,e);case`validate`:return await mhe(i,a,e,cR(n?.env));case`remove`:case`rm`:case`delete`:return await hhe(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-luCL6DCO.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=ghe(t,e);if(await n.exists(r))return{kind:`local`,root:r};let{parseGitHubRef:i}=await import(`./github-install-DCTLf8fO.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 she(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(she).join(`--`)}`}async function Q6(e,t,n,r){let{fetchRepoZip:i,stripZipPrefix:a,writeZipFilesToDir:o}=await import(`./github-zip-B98l3J_a.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 che(e,t,n){if(oi(e))return K6(`usage: plugin install <path|repo>
|
|
3357
3357
|
|
|
3358
3358
|
Loads the Agent Plugins package at <path>, or downloads it from a GitHub
|
|
3359
3359
|
reference (owner/repo, owner/repo@branch, or
|
|
@@ -3364,19 +3364,19 @@ mcp.json. On success the plugin is recorded in
|
|
|
3364
3364
|
/workspace/.plugins/plugins.json — its skills then surface through the
|
|
3365
3365
|
standard skills discovery, and each supported streamable-http MCP server
|
|
3366
3366
|
is registered in the MCP store as "<plugin>:<server>".
|
|
3367
|
-
`);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-
|
|
3367
|
+
`);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-CyOgmeoj.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 dhe(u,n),g=await uhe(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(lhe(u,h,g,s??o,l.diagnostics))}function lhe(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(`
|
|
3368
3368
|
`)+`
|
|
3369
|
-
`}async function uhe(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-
|
|
3370
|
-
`);let n=J6(`list`,e);if(!(`ok`in n))return n;let{listInstalledPlugins:r}=await import(`./store-
|
|
3369
|
+
`}async function uhe(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-CvgWI8Er.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 dhe(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-CvgWI8Er.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 fhe(e,t){if(oi(e))return K6(`usage: plugin list
|
|
3370
|
+
`);let n=J6(`list`,e);if(!(`ok`in n))return n;let{listInstalledPlugins:r}=await import(`./store-CyOgmeoj.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(`
|
|
3371
3371
|
`)+`
|
|
3372
3372
|
`)}async function phe(e,t){if(oi(e))return K6(`usage: plugin info <name>
|
|
3373
|
-
`);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-
|
|
3373
|
+
`);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-CyOgmeoj.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(`
|
|
3374
3374
|
`)+`
|
|
3375
3375
|
`)}async function mhe(e,t,n,r){if(oi(e))return K6(`usage: plugin validate <path|repo>
|
|
3376
3376
|
`);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(`
|
|
3377
3377
|
`)+`
|
|
3378
3378
|
`)}async function hhe(e,t){if(oi(e))return K6(`usage: plugin remove <name>
|
|
3379
|
-
`);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-
|
|
3379
|
+
`);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-CyOgmeoj.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-CvgWI8Er.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(`
|
|
3380
3380
|
`)+`
|
|
3381
3381
|
`)}function ghe(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(`
|
|
3382
3382
|
`)}const t8=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],_he=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],vhe={running:`R`,pending:`S`,exited:`Z`,killed:`K`},yhe=[`-a`,`-A`,`-e`,`--all`,`-T`,`--tree`],n8=[`-o`,`--columns`];function bhe(e={}){return B(`ps`,async t=>{if(oi(t,{valueFlags:n8}))return Mhe();let n=e.processManager??xhe();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
|
|
@@ -4996,7 +4996,7 @@ pass --wait to block and print the full result.`,xxe=new Set([`list`,`status`,`s
|
|
|
4996
4996
|
`)}`}}function KSe({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}:{},...qSe(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 qSe(e,t,n,r,i){let a=`/scoops/${t}/`;return{visiblePaths:r??(e===`private`?[]:n),writablePaths:i??(e===`private`?[a]:[a,`/shared/`])}}async function JSe(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return s9.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 YSe(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=bn(s);if(!f.ok)return{content:f.error,isError:!0};let p=ISe(l);if(!p.ok)return{content:p.content,isError:p.isError};let m=LSe(u);if(!m.ok)return{content:m.content,isError:!0};let h=RSe(r,t.resolveModelSelection);if(!h.ok)return{content:h.content,isError:h.isError};let g=FSe(n),_=l9(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=kn(g,t.getScoops().map(e=>e.folder));try{let e=KSe({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:Hn(Wn(t.scoop)),canCreateChildren:d===!0}),r=await t.onScoopScoop(e);return s9.info(`Scoop created`,{name:n,folder:v}),i&&t.onFeedScoop?JSe(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 XSe(e,t){let{scoop_name:n}=e,r=c9(t).find(u9(n));if(r?.jid===t.scoop.jid)return{content:`Cannot drop yourself.`,isError:!0};if(!r)return p9(n,t);try{return await t.onDropScoop(r.jid),s9.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 m9(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}function h9(e,t){let n=l9(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 ZSe(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return m9();let{resolved:r,unknown:i}=d9(n,t);return r.length===0?h9(i,t):(t.onMuteScoops(r.map(e=>e.jid)),s9.info(`Scoops muted`,{names:r.map(e=>e.folder)}),{content:`Muted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`})}function QSe(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 $Se(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return m9();let{resolved:r,unknown:i}=d9(n,t);if(r.length===0)return h9(i,t);let a=r.map(e=>e.jid),o=new Map(r.map(e=>[e.jid,e.folder])),s=await t.onUnmuteScoops(a);s9.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(...QSe(s,o)),{content:c.join(`
|
|
4997
4997
|
`)}}function eCe(e,t){return!Array.isArray(e)||e.length===0?m9():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 tCe(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 nCe(e,t){let{scoop_names:n,timeout_ms:r}=e,i=eCe(n,r);if(i)return i;let{resolved:a,unknown:o}=d9(n,t);if(a.length===0)return h9(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 s9.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:tCe(u,o,d,r)}}function rCe(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 iCe(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?(s9.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:rCe(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 aCe(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?(s9.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 oCe(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(`
|
|
4998
4998
|
`)}`}}async function sCe(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),s9.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 cCe(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=>BSe(t,e)}}function lCe(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:[...f9],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=>USe(t,e)}}function uCe(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=>WSe(t,e)}}function dCe(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:()=>GSe(e)}}function fCe(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:[...ir],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=>YSe(t,e)}}function pCe(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=>XSe(t,e)}}function mCe(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=>ZSe(t,e)}}function hCe(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=>$Se(t,e)}}function gCe(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=>nCe(t,e)}}function _Ce(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=>iCe(t,e)}}function vCe(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=>aCe(t,e)}}function yCe(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:()=>oCe(e)}}function bCe(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=>sCe(t,e)}}function xCe(e){let t=[],n=lee(e.scoop);return xn(e.scoop)||(t.push(cCe(e)),e.onSudoRequest&&t.push(lCe(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(fCe(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(uCe(e)),t.push(dCe(e)),e.onDropScoop&&t.push(pCe(e)),e.onMuteScoops&&t.push(mCe(e)),e.onUnmuteScoops&&t.push(hCe(e)),e.onScheduleScoopWait&&t.push(gCe(e)),e.onSudoResolve&&(t.push(_Ce(e)),t.push(vCe(e))),e.onListSudoRequests&&t.push(yCe(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(bCe(e))),t}const SCe=r(`scoop-context`);function CCe(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-CwWcQt6s.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function wCe(e){let{scoop:t,unit:n,callbacks:r}=e,i=xCe({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=[...jSe(e.gatedFs),wSe(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){SCe.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=CCe(e);return e.processManager?Lt(a,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},o,s):Lt(a,void 0,o,s)}const g9=r(`scoop-context`);async function TCe(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();g9.info(`Filesystem ready`,{folder:t.folder}),await Tie(r,t,n,a);let{shell:o,gatedFs:s,skills:c}=await lSe({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 wCe({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 fie(r,n,()=>i.getGlobalMemory());if(!$C(t))return g9.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let f=mie(t,n),p=tw(t,n,d,u,c),m=await e.sessions.restore(),{streamWithSessionId:h,compactFn:g,getCompactionApiKey:_}=await Die(f,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>$C(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=Mn(t);return{kind:`ready`,agent:Cie({model:f,tools:l,systemPrompt:p,messages:m,thinkingLevel:nw(rw()??v.level,f),getApiKey:()=>$C(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 _9=r(`scoop-context`);var ECe=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=nn(e.messages);return this.createdAt=e.createdAt,_9.info(`Restored agent session`,{folder:this.deps.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){_9.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 _9.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=Pi(t);if(n.length===0)return null;let r=nn(n);return t&&(this.createdAt=t.createdAt),_9.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=>{_9.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=>{_9.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){_9.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 DCe(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 OCe(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function v9(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const y9=r(`scoop-context`);var kCe=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;y9.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)&&(y9.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:YC(r)}),!!(t<3&&(await XC(b9(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return nie(e)?(y9.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 Cs(e)?(y9.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),Es(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(!YC(e)||t>=3)return!1;let r=b9(t);return y9.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await XC(r,n)&&!this.deps.isDisposed()}fail(e,t){JC(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function b9(e){return 1e3*2**(e-1)}function ACe(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){y9.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 x9=r(`scoop-context`);var jCe=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=Un(e),this.owner={kind:zn(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 ECe({store:r??null,canonical:c?{store:c,identity:{key:Tr(e),workUnitId:e.jid,workspaceId:wr(e),folder:e.folder,legacyKeys:{agentSessionId:e.jid,chatSessionId:Nn(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 Sie({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new lie({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new uie({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new xie({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 kCe({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 oSe(this.unit,this.scoop,Vn(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return fee(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 TCe({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`),x9.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);x9.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(gie(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),OCe(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(ACe(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=DCe(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(){v9(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&&us(`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:rn,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){x9.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 hie(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=vie(this.agent,this.scoop))}async reloadSkills(){this.agent&&await bie(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){return this.agent?rw()?this.agent.state.thinkingLevel:(this.activeEffortOverride=t,yie(this.agent,e)):`off`}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.sessions.persistNow(),this.disposed=!0,this.idleCompaction?.cancel(),this.runBounds.disarm(),v9(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||aie(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||rie(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 S9=r(`scoop-lifecycle-manager`);var MCe=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 $re(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))??Vn(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return vn(t.values(),e)??Vn(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){S9.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 xr))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`)S9.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{S9.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=Un(t).policy.filesystem;if(a.kind===`restricted`){let e=bn(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new xr(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:yn(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 jCe(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=>{S9.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),S9.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);S9.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),S9.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 S9.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(S9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){S9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}o=this.getContext(e)}if(!o||!s){S9.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`)),S9.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(jn(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=kn(e.folder,n);r!==e.folder&&(S9.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),S9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&AC(`spawn`,e.folder)}catch(n){S9.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){S9.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=>{S9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}inheritModel(e){if(Ln(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?Pn(t):void 0)??bC();n&&En(e,n)}async unregister(e){let t=this.deps.getScoops();for(let n of Bn(t.values(),e))await this.unregister(n.jid);let n=t.get(e);if(n&&n.parentJid===null&&Vn(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=>{S9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),n&&this.deps.getConversationStore()?.delete(Tr(n)),this.deps.getSessionStore()?.delete(e).catch(t=>{S9.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&&S9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),n&&this.deps.getSudoManager()?.forgetScoopPolicies(n.folder),S9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){S9.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;En(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return En(n,r),this.getContext(e)?.updateModel(),S9.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();S9.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=>{S9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),S9.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;Dn(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){S9.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}=Un(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}),AC(`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 On(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:Wn(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,xn(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(xn(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(S9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),AC(`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`),Un(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){S9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(a).catch(e=>{S9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const C9=r(`scoop-message-router`);var NCe=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(C9.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){C9.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}`);AC(`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),C9.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);C9.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){C9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){C9.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(C9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){C9.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{C9.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);C9.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);C9.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,C9.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){C9.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){C9.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){C9.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(C9.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){C9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){C9.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=Fr(Jr(zr(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){C9.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}: ${en(e.content,e.attachments)}`).join(`
|
|
4999
|
-
`),l=s.flatMap(e=>tn(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=Fr(Jr(zr(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);C9.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=>{C9.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=>{C9.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),C9.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=>{C9.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=>{C9.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(),C9.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 w9=r(`orchestrator`),PCe={decision:`deny`};var FCe=class{scoops=new Map;workUnits=new kv(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new pC({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new GC({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 UC({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new LC({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 TC({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=>Ur(e),saveMessage:e=>Ir(e)});lickRegistry=new gC({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 NCe({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=>Ir(e),deleteMessage:e=>Rr(e),clearMessagesForScoop:e=>Kr(e),clearAllMessages:()=>Wr(),getMessagesSince:(e,t,n)=>Hr(e,t,n),setState:(e,t)=>Pr(e,t)},isExternalLickChannel:nv});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new MCe({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=>Nr(e),deleteScoop:e=>Gr(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 xC(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new vb({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 Ny(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new yC(e,t),await this.modelPolicyFile.init(),n(),Yr()),n,{stagePrefix:`orchestrator-init`})}async init(e){await Zr(),this.sharedFs=await xC(e=>br.create({dbName:`slicc-fs`,onRepairProgress:e}),e),this.sessionStore=new Y_,this.conversationStore=new kS,this.fsWatcher=new yr,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=>wn(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),jn(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await Vr(`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 CC({onTaskRun:async(e,t)=>{w9.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(),w9.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);w9.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}`)}mee(e=>this.getSessionCostsForCommand(e)),hee(async()=>{let{refreshBudgetWindow:e}=await import(`./budget-usage-source-BBh4_xMQ.js`).then(e=>e.t);return e()}),this.unregisterExportService=bb(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new Q_;try{await CS({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){w9.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=wn(e)?null:t??null;try{await Nr(e)}catch(t){w9.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=>!Ln(e));if(e.length===0)return;let t=bC(),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?Pn(n):void 0)??t;if(r){En(e,r);try{await Nr(e)}catch(t){w9.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=`${qn.root}/`,r=Hn(dee(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-BcPMLVWo.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:Wn,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(w9.warn(`Guest approval before SudoManager init — failing closed`),PCe)}})}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 Nr(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 Vn(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 Cn(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return vn(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 br.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await cC(this.sharedFs).catch(e=>{w9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new vb({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 Ny(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new yC(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),w9.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 Ur(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(_ee)]}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&&w9.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,w9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new Q_,t=this.sharedFs;return new Ux({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:cS(),snapshotStore:{read:e=>eS(t,e),write:(e,n)=>$x(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.3`})}};const T9=r(`workflow-run-manager`),E9=`/shared/workflow-runs`,D9=1e3;function ICe(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function LCe(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){T9.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=ICe(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),BCe(t,n);let f=i(a.ctx,c),p=VCe(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=>T9.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=`${E9}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(E9,{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);T9.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`?zCe(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){T9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function RCe(e){let t=LCe(e);return globalThis[E7]=t,T9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function zCe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function BCe(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 VCe(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`?UCe(n,t,a?.args??[],r):e===`agent`?WCe(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function UCe(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>D9&&i.logs.splice(0,i.logs.length-D9),r()}return{stdout:``,stderr:``,exitCode:0}}async function WCe(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 GCe=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function KCe(e,t,n){let r=qCe(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=JCe(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function qCe(e){let t=new Map;return O9(t,e.discoveryOrigin),O9(t,e.discoveryUrl),[...t.values()]}function O9(e,t){if(t){k9(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);k9(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!GCe.has(e)))k9(e,t,1,`substring`)}catch{}}}function k9(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 JCe(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=XCe(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)YCe(a,e)&&(r+=e.weight*o)}return r}function YCe(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 XCe(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}var ZCe=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=M9(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:j9,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===j9)throw new or(`ENOTDIR`,`not a directory`,e);let n=N9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);return A9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new or(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=M9(e);if(t.length===1&&t[0]===j9)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new or(`EISDIR`,`is a directory`,e);let n=N9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!A9.includes(r))throw new or(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new or(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=M9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===j9)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=N9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=N9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!A9.includes(r))throw new or(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new or(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new or(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new or(`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 or(`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:P9(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:F9(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
4999
|
+
`),l=s.flatMap(e=>tn(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=Fr(Jr(zr(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);C9.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=>{C9.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=>{C9.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),C9.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=>{C9.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=>{C9.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(),C9.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 w9=r(`orchestrator`),PCe={decision:`deny`};var FCe=class{scoops=new Map;workUnits=new kv(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new pC({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new GC({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 UC({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new LC({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 TC({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=>Ur(e),saveMessage:e=>Ir(e)});lickRegistry=new gC({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 NCe({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=>Ir(e),deleteMessage:e=>Rr(e),clearMessagesForScoop:e=>Kr(e),clearAllMessages:()=>Wr(),getMessagesSince:(e,t,n)=>Hr(e,t,n),setState:(e,t)=>Pr(e,t)},isExternalLickChannel:nv});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new MCe({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=>Nr(e),deleteScoop:e=>Gr(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 xC(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new vb({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 Ny(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new yC(e,t),await this.modelPolicyFile.init(),n(),Yr()),n,{stagePrefix:`orchestrator-init`})}async init(e){await Zr(),this.sharedFs=await xC(e=>br.create({dbName:`slicc-fs`,onRepairProgress:e}),e),this.sessionStore=new Y_,this.conversationStore=new kS,this.fsWatcher=new yr,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=>wn(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),jn(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await Vr(`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 CC({onTaskRun:async(e,t)=>{w9.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(),w9.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);w9.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}`)}mee(e=>this.getSessionCostsForCommand(e)),hee(async()=>{let{refreshBudgetWindow:e}=await import(`./budget-usage-source--h4cY6Ul.js`).then(e=>e.t);return e()}),this.unregisterExportService=bb(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new Q_;try{await CS({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){w9.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=wn(e)?null:t??null;try{await Nr(e)}catch(t){w9.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=>!Ln(e));if(e.length===0)return;let t=bC(),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?Pn(n):void 0)??t;if(r){En(e,r);try{await Nr(e)}catch(t){w9.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=`${qn.root}/`,r=Hn(dee(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-Blbo1tMy.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:Wn,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(w9.warn(`Guest approval before SudoManager init — failing closed`),PCe)}})}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 Nr(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 Vn(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 Cn(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return vn(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 br.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await cC(this.sharedFs).catch(e=>{w9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new vb({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 Ny(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new yC(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),w9.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 Ur(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(_ee)]}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&&w9.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,w9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new Q_,t=this.sharedFs;return new Ux({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:cS(),snapshotStore:{read:e=>eS(t,e),write:(e,n)=>$x(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.4`})}};const T9=r(`workflow-run-manager`),E9=`/shared/workflow-runs`,D9=1e3;function ICe(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function LCe(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){T9.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=ICe(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),BCe(t,n);let f=i(a.ctx,c),p=VCe(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=>T9.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=`${E9}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(E9,{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);T9.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`?zCe(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){T9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function RCe(e){let t=LCe(e);return globalThis[E7]=t,T9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function zCe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function BCe(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 VCe(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`?UCe(n,t,a?.args??[],r):e===`agent`?WCe(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function UCe(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>D9&&i.logs.splice(0,i.logs.length-D9),r()}return{stdout:``,stderr:``,exitCode:0}}async function WCe(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 GCe=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function KCe(e,t,n){let r=qCe(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=JCe(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function qCe(e){let t=new Map;return O9(t,e.discoveryOrigin),O9(t,e.discoveryUrl),[...t.values()]}function O9(e,t){if(t){k9(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);k9(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!GCe.has(e)))k9(e,t,1,`substring`)}catch{}}}function k9(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 JCe(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=XCe(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)YCe(a,e)&&(r+=e.weight*o)}return r}function YCe(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 XCe(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}var ZCe=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=M9(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:j9,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===j9)throw new or(`ENOTDIR`,`not a directory`,e);let n=N9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);return A9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new or(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=M9(e);if(t.length===1&&t[0]===j9)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new or(`EISDIR`,`is a directory`,e);let n=N9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!A9.includes(r))throw new or(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new or(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=M9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===j9)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=N9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=N9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!A9.includes(r))throw new or(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new or(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new or(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new or(`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 or(`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:P9(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:F9(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
5000
5000
|
`}renderProcFile(e,t){if(e===1)return nwe(t);let n=this.pm.get(e);switch(t){case`status`:return QCe(n);case`cmdline`:return $Ce(n);case`cwd`:return ewe(n);case`stat`:return twe(n)}}};const A9=[`status`,`cmdline`,`cwd`,`stat`],j9=`table`;function M9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function N9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function QCe(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${P9(e.status)} (${e.status})`,`Owner:\t${F9(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(`
|
|
5001
5001
|
`)+`
|
|
5002
5002
|
`}function $Ce(e){return e.argv.join(`\0`)+`\0`}function ewe(e){return e.cwd+`
|
|
@@ -5005,7 +5005,7 @@ pass --wait to block and print the full result.`,xxe=new Set([`list`,`status`,`s
|
|
|
5005
5005
|
`)+`
|
|
5006
5006
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
5007
5007
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
5008
|
-
`}}function rwe(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(nW(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(!ZU(n.token))return;let a=i.get(n.id);if(a){r({type:rW,id:n.id}),a.result&&r({type:iW,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:rW,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:iW,id:n.id,...e})};(cW(n)?dW(n):tW(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 I9(){return globalThis}function iwe(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 awe(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 owe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}swe(e,t)}function swe(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=Vn(r),a=e.type===`discovery`&&!e.targetScoop?KCe(e,i.filter(Ay),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?Yc(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!Ay(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=gv(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=iwe(e),l=awe(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 cwe(e,t,n,r,i){let a=new _a,o=new FCe(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a);let s=zt(),c=i.capabilityBroker??Vy(s,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});o.setCapabilityBroker(c),ur(c),I9().__slicc_pm=a,AJ(MJ()),I9().__slicc_browser=t,await n.bind(o,t);let l=Ar(()=>n.emitTrayRuntimeStatus()),u=qv(()=>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 lwe(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
|
|
5009
|
-
`,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 pwe(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 mwe(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 xy(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})},{...hwe(t),isOwnTab:yy(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function hwe(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:()=>Sy()}}function gwe(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-BkELRMZC.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 _we(){$r(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-DlCzP4lD.js`);return e()})}function vwe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-DlCzP4lD.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 ywe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DqSIi75u.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 bwe(e){return e===`node-rest`}async function xwe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);_we();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await cwe(t,n,r,i,e);if(s(`orchestrator-ready`),f?hn(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new ZCe(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await lwe(l,e,o);s(`lick-manager-ready`),f&&dwe({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),I9().__slicc_lickManager=m;let{wsBridge:h,wsRegistry:g}=await fwe({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});I9().__slicc_wsSubscribers=g;let _=null;bwe(p.adapter)&&(_=await pwe(m,o,e.localLickWsUrl??null,f));let v=mwe(n,m,o,e.appPageUrl);f&&gwe(f,m,o),a||await uwe(l),s(`cone-bootstrapped`),f&&vwe(m,o);let y=null,b=null;f&&({bshWatchdogStop:y,scriptCatalogDispose:b}=await ywe(f,n,o));let x=null;f&&e.syncFsChannelNonce&&(x=rwe({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 Swe({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 Swe(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)}Cwe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function Cwe(e){let t=I9();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,AJ(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 L9=`x-bypass-llm-proxy`;function wwe(e,t,n){return t?(r,i)=>{if(!Twe(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(L9)||a.set(L9,`1`),e(r,{...i,headers:a})}:e}function Twe(e,t,n){if(Dwe(e,t))return!0;let r=n?.()??null;return r?Ewe(e,r,t):!1}function Ewe(e,t,n){let r=R9(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 Dwe(e,t){let n=R9(e);try{return new URL(n,t).origin===t}catch{return!0}}function R9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Owe(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 kwe=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(!Awe(e)||e.source!==`panel`)return;let t=e.payload;jwe(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=$a(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?z9(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,z9(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 Awe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function z9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function jwe(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 Mwe=class extends W7{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 Nwe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new kwe({transport:t,processManager:i,createShell:(a,o)=>new Mwe(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Or},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function Pwe(e){return typeof e==`string`&&e.startsWith(`No API key configured`)}function Fwe(e){if(!e)return!1;let t=e.toLowerCase();return t.includes(`the provided model identifier is invalid`)||t.includes(`model not allowed`)}function Iwe(e){return e?e.toLowerCase().includes(`please log in again`):!1}function Lwe(e){return e?e.toLowerCase().includes(`quota_exceeded`):!1}function B9(e){return Pwe(e)||Fwe(e)||Iwe(e)||Lwe(e)}let V9=null,H9=!1;function Rwe(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function U9(e){return Rwe()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function zwe(e={}){if(!H9&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){Qxe(Bwe),kC(Vwe),eie(W9);try{let t=U9(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(V9=(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`?(V9=(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`),Wwe(),V9=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),H9=!0,V9&&V9(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function Bwe(e){V9?.(`fill`,{source:e})}function W9(e,t){let n=t;if(typeof n==`string`){if(B9(n))return;let e=G9(n);if(e===null)return;n=e}V9?.(`error`,{source:e,target:n})}function Vwe(e,t,n){if(e===`error`){let e=n;if(typeof e==`string`){if(B9(e))return;let t=G9(e);if(t===null)return;e=t}V9?.(`error`,{source:`scoop:${t}`,target:e});return}V9?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function Hwe(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(`
|
|
5008
|
+
`}}function rwe(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(nW(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(!ZU(n.token))return;let a=i.get(n.id);if(a){r({type:rW,id:n.id}),a.result&&r({type:iW,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:rW,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:iW,id:n.id,...e})};(cW(n)?dW(n):tW(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 I9(){return globalThis}function iwe(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 awe(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 owe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}swe(e,t)}function swe(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=Vn(r),a=e.type===`discovery`&&!e.targetScoop?KCe(e,i.filter(Ay),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?Yc(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!Ay(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=gv(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=iwe(e),l=awe(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 cwe(e,t,n,r,i){let a=new _a,o=new FCe(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a);let s=zt(),c=i.capabilityBroker??Vy(s,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});o.setCapabilityBroker(c),ur(c),I9().__slicc_pm=a,AJ(MJ()),I9().__slicc_browser=t,await n.bind(o,t);let l=Ar(()=>n.emitTrayRuntimeStatus()),u=qv(()=>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 lwe(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--h4cY6Ul.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??owe,l={orchestrator:e,lickManager:s,log:n};return s.setEventHandler(e=>c(e,l)),s}async function uwe(e){let t=e.getScoops();Vn(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 dwe(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;RCe({sharedFs:i,getStartingRoot:e=>{let n=Vn(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)=>PJ(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>D7().slice(10,22),splitResult:(e,t)=>O7(e,t)})}async function fwe(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))+`
|
|
5009
|
+
`,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 pwe(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 mwe(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 xy(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})},{...hwe(t),isOwnTab:yy(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function hwe(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:()=>Sy()}}function gwe(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-Ds6xJnFc.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 _we(){$r(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-DgoklRjO.js`);return e()})}function vwe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-DgoklRjO.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 ywe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DqSIi75u.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 bwe(e){return e===`node-rest`}async function xwe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);_we();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await cwe(t,n,r,i,e);if(s(`orchestrator-ready`),f?hn(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new ZCe(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await lwe(l,e,o);s(`lick-manager-ready`),f&&dwe({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),I9().__slicc_lickManager=m;let{wsBridge:h,wsRegistry:g}=await fwe({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});I9().__slicc_wsSubscribers=g;let _=null;bwe(p.adapter)&&(_=await pwe(m,o,e.localLickWsUrl??null,f));let v=mwe(n,m,o,e.appPageUrl);f&&gwe(f,m,o),a||await uwe(l),s(`cone-bootstrapped`),f&&vwe(m,o);let y=null,b=null;f&&({bshWatchdogStop:y,scriptCatalogDispose:b}=await ywe(f,n,o));let x=null;f&&e.syncFsChannelNonce&&(x=rwe({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 Swe({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 Swe(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)}Cwe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function Cwe(e){let t=I9();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,AJ(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 L9=`x-bypass-llm-proxy`;function wwe(e,t,n){return t?(r,i)=>{if(!Twe(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(L9)||a.set(L9,`1`),e(r,{...i,headers:a})}:e}function Twe(e,t,n){if(Dwe(e,t))return!0;let r=n?.()??null;return r?Ewe(e,r,t):!1}function Ewe(e,t,n){let r=R9(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 Dwe(e,t){let n=R9(e);try{return new URL(n,t).origin===t}catch{return!0}}function R9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Owe(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 kwe=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(!Awe(e)||e.source!==`panel`)return;let t=e.payload;jwe(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=$a(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?z9(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,z9(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 Awe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function z9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function jwe(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 Mwe=class extends W7{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 Nwe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new kwe({transport:t,processManager:i,createShell:(a,o)=>new Mwe(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Or},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function Pwe(e){return typeof e==`string`&&e.startsWith(`No API key configured`)}function Fwe(e){if(!e)return!1;let t=e.toLowerCase();return t.includes(`the provided model identifier is invalid`)||t.includes(`model not allowed`)}function Iwe(e){return e?e.toLowerCase().includes(`please log in again`):!1}function Lwe(e){return e?e.toLowerCase().includes(`quota_exceeded`):!1}function B9(e){return Pwe(e)||Fwe(e)||Iwe(e)||Lwe(e)}let V9=null,H9=!1;function Rwe(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function U9(e){return Rwe()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function zwe(e={}){if(!H9&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){Qxe(Bwe),kC(Vwe),eie(W9);try{let t=U9(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(V9=(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`?(V9=(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`),Wwe(),V9=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),H9=!0,V9&&V9(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function Bwe(e){V9?.(`fill`,{source:e})}function W9(e,t){let n=t;if(typeof n==`string`){if(B9(n))return;let e=G9(n);if(e===null)return;n=e}V9?.(`error`,{source:e,target:n})}function Vwe(e,t,n){if(e===`error`){let e=n;if(typeof e==`string`){if(B9(e))return;let t=G9(e);if(t===null)return;e=t}V9?.(`error`,{source:`scoop:${t}`,target:e});return}V9?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function Hwe(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(`
|
|
5010
5010
|
`).filter(e=>!Hwe(e)).join(`
|
|
5011
|
-
`).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 Uwe(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 Wwe(){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=Uwe(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 Gwe(e){let t=new Kwe(e);return t.start(),{stop:()=>t.dispose()}}var Kwe=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(!qwe(e)||e.source!==`panel`)return;let t=e.payload;if(Jwe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(Ywe(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(Xwe(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 or(`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 or(`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(Zwe(e.type),e.requestId,new or(`EACCES`,`vfs-rpc-host has no writable backend wired`),Qwe(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 or(`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 or(`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 or(`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 qwe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Jwe(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 Ywe(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 Xwe(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function Zwe(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 Qwe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof or?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function $we(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=wwe(e.bind(globalThis),t,eTe)}function eTe(){let e=Se();if(!e)return null;try{return new URL(e).origin}catch{return null}}function tTe(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 nTe=Owe(e=>aTe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&nTe.handle(e.data)});function rTe(e){let t=Os(e.pageBuildId,`6.141.3-mtt65avy`);return()=>{t&&W9(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.141.3-mtt65avy`)}}function iTe(e){$we(),xe(e.localApiBaseUrl??null),A(e.bridgeToken??null),wJ(e.syncFsBridgeEnabled??!1),qee(e.pageLoadedAt??null),j(e.extensionDelegateId??null),tTe(e.localStorageSeed??{}),e.flagFloat&&gs(e.flagFloat)}async function aTe(e){Ts(e.instanceId);let t=rTe(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{iTe(e),zwe().then(t).catch(()=>{}),await p(),n(`providers-registered`);let r=qc(e.kernelPort),i=new fy(r),a=fy.createCallbacks(i),o=new Jc(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new cte(o);Y9=await xwe({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 Yee)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(ute(u));let m=await sTe({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){oTe(e.kernelPort,t)}}function oTe(e,t){Ds(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 sTe(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=Nwe({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=Gwe({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await cTe(t,e.instanceId);return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a}}async function cTe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-B14FEqf-.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())});
|
|
5011
|
+
`).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 Uwe(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 Wwe(){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=Uwe(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 Gwe(e){let t=new Kwe(e);return t.start(),{stop:()=>t.dispose()}}var Kwe=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(!qwe(e)||e.source!==`panel`)return;let t=e.payload;if(Jwe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(Ywe(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(Xwe(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 or(`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 or(`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(Zwe(e.type),e.requestId,new or(`EACCES`,`vfs-rpc-host has no writable backend wired`),Qwe(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 or(`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 or(`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 or(`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 qwe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Jwe(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 Ywe(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 Xwe(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function Zwe(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 Qwe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof or?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function $we(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=wwe(e.bind(globalThis),t,eTe)}function eTe(){let e=Se();if(!e)return null;try{return new URL(e).origin}catch{return null}}function tTe(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 nTe=Owe(e=>aTe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&nTe.handle(e.data)});function rTe(e){let t=Os(e.pageBuildId,`6.141.4-mtt9nzun`);return()=>{t&&W9(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.141.4-mtt9nzun`)}}function iTe(e){$we(),xe(e.localApiBaseUrl??null),A(e.bridgeToken??null),wJ(e.syncFsBridgeEnabled??!1),qee(e.pageLoadedAt??null),j(e.extensionDelegateId??null),tTe(e.localStorageSeed??{}),e.flagFloat&&gs(e.flagFloat)}async function aTe(e){Ts(e.instanceId);let t=rTe(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{iTe(e),zwe().then(t).catch(()=>{}),await p(),n(`providers-registered`);let r=qc(e.kernelPort),i=new fy(r),a=fy.createCallbacks(i),o=new Jc(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new cte(o);Y9=await xwe({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 Yee)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(ute(u));let m=await sTe({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){oTe(e.kernelPort,t)}}function oTe(e,t){Ds(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 sTe(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=Nwe({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=Gwe({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await cTe(t,e.instanceId);return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a}}async function cTe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-B14FEqf-.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())});
|